[ { "problem_id": 1, "explanations": { "1": "We can use a hash table $\\textit{d}$ to store each element and its corresponding index.\n\nTraverse the array $\\textit{nums}$, for the current element $\\textit{nums}[i]$, we first check if $\\textit{target} - \\textit{nums}[i]$ is in the hash table $\\textit{d}$. If it is in $\\textit{d}$, it means the $\\textit{target}$ value has been found, and we return the indices of $\\textit{target} - \\textit{nums}[i]$ and $i$.\n\nTime complexity is $O(n)$, and space complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2, "explanations": { "1": "We traverse two linked lists $l_1$ and $l_2$ at the same time, and use the variable $carry$ to indicate whether there is a carry.\n\nEach time we traverse, we take out the current bit of the corresponding linked list, calculate the sum with the carry $carry$, and then update the value of the carry. Then we add the current bit to the answer linked list. If both linked lists are traversed, and the carry is $0$, the traversal ends.\n\nFinally, we return the head node of the answer linked list.\n\nThe time complexity is $O(\\max (m, n))$, where $m$ and $n$ are the lengths of the two linked lists. We need to traverse the entire position of the two linked lists, and each position only needs $O(1)$ time. Ignoring the space consumption of the answer, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\max (m, n))", "space_complexity": "O(1)" }, { "problem_id": 3, "explanations": { "1": "We can use two pointers $l$ and $r$ to maintain a sliding window that always satisfies the condition of having no repeating characters within the window. Initially, both $l$ and $r$ point to the first character of the string. We use a hash table or an array of length $128$ called $\\textit{cnt}$ to record the number of occurrences of each character, where $\\textit{cnt}[c]$ represents the number of occurrences of character $c$.\n\nNext, we move the right pointer $r$ one step at a time. Each time we move it, we increment the value of $\\textit{cnt}[s[r]]$ by $1$, and then check if the value of $\\textit{cnt}[s[r]]$ is greater than $1$ within the current window $[l, r]$. If it is greater than $1$, it means there are repeating characters within the current window, and we need to move the left pointer $l$ until there are no repeating characters within the window. Then, we update the answer $\\textit{ans} = \\max(\\textit{ans}, r - l + 1)$.\n\nFinally, we return the answer $\\textit{ans}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(|\\Sigma|)$, where $\\Sigma$ represents the character set, and the size of $\\Sigma$ is $128$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 4, "explanations": { "1": "The problem requires the time complexity of the algorithm to be $O(\\log (m + n))$, so we cannot directly traverse the two arrays, but need to use the binary search method.\n\nIf $m + n$ is odd, then the median is the $\\left\\lfloor\\frac{m + n + 1}{2}\\right\\rfloor$-th number; if $m + n$ is even, then the median is the average of the $\\left\\lfloor\\frac{m + n + 1}{2}\\right\\rfloor$-th and the $\\left\\lfloor\\frac{m + n + 2}{2}\\right\\rfloor$-th numbers. In fact, we can unify it as the average of the $\\left\\lfloor\\frac{m + n + 1}{2}\\right\\rfloor$-th and the $\\left\\lfloor\\frac{m + n + 2}{2}\\right\\rfloor$-th numbers.\n\nTherefore, we can design a function $f(i, j, k)$, which represents the $k$-th smallest number in the interval $[i, m)$ of array $nums1$ and the interval $[j, n)$ of array $nums2$. The median is the average of $f(0, 0, \\left\\lfloor\\frac{m + n + 1}{2}\\right\\rfloor)$ and $f(0, 0, \\left\\lfloor\\frac{m + n + 2}{2}\\right\\rfloor)$.\n\nThe implementation idea of the function $f(i, j, k)$ is as follows:\n\n- If $i \\geq m$, it means that the interval $[i, m)$ of array $nums1$ is empty, so directly return $nums2[j + k - 1]$;\n- If $j \\geq n$, it means that the interval $[j, n)$ of array $nums2$ is empty, so directly return $nums1[i + k - 1]$;\n- If $k = 1$, it means to find the first number, so just return the minimum of $nums1[i]$ and $nums2[j]$;\n- Otherwise, we find the $\\left\\lfloor\\frac{k}{2}\\right\\rfloor$-th number in the two arrays, denoted as $x$ and $y$. (Note, if a certain array does not have the $\\left\\lfloor\\frac{k}{2}\\right\\rfloor$-th number, then we regard the $\\left\\lfloor\\frac{k}{2}\\right\\rfloor$-th number as $+\\infty$.) Compare the size of $x$ and $y$:\n - If $x \\leq y$, it means that the $\\left\\lfloor\\frac{k}{2}\\right\\rfloor$-th number of array $nums1$ cannot be the $k$-th smallest number, so we can exclude the interval $[i, i + \\left\\lfloor\\frac{k}{2}\\right\\rfloor)$ of array $nums1$, and recursively call $f(i + \\left\\lfloor\\frac{k}{2}\\right\\rfloor, j, k - \\left\\lfloor\\frac{k}{2}\\right\\rfloor)$.\n - If $x > y$, it means that the $\\left\\lfloor\\frac{k}{2}\\right\\rfloor$-th number of array $nums2$ cannot be the $k$-th smallest number, so we can exclude the interval $[j, j + \\left\\lfloor\\frac{k}{2}\\right\\rfloor)$ of array $nums2$, and recursively call $f(i, j + \\left\\lfloor\\frac{k}{2}\\right\\rfloor, k - \\left\\lfloor\\frac{k}{2}\\right\\rfloor)$.\n\nThe time complexity is $O(\\log(m + n))$, and the space complexity is $O(\\log(m + n))$. Here, $m$ and $n$ are the lengths of arrays $nums1$ and $nums2$ respectively." }, "is_english": true, "time_complexity": "O(\\log (m + n))", "space_complexity": "O(\\log(m + n))" }, { "problem_id": 5, "explanations": { "1": "We define $f[i][j]$ to represent whether the string $s[i..j]$ is a palindrome, initially $f[i][j] = true$.\n\nNext, we define variables $k$ and $mx$, where $k$ represents the starting position of the longest palindrome, and $mx$ represents the length of the longest palindrome. Initially, $k = 0$, $mx = 1$.\n\nConsidering $f[i][j]$, if $s[i] = s[j]$, then $f[i][j] = f[i + 1][j - 1]$; otherwise, $f[i][j] = false$. If $f[i][j] = true$ and $mx < j - i + 1$, then we update $k = i$, $mx = j - i + 1$.\n\nSince $f[i][j]$ depends on $f[i + 1][j - 1]$, we need to ensure that $i + 1$ is before $j - 1$, so we need to enumerate $i$ from large to small, and enumerate $j$ from small to large.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ is the length of the string $s$.", "2": "We can enumerate the midpoint of the palindrome, spread to both sides, and find the longest palindrome.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(1)$. Here, $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 6, "explanations": { "1": "We use a 2D array $g$ to simulate the process of arranging the string in a zigzag pattern, where $g[i][j]$ represents the character at row $i$ and column $j$. Initially, $i = 0$. We also define a direction variable $k$, initially $k = -1$, which means moving upwards.\n\nWe traverse the string $s$ from left to right. For each character $c$, we append it to $g[i]$. If $i = 0$ or $i = \\textit{numRows} - 1$, it means the current character is at a turning point in the zigzag pattern, so we reverse the value of $k$, i.e., $k = -k$. Then, we update $i$ to $i + k$, which means moving up or down one row. Continue traversing the next character until the end of the string $s$. Finally, we return the concatenation of all rows in $g$ as the result.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 7, "explanations": { "1": "Let's denote $mi$ and $mx$ as $-2^{31}$ and $2^{31} - 1$ respectively, then the reverse result of $x$, $ans$, needs to satisfy $mi \\le ans \\le mx$.\n\nWe can continuously take the remainder of $x$ to get the last digit $y$ of $x$, and add $y$ to the end of $ans$. Before adding $y$, we need to check if $ans$ overflows. That is, check whether $ans \\times 10 + y$ is within the range $[mi, mx]$.\n\nIf $x \\gt 0$, it needs to satisfy $ans \\times 10 + y \\leq mx$, that is, $ans \\times 10 + y \\leq \\left \\lfloor \\frac{mx}{10} \\right \\rfloor \\times 10 + 7$. Rearranging gives $(ans - \\left \\lfloor \\frac{mx}{10} \\right \\rfloor) \\times 10 \\leq 7 - y$.\n\nNext, we discuss the conditions for the inequality to hold:\n\n- When $ans \\lt \\left \\lfloor \\frac{mx}{10} \\right \\rfloor$, the inequality obviously holds;\n- When $ans = \\left \\lfloor \\frac{mx}{10} \\right \\rfloor$, the necessary and sufficient condition for the inequality to hold is $y \\leq 7$. If $ans = \\left \\lfloor \\frac{mx}{10} \\right \\rfloor$ and we can still add numbers, it means that the number is at the highest digit, that is, $y$ must not exceed $2$, therefore, the inequality must hold;\n- When $ans \\gt \\left \\lfloor \\frac{mx}{10} \\right \\rfloor$, the inequality obviously does not hold.\n\nIn summary, when $x \\gt 0$, the necessary and sufficient condition for the inequality to hold is $ans \\leq \\left \\lfloor \\frac{mx}{10} \\right \\rfloor$.\n\nSimilarly, when $x \\lt 0$, the necessary and sufficient condition for the inequality to hold is $ans \\geq \\left \\lfloor \\frac{mi}{10} \\right \\rfloor$.\n\nTherefore, we can check whether $ans$ overflows by checking whether $ans$ is within the range $[\\left \\lfloor \\frac{mi}{10} \\right \\rfloor, \\left \\lfloor \\frac{mx}{10} \\right \\rfloor]$. If it overflows, return $0$. Otherwise, add $y$ to the end of $ans$, and then remove the last digit of $x$, that is, $x \\gets \\left \\lfloor \\frac{x}{10} \\right \\rfloor$.\n\nThe time complexity is $O(\\log |x|)$, where $|x|$ is the absolute value of $x$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log |x|)", "space_complexity": "O(1)" }, { "problem_id": 8, "explanations": { "1": "First, we determine whether the string is empty. If it is, we directly return $0$.\n\nOtherwise, we need to traverse the string, skip the leading spaces, and determine whether the first non-space character is a positive or negative sign.\n\nThen we traverse the following characters. If it is a digit, we judge whether adding this digit will cause integer overflow. If it does, we return the result according to the positive or negative sign. Otherwise, we add the digit to the result. We continue to traverse the following characters until we encounter a non-digit character or the traversal ends.\n\nAfter the traversal ends, we return the result according to the positive or negative sign.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string. We only need to process all characters in turn. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 9, "explanations": { "1": "First, we determine special cases:\n\n- If $x < 0$, then $x$ is not a palindrome, directly return `false`;\n- If $x > 0$ and the last digit of $x$ is $0$, then $x$ is not a palindrome, directly return `false`;\n- If the last digit of $x$ is not $0$, then $x$ might be a palindrome, continue the following steps.\n\nWe reverse the second half of $x$ and compare it with the first half. If they are equal, then $x$ is a palindrome, otherwise, $x$ is not a palindrome.\n\nFor example, for $x = 1221$, we can reverse the second half from \"21\" to \"12\" and compare it with the first half \"12\". Since they are equal, we know that $x$ is a palindrome.\n\nLet's see how to reverse the second half.\n\nFor the number $1221$, if we perform $1221 \\bmod 10$, we will get the last digit $1$. To get the second last digit, we can first remove the last digit from $1221$ by dividing by $10$, $1221 / 10 = 122$, then get the remainder of the previous result divided by $10$, $122 \\bmod 10 = 2$, to get the second last digit.\n\nIf we continue this process, we will get more reversed digits.\n\nBy continuously multiplying the last digit to the variable $y$, we can get the number in reverse order.\n\nIn the code implementation, we can repeatedly \"take out\" the last digit of $x$ and \"add\" it to the end of $y$, loop until $y \\ge x$. If at this time $x = y$, or $x = y / 10$, then $x$ is a palindrome.\n\nThe time complexity is $O(\\log_{10}(n))$, where $n$ is $x$. For each iteration, we will divide the input by $10$, so the time complexity is $O(\\log_{10}(n))$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log_{10}(n))", "space_complexity": "O(1)" }, { "problem_id": 10, "explanations": { "1": "We design a function $dfs(i, j)$, which indicates whether the $i$-th character of $s$ matches the $j$-th character of $p$. The answer is $dfs(0, 0)$.\n\nThe calculation process of the function $dfs(i, j)$ is as follows:\n\n- If $j$ has reached the end of $p$, then if $i$ has also reached the end of $s$, the match is successful, otherwise, the match fails.\n- If the next character of $j$ is `'*'`, we can choose to match $0$ $s[i]$ characters, which is $dfs(i, j + 2)$. If $i \\lt m$ and $s[i]$ matches $p[j]$, we can choose to match $1$ $s[i]$ character, which is $dfs(i + 1, j)$.\n- If the next character of $j$ is not `'*'`, then if $i \\lt m$ and $s[i]$ matches $p[j]$, it is $dfs(i + 1, j + 1)$. Otherwise, the match fails.\n\nDuring the process, we can use memoization search to avoid repeated calculations.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the lengths of $s$ and $p$ respectively.", "2": "We can convert the memoization search in Solution 1 into dynamic programming.\n\nDefine $f[i][j]$ to represent whether the first $i$ characters of string $s$ match the first $j$ characters of string $p$. The answer is $f[m][n]$. Initialize $f[0][0] = true$, indicating that the empty string and the empty regular expression match.\n\nSimilar to Solution 1, we can discuss different cases.\n\n- If $p[j - 1]$ is `'*'`, we can choose to match $0$ $s[i - 1]$ characters, which is $f[i][j] = f[i][j - 2]$. If $s[i - 1]$ matches $p[j - 2]$, we can choose to match $1$ $s[i - 1]$ character, which is $f[i][j] = f[i][j] \\lor f[i - 1][j]$.\n- If $p[j - 1]$ is not `'*'`, then if $s[i - 1]$ matches $p[j - 1]$, it is $f[i][j] = f[i - 1][j - 1]$. Otherwise, the match fails.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the lengths of $s$ and $p$ respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 11, "explanations": { "1": "We use two pointers $l$ and $r$ to point to the left and right ends of the array, respectively, i.e., $l = 0$ and $r = n - 1$, where $n$ is the length of the array.\n\nNext, we use a variable $\\textit{ans}$ to record the maximum capacity of the container, initially set to $0$.\n\nThen, we start a loop. In each iteration, we calculate the current capacity of the container, i.e., $\\textit{min}(height[l], height[r]) \\times (r - l)$, and compare it with $\\textit{ans}$, assigning the larger value to $\\textit{ans}$. Then, we compare the values of $height[l]$ and $height[r]$. If $\\textit{height}[l] < \\textit{height}[r]$, moving the $r$ pointer will not improve the result because the height of the container is determined by the shorter vertical line, so we move the $l$ pointer. Otherwise, we move the $r$ pointer.\n\nAfter the iteration, we return $\\textit{ans}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{height}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 12, "explanations": { "1": "We can first list all possible symbols $cs$ and their corresponding values $vs$, then enumerate each value $vs[i]$ from large to small. Each time, we use as many symbols $cs[i]$ corresponding to this value as possible, until the number $num$ becomes $0$.\n\nThe time complexity is $O(m)$, and the space complexity is $O(m)$. Here, $m$ is the number of symbols." }, "is_english": true, "time_complexity": "O(m)", "space_complexity": "O(m)" }, { "problem_id": 13, "explanations": { "1": "First, we use a hash table $d$ to record the numerical value corresponding to each character. Then, we traverse the string $s$ from left to right. If the numerical value corresponding to the current character is less than the numerical value corresponding to the character on the right, we subtract the numerical value corresponding to the current character. Otherwise, we add the numerical value corresponding to the current character.\n\nThe time complexity is $O(n)$, and the space complexity is $O(m)$. Here, $n$ and $m$ are the length of the string $s$ and the size of the character set, respectively." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(m)" }, { "problem_id": 14, "explanations": { "1": "We use the first string $strs[0]$ as a benchmark, and compare whether the $i$-th character of the subsequent strings is the same as the $i$-th character of $strs[0]$. If they are the same, we continue to compare the next character. Otherwise, we return the first $i$ characters of $strs[0]$.\n\nIf the traversal ends, it means that the first $i$ characters of all strings are the same, and we return $strs[0]$.\n\nThe time complexity is $O(n \\times m)$, where $n$ and $m$ are the length of the string array and the minimum length of the strings, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times m)", "space_complexity": "O(1)" }, { "problem_id": 15, "explanations": { "1": "We notice that the problem does not require us to return the triplet in order, so we might as well sort the array first, which makes it easy to skip duplicate elements.\n\nNext, we enumerate the first element of the triplet $nums[i]$, where $0 \\leq i \\lt n - 2$. For each $i$, we can find $j$ and $k$ satisfying $nums[i] + nums[j] + nums[k] = 0$ by maintaining two pointers $j = i + 1$ and $k = n - 1$. In the enumeration process, we need to skip duplicate elements to avoid duplicate triplets.\n\nThe specific judgment logic is as follows:\n\nIf $i \\gt 0$ and $nums[i] = nums[i - 1]$, it means that the element currently enumerated is the same as the previous element, we can skip it directly, because it will not produce new results.\n\nIf $nums[i] \\gt 0$, it means that the element currently enumerated is greater than $0$, so the sum of three numbers must not be equal to $0$, and the enumeration ends.\n\nOtherwise, we let the left pointer $j = i + 1$, and the right pointer $k = n - 1$. When $j \\lt k$, the loop is executed, and the sum of three numbers $x = nums[i] + nums[j] + nums[k]$ is calculated and compared with $0$:\n\n- If $x \\lt 0$, it means that $nums[j]$ is too small, we need to move $j$ to the right.\n- If $x \\gt 0$, it means that $nums[k]$ is too large, we need to move $k$ to the left.\n- Otherwise, it means that we have found a valid triplet, add it to the answer, move $j$ to the right, move $k$ to the left, and skip all duplicate elements to continue looking for the next valid triplet.\n\nAfter the enumeration is over, we can get the answer to the triplet.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(\\log n)$. The $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(\\log n)" }, { "problem_id": 16, "explanations": { "1": "We sort the array first, then traverse the array. For each element $nums[i]$, we use pointers $j$ and $k$ to point to $i+1$ and $n-1$ respectively, calculate the sum of the three numbers. If the sum of the three numbers equals $target$, we directly return $target$. Otherwise, we update the answer based on the difference from $target$. If the sum of the three numbers is greater than $target$, we move $k$ one place to the left, otherwise, we move $j$ one place to the right.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(\\log n)" }, { "problem_id": 17, "explanations": { "1": "First, we use an array or hash table to store the letters corresponding to each digit. Then we traverse each digit, combine its corresponding letters with the previous results to get the new results.\n\nThe time complexity is $O(4^n)$, and the space complexity is $O(4^n)$. Here, $n$ is the length of the input digits.", "2": "We can use the method of depth-first search to enumerate all possible letter combinations. Suppose that a part of the letter combination has been generated, but some digits have not been exhausted. At this time, we take out the letters corresponding to the next digit, and then enumerate each letter corresponding to this digit one by one, add them to the letter combination that has been generated before, to form all possible combinations.\n\nThe time complexity is $O(4^n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the input digits." }, "is_english": true, "time_complexity": "O(4^n)", "space_complexity": "O(4^n)" }, { "problem_id": 18, "explanations": { "1": "We notice that the problem requires us to find non-repeating quadruplets. Therefore, we can first sort the array, which makes it easy to skip duplicate elements.\n\nNext, we enumerate the first two elements of the quadruplet, $nums[i]$ and $nums[j]$, where $i \\lt j$. During the enumeration process, we skip duplicate $nums[i]$ and $nums[j]$. Then, we use two pointers $k$ and $l$ to point to the two ends behind $nums[i]$ and $nums[j]$. Let $x = nums[i] + nums[j] + nums[k] + nums[l]$, we compare $x$ with $target$ and perform the following operations:\n\n- If $x \\lt target$, then update $k = k + 1$ to get a larger $x$;\n- If $x \\gt target$, then update $l = l - 1$ to get a smaller $x$;\n- Otherwise, it means that a quadruplet $(nums[i], nums[j], nums[k], nums[l])$ is found. Add it to the answer, then we update the pointers $k$ and $l$, and skip all duplicate elements to prevent the answer from containing duplicate quadruplets, and continue to find the next quadruplet.\n\nThe time complexity is $O(n^3)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n^3)", "space_complexity": "O(\\log n)" }, { "problem_id": 19, "explanations": { "1": "We define two pointers `fast` and `slow`, both initially pointing to the dummy head node of the linked list.\n\nNext, the `fast` pointer moves forward $n$ steps first, then `fast` and `slow` pointers move forward together until the `fast` pointer reaches the end of the linked list. At this point, the node pointed to by `slow.next` is the predecessor of the $n$-th node from the end, and we can delete it.\n\nThe time complexity is $O(n)$, where $n$ is the length of the linked list. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 20, "explanations": { "1": "Traverse the bracket string $s$. When encountering a left bracket, push the current left bracket into the stack; when encountering a right bracket, pop the top element of the stack (if the stack is empty, directly return `false`), and judge whether it matches. If it does not match, directly return `false`.\n\nAlternatively, when encountering a left bracket, you can push the corresponding right bracket into the stack; when encountering a right bracket, pop the top element of the stack (if the stack is empty, directly return `false`), and judge whether they are equal. If they do not match, directly return `false`.\n\n> The difference between the two methods is only the timing of bracket conversion, one is when pushing into the stack, and the other is when popping out of the stack.\n\nAt the end of the traversal, if the stack is empty, it means the bracket string is valid, return `true`; otherwise, return `false`.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the bracket string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 21, "explanations": { "1": "First, we judge whether the linked lists $l_1$ and $l_2$ are empty. If one of them is empty, we return the other linked list. Otherwise, we compare the head nodes of $l_1$ and $l_2$:\n\n- If the value of the head node of $l_1$ is less than or equal to the value of the head node of $l_2$, we recursively call the function $mergeTwoLists(l_1.next, l_2)$, and connect the head node of $l_1$ with the returned linked list head node, and return the head node of $l_1$.\n- Otherwise, we recursively call the function $mergeTwoLists(l_1, l_2.next)$, and connect the head node of $l_2$ with the returned linked list head node, and return the head node of $l_2$.\n\nThe time complexity is $O(m + n)$, and the space complexity is $O(m + n)$. Here, $m$ and $n$ are the lengths of the two linked lists respectively.", "2": "We can also use iteration to implement the merging of two sorted linked lists.\n\nFirst, we define a dummy head node $dummy$, then loop through the two linked lists, compare the head nodes of the two linked lists, add the smaller node to the end of $dummy$, until one of the linked lists is empty, then add the remaining part of the other linked list to the end of $dummy$.\n\nFinally, return $dummy.next$.\n\nThe time complexity is $O(m + n)$, where $m$ and $n$ are the lengths of the two linked lists respectively. Ignoring the space consumption of the answer linked list, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m + n)", "space_complexity": "O(m + n)" }, { "problem_id": 22, "explanations": { "1": "The range of $n$ in the problem is $[1, 8]$, so we can directly solve this problem through \"brute force search + pruning\".\n\nWe design a function $dfs(l, r, t)$, where $l$ and $r$ represent the number of left and right brackets respectively, and $t$ represents the current bracket sequence. Then we can get the following recursive structure:\n\n- If $l \\gt n$ or $r \\gt n$ or $l \\lt r$, then the current bracket combination $t$ is invalid, return directly;\n- If $l = n$ and $r = n$, then the current bracket combination $t$ is valid, add it to the answer array `ans`, and return directly;\n- We can choose to add a left bracket, and recursively execute `dfs(l + 1, r, t + \"(\")`;\n- We can also choose to add a right bracket, and recursively execute `dfs(l, r + 1, t + \")\")`.\n\nThe time complexity is $O(2^{n\\times 2} \\times n)$, and the space complexity is $O(n)$.", "2": "" }, "is_english": true, "time_complexity": "O(2^{n\\times 2} \\times n)", "space_complexity": "O(n)" }, { "problem_id": 23, "explanations": { "1": "We can create a min heap $pq$ to maintain the head nodes of all linked lists. Each time, we take out the node with the smallest value from the min heap, add it to the end of the result linked list, and then add the next node of this node to the heap. Repeat the above steps until the heap is empty.\n\nThe time complexity is $O(n \\times \\log k)$, and the space complexity is $O(k)$. Here, $n$ is the total number of all linked list nodes, and $k$ is the number of linked lists given in the problem." }, "is_english": true, "time_complexity": "O(n \\times \\log k)", "space_complexity": "O(k)" }, { "problem_id": 24, "explanations": { "1": "We can implement swapping two nodes in the linked list through recursion.\n\nThe termination condition of recursion is that there are no nodes in the linked list, or there is only one node in the linked list. At this time, swapping cannot be performed, so we directly return this node.\n\nOtherwise, we recursively swap the linked list $head.next.next$, and let the swapped head node be $t$. Then we let $p$ be the next node of $head$, and let $p$ point to $head$, and $head$ point to $t$, finally return $p$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the linked list.", "2": "We set a dummy head node $dummy$, initially pointing to $head$, and then set two pointers $pre$ and $cur$, initially $pre$ points to $dummy$, and $cur$ points to $head$.\n\nNext, we traverse the linked list. Each time we need to swap the two nodes after $pre$, so we first judge whether $cur$ and $cur.next$ are empty. If they are not empty, we perform the swap, otherwise we terminate the loop.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the linked list." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 25, "explanations": { "1": "We can simulate the entire reversal process according to the problem description.\n\nFirst, we define a helper function $\\textit{reverse}$ to reverse a linked list. Then, we define a dummy head node $\\textit{dummy}$ and set its $\\textit{next}$ pointer to $\\textit{head}$.\n\nNext, we traverse the linked list, processing $k$ nodes at a time. If the remaining nodes are fewer than $k$, we do not perform the reversal. Otherwise, we extract $k$ nodes and call the $\\textit{reverse}$ function to reverse these $k$ nodes. Then, we connect the reversed linked list back to the original linked list. We continue to process the next $k$ nodes until the entire linked list is traversed.\n\nThe time complexity is $O(n)$, where $n$ is the length of the linked list. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 26, "explanations": { "1": "We use a variable $k$ to record the current length of the processed array. Initially, $k=0$ represents an empty array.\n\nThen we traverse the array from left to right. For each element $x$ we encounter, if $k=0$ or $x \\neq nums[k-1]$, we place $x$ in the position of $nums[k]$, and then increment $k$ by $1$. Otherwise, $x$ is the same as $nums[k-1]$, so we skip this element. Continue to traverse until the entire array is traversed.\n\nIn this way, when the traversal ends, the first $k$ elements in $nums$ are the answer we are looking for, and $k$ is the length of the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the array.\n\nSupplement:\n\nThe original problem requires that the same number appear at most once. We can extend it to keep at most $k$ identical numbers.\n\n- Since the same number can be kept at most $k$ times, we can directly keep the first $k$ elements of the original array;\n- For the following numbers, the premise of being able to keep them is: the current number $x$ is compared with the last $k$th element of the previously retained numbers. If they are different, keep them, otherwise skip them.\n\nSimilar problems:\n\n- [80. Remove Duplicates from Sorted Array II](https://github.com/doocs/leetcode/blob/main/solution/0000-0099/0080.Remove%20Duplicates%20from%20Sorted%20Array%20II/README_EN.md)" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 27, "explanations": { "1": "We use the variable $k$ to record the number of elements that are not equal to $val$.\n\nTraverse the array $nums$, if the current element $x$ is not equal to $val$, then assign $x$ to $nums[k]$, and increment $k$ by $1$.\n\nFinally, return $k$.\n\nThe time complexity is $O(n)$ and the space complexity is $O(1)$, where $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 28, "explanations": { "1": "We compare the string `needle` with each character of the string `haystack` as the starting point. If we find a matching index, we return it directly.\n\nAssuming the length of the string `haystack` is $n$ and the length of the string `needle` is $m$, the time complexity is $O((n-m) \\times m)$, and the space complexity is $O(1)$.", "2": "The [Rabin-Karp algorithm](https://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_algorithm) essentially uses a sliding window combined with a hash function to compare the hashes of fixed-length strings, which can reduce the time complexity of comparing whether two strings are the same to $O(1)$.\n\nAssuming the length of the string `haystack` is $n$ and the length of the string `needle` is $m$, the time complexity is $O(n+m)$, and the space complexity is $O(1)$.", "3": "Assuming the length of the string `haystack` is $n$ and the length of the string `needle` is $m$, the time complexity is $O(n+m)$, and the space complexity is $O(m)$." }, "is_english": true, "time_complexity": "O((n-m) \\times m)", "space_complexity": "O(1)" }, { "problem_id": 29, "explanations": { "1": "Division is essentially subtraction. The problem requires us to calculate the integer result after dividing two numbers, which is actually calculating how many divisors and a number less than the divisor constitute the dividend. However, only one subtraction can be done in one loop, which is too inefficient and will lead to timeout. This can be optimized by using the idea of fast power.\n\nIt should be noted that since the problem explicitly requires that only 32-bit signed integers can be used at most, the divisor and dividend need to be converted to negative numbers for calculation. Because converting to positive numbers may cause overflow, such as when the dividend is `INT32_MIN`, it will be greater than `INT32_MAX` when converted to a positive number.\n\nAssuming the dividend is $a$ and the divisor is $b$, the time complexity is $O(\\log a \\times \\log b)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log a \\times \\log b)", "space_complexity": "O(1)" }, { "problem_id": 30, "explanations": { "1": "We use a hash table $cnt$ to count the number of times each word appears in $words$, and use a hash table $cnt1$ to count the number of times each word appears in the current sliding window. We denote the length of the string $s$ as $m$, the number of words in the string array $words$ as $n$, and the length of each word as $k$.\n\nWe can enumerate the starting point $i$ of the sliding window, where $0 \\lt i < k$. For each starting point, we maintain a sliding window with the left boundary as $l$, the right boundary as $r$, and the number of words in the sliding window as $t$. Additionally, we use a hash table $cnt1$ to count the number of times each word appears in the sliding window.\n\nEach time, we extract the string $s[r:r+k]$. If $s[r:r+k]$ is not in the hash table $cnt$, it means that the words in the current sliding window are not valid. We update the left boundary $l$ to $r$, clear the hash table $cnt1$, and reset the word count $t$ to 0. If $s[r:r+k]$ is in the hash table $cnt$, it means that the words in the current sliding window are valid. We increase the word count $t$ by 1, and increase the count of $s[r:r+k]$ in the hash table $cnt1$ by 1. If $cnt1[s[r:r+k]]$ is greater than $cnt[s[r:r+k]]$, it means that $s[r:r+k]$ appears too many times in the current sliding window. We need to move the left boundary $l$ to the right until $cnt1[s[r:r+k]] = cnt[s[r:r+k]]$. If $t = n$, it means that the words in the current sliding window are exactly valid, and we add the left boundary $l$ to the answer array.\n\nThe time complexity is $O(m \\times k)$, and the space complexity is $O(n \\times k)$. Here, $m$ and $n$ are the lengths of the string $s$ and the string array $words$ respectively, and $k$ is the length of the words in the string array $words$." }, "is_english": true, "time_complexity": "O(m \\times k)", "space_complexity": "O(n \\times k)" }, { "problem_id": 31, "explanations": { "1": "We first traverse the array from back to front and find the first position $i$ where $nums[i] \\lt nums[i + 1]$.\n\nThen traverse the array from back to front again and find the first position $j$ where $nums[j] \\gt nums[i]$. Swap $nums[i]$ and $nums[j]$, and then reverse the elements from $nums[i + 1]$ to $nums[n - 1]$, the next permutation can be obtained.\n\nThe time complexity is $O(n)$ and the space complexity is $O(1)$. Where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 32, "explanations": { "1": "We define $f[i]$ to be the length of the longest valid parentheses that ends with $s[i-1]$, and the answer is $max(f[i])$.\n\nWhen $i \\lt 2$, the length of the string is less than $2$, and there is no valid parentheses, so $f[i] = 0$.\n\nWhen $i \\ge 2$, we consider the length of the longest valid parentheses that ends with $s[i-1]$, that is, $f[i]$:\n\n- If $s[i-1]$ is a left parenthesis, then the length of the longest valid parentheses that ends with $s[i-1]$ must be $0$, so $f[i] = 0$.\n- If $s[i-1]$ is a right parenthesis, there are the following two cases:\n - If $s[i-2]$ is a left parenthesis, then the length of the longest valid parentheses that ends with $s[i-1]$ is $f[i-2] + 2$.\n - If $s[i-2]$ is a right parenthesis, then the length of the longest valid parentheses that ends with $s[i-1]$ is $f[i-1] + 2$, but we also need to consider whether $s[i-f[i-1]-2]$ is a left parenthesis. If it is a left parenthesis, then the length of the longest valid parentheses that ends with $s[i-1]$ is $f[i-1] + 2 + f[i-f[i-1]-2]$.\n\nTherefore, we can get the state transition equation:\n\n$$\n\\begin{cases}\nf[i] = 0, & \\textit{if } s[i-1] = '(',\\\\\nf[i] = f[i-2] + 2, & \\textit{if } s[i-1] = ')' \\textit{ and } s[i-2] = '(',\\\\\nf[i] = f[i-1] + 2 + f[i-f[i-1]-2], & \\textit{if } s[i-1] = ')' \\textit{ and } s[i-2] = ')' \\textit{ and } s[i-f[i-1]-2] = '(',\\\\\n\\end{cases}\n$$\n\nFinally, we only need to return $max(f)$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the string.", "2": "- Maintain a stack to store the indices of left parentheses. Initialize the bottom element of the stack with the value -1 to facilitate the calculation of the length of valid parentheses.\n- Iterate through each element of the string:\n - If the character is a left parenthesis, push the index of the character onto the stack.\n - If the character is a right parenthesis, pop an element from the stack to represent that we have found a valid pair of parentheses.\n - If the stack is empty, it means we couldn't find a left parenthesis to match the right parenthesis. In this case, push the index of the character as a new starting point.\n - If the stack is not empty, calculate the length of the valid parentheses and update it.\n\nSummary:\n\nThe key to this algorithm is to maintain a stack to store the indices of left parentheses and then update the length of the valid substring of parentheses by pushing and popping elements.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the string." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 33, "explanations": { "1": "We use binary search to divide the array into two parts, $[left,.. mid]$ and $[mid + 1,.. right]$. At this point, we can find that one part must be sorted.\n\nTherefore, we can determine whether $target$ is in this part based on the sorted part:\n\n- If the elements in the range $[0,.. mid]$ form a sorted array:\n - If $nums[0] \\leq target \\leq nums[mid]$, then our search range can be narrowed down to $[left,.. mid]$;\n - Otherwise, search in $[mid + 1,.. right]$;\n- If the elements in the range $[mid + 1, n - 1]$ form a sorted array:\n - If $nums[mid] \\lt target \\leq nums[n - 1]$, then our search range can be narrowed down to $[mid + 1,.. right]$;\n - Otherwise, search in $[left,.. mid]$.\n\nThe termination condition for binary search is $left \\geq right$. If at the end we find that $nums[left]$ is not equal to $target$, it means that there is no element with a value of $target$ in the array, and we return $-1$. Otherwise, we return the index $left$.\n\nThe time complexity is $O(\\log n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 34, "explanations": { "1": "We can perform two binary searches to find the left boundary and the right boundary.\n\nThe time complexity is $O(\\log n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 35, "explanations": { "1": "Since the array $nums$ is already sorted, we can use the binary search method to find the insertion position of the target value $target$.\n\nThe time complexity is $O(\\log n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the array $nums$.", "2": "We can also directly use the built-in function for binary search.\n\nThe time complexity is $O(\\log n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 36, "explanations": { "1": "The valid sudoku satisfies the following three conditions:\n\n- The digits are not repeated in each row;\n- The digits are not repeated in each column;\n- The digits are not repeated in each $3 \\times 3$ box.\n\nTraverse the sudoku, for each digit, check whether the row, column and $3 \\times 3$ box it is in have appeared the digit. If it is, return `false`. If the traversal is over, return `true`.\n\nThe time complexity is $O(C)$ and the space complexity is $O(C)$, where $C$ is the number of empty spaces in the sudoku. In this question, $C=81$." }, "is_english": true, "time_complexity": "O(C)", "space_complexity": "O(C)" }, { "problem_id": 37, "explanations": { "1": "We use arrays $\\textit{row}$, $\\textit{col}$, and $\\textit{box}$ to record whether each number has appeared in each row, each column, and each 3x3 sub-box, respectively. If the number $i$ has appeared in row $r$, column $c$, or the $b$-th 3x3 sub-box, then $\\text{row[r][i]}$, $\\text{col[c][i]}$, and $\\text{box[b][i]}$ are all set to $true$.\n\nWe iterate over every empty cell in the $\\textit{board}$ and enumerate the possible numbers $v$ that can be filled in. If $v$ has not appeared in the current row, column, or 3x3 sub-box, we can try filling in $v$ and continue searching for the next empty cell. If we reach the end and all cells are filled, it means we have found a valid solution." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 38, "explanations": { "1": "The task requires outputting the appearance sequence of the $n$-th item, where the $n$-th item is the description of the $n-1$-th item in the sequence. Therefore, we iterate $n-1$ times. In each iteration, we use fast and slow pointers, denoted as j and i respectively, to record the current character's position and the position of the next character that is not equal to the current character. We then update the sequence of the previous item to be $j-i$ occurrences of the current character.\n\nTime Complexity:\n\n1. The outer loop runs `n - 1` times, iterating to generate the \"Count and Say\" sequence up to the nth term.\n2. The inner while loop iterates through each character in the current string s and counts the consecutive occurrences of the same character.\n3. The inner while loop runs in $O(m)$ time, where m is the length of the current string s.\n\nOverall, the time complexity is $O(n \\times m)$, where n is the input parameter representing the term to generate, and m is the maximum length of the string in the sequence.\n\nSpace Complexity: $O(m)$." }, "is_english": true, "time_complexity": "O(n \\times m)", "space_complexity": null }, { "problem_id": 39, "explanations": { "1": "We can first sort the array to facilitate pruning.\n\nNext, we design a function $dfs(i, s)$, which means starting the search from index $i$ with a remaining target value of $s$. Here, $i$ and $s$ are both non-negative integers, the current search path is $t$, and the answer is $ans$.\n\nIn the function $dfs(i, s)$, we first check whether $s$ is $0$. If it is, we add the current search path $t$ to the answer $ans$, and then return. If $s \\lt candidates[i]$, it means that the elements of the current index and the following indices are all greater than the remaining target value $s$, and the path is invalid, so we return directly. Otherwise, we start the search from index $i$, and the search index range is $j \\in [i, n)$, where $n$ is the length of the array $candidates$. During the search, we add the element of the current index to the search path $t$, recursively call the function $dfs(j, s - candidates[j])$, and after the recursion ends, we remove the element of the current index from the search path $t$.\n\nIn the main function, we just need to call the function $dfs(0, target)$ to get the answer.\n\nThe time complexity is $O(2^n \\times n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $candidates$. Due to pruning, the actual time complexity is much less than $O(2^n \\times n)$.\n\nSimilar problems:\n\n- [40. Combination Sum II](https://github.com/doocs/leetcode/blob/main/solution/0000-0099/0040.Combination%20Sum%20II/README_EN.md)\n- [77. Combinations](https://github.com/doocs/leetcode/blob/main/solution/0000-0099/0077.Combinations/README_EN.md)\n- [216. Combination Sum III](https://github.com/doocs/leetcode/blob/main/solution/0200-0299/0216.Combination%20Sum%20III/README_EN.md)", "2": "We can also change the implementation logic of the function $dfs(i, s)$ to another form. In the function $dfs(i, s)$, we first check whether $s$ is $0$. If it is, we add the current search path $t$ to the answer $ans$, and then return. If $i \\geq n$ or $s \\lt candidates[i]$, the path is invalid, so we return directly. Otherwise, we consider two situations, one is not selecting the element of the current index, that is, recursively calling the function $dfs(i + 1, s)$, and the other is selecting the element of the current index, that is, recursively calling the function $dfs(i, s - candidates[i])$.\n\nThe time complexity is $O(2^n \\times n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $candidates$. Due to pruning, the actual time complexity is much less than $O(2^n \\times n)$." }, "is_english": true, "time_complexity": "O(2^n \\times n)", "space_complexity": "O(n)" }, { "problem_id": 40, "explanations": { "1": "We can first sort the array to facilitate pruning and skipping duplicate numbers.\n\nNext, we design a function $dfs(i, s)$, which means starting the search from index $i$ with a remaining target value of $s$. Here, $i$ and $s$ are both non-negative integers, the current search path is $t$, and the answer is $ans$.\n\nIn the function $dfs(i, s)$, we first check whether $s$ is $0$. If it is, we add the current search path $t$ to the answer $ans$, and then return. If $i \\geq n$ or $s \\lt candidates[i]$, the path is invalid, so we return directly. Otherwise, we start the search from index $i$, and the search index range is $j \\in [i, n)$, where $n$ is the length of the array $candidates$. During the search, if $j \\gt i$ and $candidates[j] = candidates[j - 1]$, it means that the current number is the same as the previous number, we can skip the current number because the previous number has been searched. Otherwise, we add the current number to the search path $t$, recursively call the function $dfs(j + 1, s - candidates[j])$, and after the recursion ends, we remove the current number from the search path $t$.\n\nWe can also change the implementation logic of the function $dfs(i, s)$ to another form. If we choose the current number, we add the current number to the search path $t$, then recursively call the function $dfs(i + 1, s - candidates[i])$, and after the recursion ends, we remove the current number from the search path $t$. If we do not choose the current number, we can skip all numbers that are the same as the current number, then recursively call the function $dfs(j, s)$, where $j$ is the index of the first number that is different from the current number.\n\nIn the main function, we just need to call the function $dfs(0, target)$ to get the answer.\n\nThe time complexity is $O(2^n \\times n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $candidates$. Due to pruning, the actual time complexity is much less than $O(2^n \\times n)$.\n\nSimilar problems:\n\n- [39. Combination Sum](https://github.com/doocs/leetcode/blob/main/solution/0000-0099/0039.Combination%20Sum/README_EN.md)\n- [77. Combinations](https://github.com/doocs/leetcode/blob/main/solution/0000-0099/0077.Combinations/README_EN.md)\n- [216. Combination Sum III](https://github.com/doocs/leetcode/blob/main/solution/0200-0299/0216.Combination%20Sum%20III/README_EN.md)", "2": "We can also change the implementation logic of the function $dfs(i, s)$ to another form. If we choose the current number, we add the current number to the search path $t$, then recursively call the function $dfs(i + 1, s - candidates[i])$, and after the recursion ends, we remove the current number from the search path $t$. If we do not choose the current number, we can skip all numbers that are the same as the current number, then recursively call the function $dfs(j, s)$, where $j$ is the index of the first number that is different from the current number.\n\nThe time complexity is $O(2^n \\times n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $candidates$. Due to pruning, the actual time complexity is much less than $O(2^n \\times n)$." }, "is_english": true, "time_complexity": "O(2^n \\times n)", "space_complexity": "O(n)" }, { "problem_id": 41, "explanations": { "1": "We assume the length of the array $nums$ is $n$, then the smallest positive integer must be in the range $[1, .., n + 1]$. We can traverse the array and swap each number $x$ to its correct position, that is, the position $x - 1$. If $x$ is not in the range $[1, n + 1]$, then we can ignore it.\n\nAfter the traversal, we traverse the array again. If $i+1$ is not equal to $nums[i]$, then $i+1$ is the smallest positive integer we are looking for.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 42, "explanations": { "1": "We define $left[i]$ as the height of the highest bar to the left of and including the position at index $i$, and $right[i]$ as the height of the highest bar to the right of and including the position at index $i$. Therefore, the amount of rainwater that can be trapped at index $i$ is $min(left[i], right[i]) - height[i]$. We traverse the array to calculate $left[i]$ and $right[i]$, and the final answer is $\\sum_{i=0}^{n-1} \\min(left[i], right[i]) - height[i]$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 43, "explanations": { "1": "Assume the lengths of $num1$ and $num2$ are $m$ and $n$ respectively, then the length of their product can be at most $m + n$.\n\nThe proof is as follows:\n\n- If $num1$ and $num2$ both take the minimum value, then their product is ${10}^{m - 1} \\times {10}^{n - 1} = {10}^{m + n - 2}$, with a length of $m + n - 1$.\n- If $num1$ and $num2$ both take the maximum value, then their product is $({10}^m - 1) \\times ({10}^n - 1) = {10}^{m + n} - {10}^m - {10}^n + 1$, with a length of $m + n$.\n\nTherefore, we can apply for an array of length $m + n$ to store each digit of the product.\n\nFrom the least significant digit to the most significant digit, we calculate each digit of the product in turn, and finally convert the array into a string.\n\nNote to check whether the most significant digit is $0$, if it is, remove it.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m + n)$. Here, $m$ and $n$ are the lengths of $num1$ and $num2$ respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m + n)" }, { "problem_id": 44, "explanations": { "1": "We design a function $dfs(i, j)$, which represents whether the string $s$ starting from the $i$-th character matches the string $p$ starting from the $j$-th character. The answer is $dfs(0, 0)$.\n\nThe execution process of the function $dfs(i, j)$ is as follows:\n\n- If $i \\geq \\textit{len}(s)$, then $dfs(i, j)$ is true only when $j \\geq \\textit{len}(p)$ or $p[j] = '*'$ and $dfs(i, j + 1)$ is true.\n- If $j \\geq \\textit{len}(p)$, then $dfs(i, j)$ is false.\n- If $p[j] = '*'$, then $dfs(i, j)$ is true if and only if $dfs(i + 1, j)$ or $dfs(i + 1, j + 1)$ or $dfs(i, j + 1)$ is true.\n- Otherwise, $dfs(i, j)$ is true if and only if $p[j] = '?'$ or $s[i] = p[j]$ and $dfs(i + 1, j + 1)$ is true.\n\nTo avoid repeated calculations, we use the method of memoization search and store the result of $dfs(i, j)$ in a hash table.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Where $m$ and $n$ are the lengths of the strings $s$ and $p$, respectively.", "2": "We can convert the memoization search in Solution 1 into dynamic programming.\n\nDefine $f[i][j]$ to represent whether the first $i$ characters of string $s$ match the first $j$ characters of string $p$. Initially, $f[0][0] = \\textit{true}$, indicating that two empty strings are matching. For $j \\in [1, n]$, if $p[j-1] = '*'$, then $f[0][j] = f[0][j-1]$.\n\nNext, we consider the case of $i \\in [1, m]$ and $j \\in [1, n]$:\n\n- If $p[j-1] = '*'$, then $f[i][j] = f[i-1][j] \\lor f[i][j-1] \\lor f[i-1][j-1]$.\n- Otherwise, $f[i][j] = (p[j-1] = '?' \\lor s[i-1] = p[j-1]) \\land f[i-1][j-1]$.\n\nThe final answer is $f[m][n]$.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Where $m$ and $n$ are the lengths of the strings $s$ and $p$, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 45, "explanations": { "1": "We can use a variable $mx$ to record the farthest position that can be reached from the current position, a variable $last$ to record the position of the last jump, and a variable $ans$ to record the number of jumps.\n\nNext, we traverse each position $i$ in $[0,..n - 2]$. For each position $i$, we can calculate the farthest position that can be reached from the current position through $i + nums[i]$. We use $mx$ to record this farthest position, that is, $mx = max(mx, i + nums[i])$. Then, we check whether the current position has reached the boundary of the last jump, that is, $i = last$. If it has reached, then we need to make a jump, update $last$ to $mx$, and increase the number of jumps $ans$ by $1$.\n\nFinally, we return the number of jumps $ans$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$.\n\nSimilar problems:\n\n- [55. Jump Game](https://github.com/doocs/leetcode/blob/main/solution/0000-0099/0055.Jump%20Game/README_EN.md)\n- [1024. Video Stitching](https://github.com/doocs/leetcode/blob/main/solution/1000-1099/1024.Video%20Stitching/README_EN.md)\n- [1326. Minimum Number of Taps to Open to Water a Garden](https://github.com/doocs/leetcode/blob/main/solution/1300-1399/1326.Minimum%20Number%20of%20Taps%20to%20Open%20to%20Water%20a%20Garden/README_EN.md)" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 46, "explanations": { "1": "We design a function $dfs(i)$ to represent that the first $i$ positions have been filled, and now we need to fill the $i+1$ position. We enumerate all possible numbers, if this number has not been filled, we fill in this number, and then continue to fill the next position, until all positions are filled.\n\nThe time complexity is $O(n \\times n!)$, where $n$ is the length of the array. There are $n!$ permutations in total, and each permutation takes $O(n)$ time to construct.\n\nSimilar problems:\n\n- [47. Permutations II](https://github.com/doocs/leetcode/blob/main/solution/0000-0099/0047.Permutations%20II/README_EN.md)" }, "is_english": true, "time_complexity": "O(n \\times n!)", "space_complexity": null }, { "problem_id": 47, "explanations": { "1": "We can first sort the array so that duplicate numbers are placed together, making it easier to remove duplicates.\n\nThen, we design a function $\\textit{dfs}(i)$, which represents the current number to be placed at the $i$-th position. The specific implementation of the function is as follows:\n\n- If $i = n$, it means we have filled all positions, add the current permutation to the answer array, and then return.\n- Otherwise, we enumerate the number $nums[j]$ for the $i$-th position, where the range of $j$ is $[0, n - 1]$. We need to ensure that $nums[j]$ has not been used and is different from the previously enumerated number to ensure that the current permutation is not duplicated. If the conditions are met, we can place $nums[j]$ and continue to recursively fill the next position by calling $\\textit{dfs}(i + 1)$. After the recursive call ends, we need to mark $nums[j]$ as unused to facilitate subsequent enumeration.\n\nIn the main function, we first sort the array, then call $\\textit{dfs}(0)$ to start filling from the 0th position, and finally return the answer array.\n\nThe time complexity is $O(n \\times n!)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array. We need to perform $n!$ enumerations, and each enumeration requires $O(n)$ time to check for duplicates. Additionally, we need a marker array to mark whether each position has been used, so the space complexity is $O(n)$.\n\nSimilar problems:\n\n- [46. Permutations](https://github.com/doocs/leetcode/blob/main/solution/0000-0099/0046.Permutations/README_EN.md)" }, "is_english": true, "time_complexity": "O(n \\times n!)", "space_complexity": "O(n)" }, { "problem_id": 48, "explanations": { "1": "According to the problem requirements, we need to rotate $\\text{matrix}[i][j]$ to $\\text{matrix}[j][n - i - 1]$.\n\nWe can first flip the matrix upside down, i.e., swap $\\text{matrix}[i][j]$ with $\\text{matrix}[n - i - 1][j]$, and then flip the matrix along the main diagonal, i.e., swap $\\text{matrix}[i][j]$ with $\\text{matrix}[j][i]$. This way, we can rotate $\\text{matrix}[i][j]$ to $\\text{matrix}[j][n - i - 1]$.\n\nThe time complexity is $O(n^2)$, where $n$ is the side length of the matrix. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(1)" }, { "problem_id": 49, "explanations": { "1": "1. Traverse the string array, sort each string in **character dictionary order** to get a new string.\n2. Use the new string as `key` and `[str]` as `value`, and store them in the hash table (`HashMap>`).\n3. When encountering the same `key` during subsequent traversal, add it to the corresponding `value`.\n\nTake `strs = [\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"]` as an example. At the end of the traversal, the state of the hash table is:\n\n| key | value |\n| ------- | ----------------------- |\n| `\"aet\"` | `[\"eat\", \"tea\", \"ate\"]` |\n| `\"ant\"` | `[\"tan\", \"nat\"] ` |\n| `\"abt\"` | `[\"bat\"] ` |\n\nFinally, return the `value` list of the hash table.\n\nThe time complexity is $O(n\\times k\\times \\log k)$, where $n$ and $k$ are the lengths of the string array and the maximum length of the string, respectively.", "2": "We can also change the sorting part in Solution 1 to counting, that is, use the characters in each string $s$ and their occurrence times as `key`, and use the string $s$ as `value` to store in the hash table.\n\nThe time complexity is $O(n\\times (k + C))$, where $n$ and $k$ are the lengths of the string array and the maximum length of the string, respectively, and $C$ is the size of the character set. In this problem, $C = 26$." }, "is_english": true, "time_complexity": "O(n\\times k\\times \\log k)", "space_complexity": null }, { "problem_id": 50, "explanations": { "1": "The core idea of the fast powering algorithm is to decompose the exponent $n$ into the sum of $1$s on several binary bits, and then transform the $n$th power of $x$ into the product of several powers of $x$.\n\nThe time complexity is $O(\\log n)$, and the space complexity is $O(1)$. Here, $n$ is the exponent." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 51, "explanations": { "1": "We define three arrays $col$, $dg$, and $udg$ to represent whether there is a queen in the column, the main diagonal, and the anti-diagonal, respectively. If there is a queen at position $(i, j)$, then $col[j]$, $dg[i + j]$, and $udg[n - i + j]$ are all $1$. In addition, we use an array $g$ to record the current state of the chessboard, where all elements in $g$ are initially `'.'`.\n\nNext, we define a function $dfs(i)$, which represents placing queens starting from the $i$th row.\n\nIn $dfs(i)$, if $i = n$, it means that we have completed the placement of all queens. We put the current $g$ into the answer array and end the recursion.\n\nOtherwise, we enumerate each column $j$ of the current row. If there is no queen at position $(i, j)$, that is, $col[j]$, $dg[i + j]$, and $udg[n - i + j]$ are all $0$, then we can place a queen, that is, change $g[i][j]$ to `'Q'`, and set $col[j]$, $dg[i + j]$, and $udg[n - i + j]$ to $1$. Then we continue to search the next row, that is, call $dfs(i + 1)$. After the recursion ends, we need to change $g[i][j]$ back to `'.'` and set $col[j]$, $dg[i + j]$, and $udg[n - i + j]$ to $0$.\n\nIn the main function, we call $dfs(0)$ to start recursion, and finally return the answer array.\n\nThe time complexity is $O(n^2 \\times n!)$, and the space complexity is $O(n)$. Here, $n$ is the integer given in the problem." }, "is_english": true, "time_complexity": "O(n^2 \\times n!)", "space_complexity": "O(n)" }, { "problem_id": 52, "explanations": { "1": "We design a function $dfs(i)$, which represents starting the search from the $i$th row, and the results of the search are added to the answer.\n\nIn the $i$th row, we enumerate each column of the $i$th row. If the current column does not conflict with the queens placed before, then we can place a queen, and then continue to search the next row, that is, call $dfs(i + 1)$.\n\nIf a conflict occurs, then we skip the current column and continue to enumerate the next column.\n\nTo determine whether a conflict occurs, we need to use three arrays to record whether a queen has been placed in each column, each positive diagonal, and each negative diagonal, respectively.\n\nSpecifically, we use the $cols$ array to record whether a queen has been placed in each column, the $dg$ array to record whether a queen has been placed in each positive diagonal, and the $udg$ array to record whether a queen has been placed in each negative diagonal.\n\nThe time complexity is $O(n!)$, and the space complexity is $O(n)$. Here, $n$ is the number of queens." }, "is_english": true, "time_complexity": "O(n!)", "space_complexity": "O(n)" }, { "problem_id": 53, "explanations": { "1": "We define $f[i]$ to represent the maximum sum of a contiguous subarray ending at element $\\textit{nums}[i]$. Initially, $f[0] = \\textit{nums}[0]$. The final answer we seek is $\\max_{0 \\leq i < n} f[i]$.\n\nConsider $f[i]$ for $i \\geq 1$. Its state transition equation is:\n\n$$\nf[i] = \\max(f[i - 1] + \\textit{nums}[i], \\textit{nums}[i])\n$$\n\nThat is:\n\n$$\nf[i] = \\max(f[i - 1], 0) + \\textit{nums}[i]\n$$\n\nSince $f[i]$ is only related to $f[i - 1]$, we can use a single variable $f$ to maintain the current value of $f[i]$ and perform the state transition. The answer is $\\max_{0 \\leq i < n} f$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$.", "2": "" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 54, "explanations": { "1": "We can simulate the entire traversal process. We use $i$ and $j$ to represent the row and column of the current element being visited, and $k$ to represent the current direction. We use an array or hash table $\\textit{vis}$ to record whether each element has been visited. Each time we visit an element, we mark it as visited, then move one step forward in the current direction. If moving forward results in an out-of-bounds condition or the element has already been visited, we change direction and continue moving forward until the entire matrix has been traversed.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the number of rows and columns of the matrix, respectively.", "2": "Notice that the range of matrix element values is $[-100, 100]$. Therefore, we can add a large value, such as $300$, to the visited elements. This way, we only need to check if the visited element is greater than $100$, without needing extra space to record whether it has been visited. If we need to restore the original values of the visited elements, we can traverse the matrix again after the traversal is complete and subtract $300$ from all elements.\n\nThe time complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns of the matrix, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 55, "explanations": { "1": "We use a variable $mx$ to maintain the farthest index that can currently be reached, initially $mx = 0$.\n\nWe traverse the array from left to right. For each position $i$ we traverse, if $mx < i$, it means that the current position cannot be reached, so we directly return `false`. Otherwise, the farthest position that we can reach by jumping from position $i$ is $i+nums[i]$, we use $i+nums[i]$ to update the value of $mx$, that is, $mx = \\max(mx, i + nums[i])$.\n\nAt the end of the traversal, we directly return `true`.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$.\n\nSimilar problems:\n\n- [45. Jump Game II](https://github.com/doocs/leetcode/blob/main/solution/0000-0099/0045.Jump%20Game%20II/README_EN.md)\n- [1024. Video Stitching](https://github.com/doocs/leetcode/blob/main/solution/1000-1099/1024.Video%20Stitching/README_EN.md)\n- [1326. Minimum Number of Taps to Open to Water a Garden](https://github.com/doocs/leetcode/blob/main/solution/1300-1399/1326.Minimum%20Number%20of%20Taps%20to%20Open%20to%20Water%20a%20Garden/README_EN.md)" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 56, "explanations": { "1": "We can sort the intervals in ascending order by the left endpoint, and then traverse the intervals for merging operations.\n\nThe specific merging operation is as follows.\n\nFirst, we add the first interval to the answer. Then, we consider each subsequent interval in turn:\n\n- If the right endpoint of the last interval in the answer array is less than the left endpoint of the current interval, it means that the two intervals will not overlap, so we can directly add the current interval to the end of the answer array;\n- Otherwise, it means that the two intervals overlap. We need to use the right endpoint of the current interval to update the right endpoint of the last interval in the answer array, setting it to the larger of the two.\n\nFinally, we return the answer array.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the number of intervals.", "2": "", "3": "" }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 57, "explanations": { "1": "We can first add the new interval `newInterval` to the interval list `intervals`, and then merge according to the regular method of interval merging.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the number of intervals.", "2": "We can traverse the interval list `intervals`, let the current interval be `interval`, and there are three situations for each interval:\n\n- The current interval is on the right side of the new interval, that is, $newInterval[1] < interval[0]$. At this time, if the new interval has not been added, then add the new interval to the answer, and then add the current interval to the answer.\n- The current interval is on the left side of the new interval, that is, $interval[1] < newInterval[0]$. At this time, add the current interval to the answer.\n- Otherwise, it means that the current interval and the new interval intersect. We take the minimum of the left endpoint of the current interval and the left endpoint of the new interval, and the maximum of the right endpoint of the current interval and the right endpoint of the new interval, as the left and right endpoints of the new interval, and then continue to traverse the interval list.\n\nAfter the traversal, if the new interval has not been added, then add the new interval to the answer.\n\nThe time complexity is $O(n)$, where $n$ is the number of intervals. Ignoring the space consumption of the answer array, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 58, "explanations": { "1": "We start traversing from the end of the string $s$, find the first character that is not a space, which is the last character of the last word, and mark the index as $i$. Then continue to traverse forward, find the first character that is a space, which is the character before the first character of the last word, and mark it as $j$. Then the length of the last word is $i - j$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 59, "explanations": { "1": "We can directly simulate the process of generating the spiral matrix.\n\nDefine a 2D array $\\textit{ans}$ to store the spiral matrix. Use $i$ and $j$ to represent the current row and column indices, and use $k$ to represent the current direction index. $\\textit{dirs}$ represents the mapping between direction indices and directions.\n\nStarting from $1$, fill each position in the matrix sequentially. After filling a position, calculate the row and column indices of the next position. If the next position is out of bounds or has already been filled, change the direction and then calculate the row and column indices of the next position.\n\nThe time complexity is $O(n^2)$, where $n$ is the side length of the matrix. Ignoring the space consumption of the answer array, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(1)" }, { "problem_id": 60, "explanations": { "1": "We know that the set $[1,2,..n]$ has a total of $n!$ permutations. If we determine the first digit, the number of permutations that the remaining digits can form is $(n-1)!$.\n\nTherefore, we enumerate each digit $i$. If $k$ is greater than the number of permutations after the current position is determined, then we can directly subtract this number; otherwise, it means that we have found the number at the current position.\n\nFor each digit $i$, where $0 \\leq i < n$, the number of permutations that the remaining digits can form is $(n-i-1)!$, which we denote as $fact$. The numbers used in the process are recorded in `vis`.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 61, "explanations": { "1": "First, we check whether the number of nodes in the linked list is less than $2$. If so, we directly return $head$.\n\nOtherwise, we first count the number of nodes $n$ in the linked list, and then take the modulus of $k$ by $n$ to get the effective value of $k$.\n\nIf the effective value of $k$ is $0$, it means that the linked list does not need to be rotated, and we can directly return $head$.\n\nOtherwise, we use fast and slow pointers, let the fast pointer move $k$ steps first, and then let the fast and slow pointers move together until the fast pointer moves to the end of the linked list. At this time, the next node of the slow pointer is the new head node of the linked list.\n\nFinally, we concatenate the linked list.\n\nThe time complexity is $O(n)$, where $n$ is the number of nodes in the linked list. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 62, "explanations": { "1": "We define $f[i][j]$ to represent the number of paths from the top left corner to $(i, j)$, initially $f[0][0] = 1$, and the answer is $f[m - 1][n - 1]$.\n\nConsider $f[i][j]$:\n\n- If $i > 0$, then $f[i][j]$ can be reached by taking one step from $f[i - 1][j]$, so $f[i][j] = f[i][j] + f[i - 1][j]$;\n- If $j > 0$, then $f[i][j]$ can be reached by taking one step from $f[i][j - 1]$, so $f[i][j] = f[i][j] + f[i][j - 1]$.\n\nTherefore, we have the following state transition equation:\n\n$$\nf[i][j] = \\begin{cases}\n1 & i = 0, j = 0 \\\\\nf[i - 1][j] + f[i][j - 1] & \\textit{otherwise}\n\\end{cases}\n$$\n\nThe final answer is $f[m - 1][n - 1]$.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the number of rows and columns of the grid, respectively.\n\nWe notice that $f[i][j]$ is only related to $f[i - 1][j]$ and $f[i][j - 1]$, so we can optimize the first dimension space and only keep the second dimension space, resulting in a time complexity of $O(m \\times n)$ and a space complexity of $O(n)$.", "2": "", "3": "" }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 63, "explanations": { "1": "We design a function $\\textit{dfs}(i, j)$ to represent the number of paths from the grid $(i, j)$ to the grid $(m - 1, n - 1)$. Here, $m$ and $n$ are the number of rows and columns of the grid, respectively.\n\nThe execution process of the function $\\textit{dfs}(i, j)$ is as follows:\n\n- If $i \\ge m$ or $j \\ge n$, or $\\textit{obstacleGrid}[i][j] = 1$, the number of paths is $0$;\n- If $i = m - 1$ and $j = n - 1$, the number of paths is $1$;\n- Otherwise, the number of paths is $\\textit{dfs}(i + 1, j) + \\textit{dfs}(i, j + 1)$.\n\nTo avoid redundant calculations, we can use memoization.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the number of rows and columns of the grid, respectively.", "2": "We can use a dynamic programming approach by defining a 2D array $f$, where $f[i][j]$ represents the number of paths from the grid $(0,0)$ to the grid $(i,j)$.\n\nWe first initialize all values in the first column and the first row of $f$, then traverse the other rows and columns with two cases:\n\n- If $\\textit{obstacleGrid}[i][j] = 1$, it means the number of paths is $0$, so $f[i][j] = 0$;\n- If $\\textit{obstacleGrid}[i][j] = 0$, then $f[i][j] = f[i - 1][j] + f[i][j - 1]$.\n\nFinally, return $f[m - 1][n - 1]$.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the number of rows and columns of the grid, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 64, "explanations": { "1": "We define $f[i][j]$ to represent the minimum path sum from the top left corner to $(i, j)$. Initially, $f[0][0] = grid[0][0]$, and the answer is $f[m - 1][n - 1]$.\n\nConsider $f[i][j]$:\n\n- If $j = 0$, then $f[i][j] = f[i - 1][j] + grid[i][j]$;\n- If $i = 0$, then $f[i][j] = f[i][j - 1] + grid[i][j]$;\n- If $i > 0$ and $j > 0$, then $f[i][j] = \\min(f[i - 1][j], f[i][j - 1]) + grid[i][j]$.\n\nFinally, return $f[m - 1][n - 1]$.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the number of rows and columns of the grid, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 65, "explanations": { "1": "First, we check if the string starts with a positive or negative sign. If it does, we move the pointer $i$ one step forward. If the pointer $i$ has reached the end of the string at this point, it means the string only contains a positive or negative sign, so we return `false`.\n\nIf the character pointed to by the current pointer $i$ is a decimal point, and there is no number after the decimal point, or if there is an `e` or `E` after the decimal point, we return `false`.\n\nNext, we use two variables $dot$ and $e$ to record the number of decimal points and `e` or `E` respectively.\n\nWe use pointer $j$ to point to the current character:\n\n- If the current character is a decimal point, and a decimal point or `e` or `E` has appeared before, return `false`. Otherwise, we increment $dot$ by one;\n- If the current character is `e` or `E`, and `e` or `E` has appeared before, or if the current character is at the beginning or end of the string, return `false`. Otherwise, we increment $e$ by one; then check if the next character is a positive or negative sign, if it is, move the pointer $j$ one step forward. If the pointer $j$ has reached the end of the string at this point, return `false`;\n- If the current character is not a number, return `false`.\n\nAfter traversing the string, return `true`.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the string." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 66, "explanations": { "1": "We start traversing from the last element of the array, add one to the current element, and then take the modulus by $10$. If the result is not $0$, it means that there is no carry for the current element, and we can directly return the array. Otherwise, the current element is $0$ and needs to be carried over. We continue to traverse the previous element and repeat the above operation. If we still haven't returned after traversing the array, it means that all elements in the array are $0$, and we need to insert a $1$ at the beginning of the array.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. Ignoring the space consumption of the answer, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 67, "explanations": { "1": "We use a variable $\\textit{carry}$ to record the current carry, and two pointers $i$ and $j$ to point to the end of $a$ and $b$ respectively, and add them bit by bit from the end to the beginning.\n\nThe time complexity is $O(\\max(m, n))$, where $m$ and $n$ are the lengths of strings $a$ and $b$ respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\max(m, n))", "space_complexity": "O(1)" }, { "problem_id": 68, "explanations": { "1": "We can simulate the process according to the problem's requirements. Note that if it is the last line, or if there is only one word in the line, then we should align to the left. Otherwise, we should distribute the spaces evenly.\n\nThe time complexity is $O(L)$, and the space complexity is $O(L)$. Here, $L$ is the sum of the lengths of all words." }, "is_english": true, "time_complexity": "O(L)", "space_complexity": "O(L)" }, { "problem_id": 69, "explanations": { "1": "We define the left boundary of the binary search as $l = 0$ and the right boundary as $r = x$, then we search for the square root within the range $[l, r]$.\n\nIn each step of the search, we find the middle value $mid = (l + r + 1) / 2$. If $mid > x / mid$, it means the square root is within the range $[l, mid - 1]$, so we set $r = mid - 1$. Otherwise, it means the square root is within the range $[mid, r]$, so we set $l = mid$.\n\nAfter the search ends, we return $l$.\n\nThe time complexity is $O(\\log x)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log x)", "space_complexity": "O(1)" }, { "problem_id": 70, "explanations": { "1": "We define $f[i]$ to represent the number of ways to climb to the $i$-th step, then $f[i]$ can be transferred from $f[i - 1]$ and $f[i - 2]$, that is:\n\n$$\nf[i] = f[i - 1] + f[i - 2]\n$$\n\nThe initial conditions are $f[0] = 1$ and $f[1] = 1$, that is, the number of ways to climb to the 0th step is 1, and the number of ways to climb to the 1st step is also 1.\n\nThe answer is $f[n]$.\n\nSince $f[i]$ is only related to $f[i - 1]$ and $f[i - 2]$, we can use two variables $a$ and $b$ to maintain the current number of ways, reducing the space complexity to $O(1)$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$.", "2": "We set $Fib(n)$ to represent a $1 \\times 2$ matrix $\\begin{bmatrix} F_n & F_{n - 1} \\end{bmatrix}$, where $F_n$ and $F_{n - 1}$ are the $n$-th and $(n - 1)$-th Fibonacci numbers respectively.\n\nWe hope to derive $Fib(n)$ based on $Fib(n-1) = \\begin{bmatrix} F_{n - 1} & F_{n - 2} \\end{bmatrix}$. That is to say, we need a matrix $base$, so that $Fib(n - 1) \\times base = Fib(n)$, that is:\n\n$$\n\\begin{bmatrix}\nF_{n - 1} & F_{n - 2}\n\\end{bmatrix} \\times base = \\begin{bmatrix} F_n & F_{n - 1} \\end{bmatrix}\n$$\n\nSince $F_n = F_{n - 1} + F_{n - 2}$, the first column of the matrix $base$ is:\n\n$$\n\\begin{bmatrix}\n1 \\\\\n1\n\\end{bmatrix}\n$$\n\nThe second column is:\n\n$$\n\\begin{bmatrix}\n1 \\\\\n0\n\\end{bmatrix}\n$$\n\nTherefore:\n\n$$\n\\begin{bmatrix} F_{n - 1} & F_{n - 2} \\end{bmatrix} \\times \\begin{bmatrix}1 & 1 \\\\ 1 & 0\\end{bmatrix} = \\begin{bmatrix} F_n & F_{n - 1} \\end{bmatrix}\n$$\n\nWe define the initial matrix $res = \\begin{bmatrix} 1 & 1 \\end{bmatrix}$, then $F_n$ is equal to the first element of the first row of the result matrix of $res$ multiplied by $base^{n - 1}$. We can solve it using matrix quick power.\n\nThe time complexity is $O(\\log n)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 71, "explanations": { "1": "We first split the path into a number of substrings split by `'/'`. Then, we traverse each substring and perform the following operations based on the content of the substring:\n\n- If the substring is empty or `'.'`, no operation is performed because `'.'` represents the current directory.\n- If the substring is `'..'`, the top element of the stack is popped, because `'..'` represents the parent directory.\n- If the substring is other strings, the substring is pushed into the stack, because the substring represents the subdirectory of the current directory.\n\nFinally, we concatenate all the elements in the stack from the bottom to the top of the stack to form a string, which is the simplified canonical path.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of the path." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 72, "explanations": { "1": "We define $f[i][j]$ as the minimum number of operations to convert $word1$ of length $i$ to $word2$ of length $j$. $f[i][0] = i$, $f[0][j] = j$, $i \\in [1, m], j \\in [0, n]$.\n\nWe consider $f[i][j]$:\n\n- If $word1[i - 1] = word2[j - 1]$, then we only need to consider the minimum number of operations to convert $word1$ of length $i - 1$ to $word2$ of length $j - 1$, so $f[i][j] = f[i - 1][j - 1]$;\n- Otherwise, we can consider insert, delete, and replace operations, then $f[i][j] = \\min(f[i - 1][j], f[i][j - 1], f[i - 1][j - 1]) + 1$.\n\nFinally, we can get the state transition equation:\n\n$$\nf[i][j] = \\begin{cases}\ni, & \\textit{if } j = 0 \\\\\nj, & \\textit{if } i = 0 \\\\\nf[i - 1][j - 1], & \\textit{if } word1[i - 1] = word2[j - 1] \\\\\n\\min(f[i - 1][j], f[i][j - 1], f[i - 1][j - 1]) + 1, & \\textit{otherwise}\n\\end{cases}\n$$\n\nFinally, we return $f[m][n]$.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. $m$ and $n$ are the lengths of $word1$ and $word2$ respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 73, "explanations": { "1": "We use arrays `rows` and `cols` to mark the rows and columns to be cleared.\n\nThen traverse the matrix again, and clear the elements in the rows and columns marked in `rows` and `cols`.\n\nThe time complexity is $O(m\\times n)$, and the space complexity is $O(m+n)$. Where $m$ and $n$ are the number of rows and columns of the matrix respectively.", "2": "In the first method, we use an additional array to mark the rows and columns to be cleared. In fact, we can also use the first row and first column of the matrix to mark them, without creating an additional array.\n\nSince the first row and the first column are used to mark, their values ​​may change due to the mark, so we need additional variables $i0$, $j0$ to mark whether the first row and the first column need to be cleared.\n\nThe time complexity is $O(m\\times n)$, and the space complexity is $O(1)$. Where $m$ and $n$ are the number of rows and columns of the matrix respectively." }, "is_english": true, "time_complexity": "O(m\\times n)", "space_complexity": "O(m+n)" }, { "problem_id": 74, "explanations": { "1": "We can logically unfold the two-dimensional matrix and then perform binary search.\n\nThe time complexity is $O(\\log(m \\times n))$, where $m$ and $n$ are the number of rows and columns of the matrix, respectively. The space complexity is $O(1)$.", "2": "Here, we start searching from the bottom left corner and move towards the top right direction. We compare the current element $matrix[i][j]$ with $target$:\n\n- If $matrix[i][j] = target$, we have found the target value and return `true`.\n- If $matrix[i][j] > target$, all elements to the right of the current position in this row are greater than target, so we should move the pointer $i$ upwards, i.e., $i = i - 1$.\n- If $matrix[i][j] < target$, all elements above the current position in this column are less than target, so we should move the pointer $j$ to the right, i.e., $j = j + 1$.\n\nIf we still can't find $target$ after the search, return `false`.\n\nThe time complexity is $O(m + n)$, where $m$ and $n$ are the number of rows and columns of the matrix, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log(m \\times n))", "space_complexity": "O(1)" }, { "problem_id": 75, "explanations": { "1": "We define three pointers $i$, $j$, and $k$. Pointer $i$ is used to point to the rightmost boundary of the elements with a value of $0$ in the array, and pointer $j$ is used to point to the leftmost boundary of the elements with a value of $2$ in the array. Initially, $i=-1$, $j=n$. Pointer $k$ is used to point to the current element being traversed, initially $k=0$.\n\nWhen $k < j$, we perform the following operations:\n\n- If $nums[k] = 0$, then swap it with $nums[i+1]$, then increment both $i$ and $k$ by $1$;\n- If $nums[k] = 2$, then swap it with $nums[j-1]$, then decrement $j$ by $1$;\n- If $nums[k] = 1$, then increment $k$ by $1$.\n\nAfter the traversal, the elements in the array are divided into three parts: $[0,i]$, $[i+1,j-1]$ and $[j,n-1]$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. Only one traversal of the array is needed. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 76, "explanations": { "1": "We use a hash table or array $\\textit{need}$ to count the occurrences of each character in string $t$, and another hash table or array $\\textit{window}$ to count the occurrences of each character in the sliding window. Additionally, we define two pointers $l$ and $r$ to point to the left and right boundaries of the window, a variable $\\textit{cnt}$ to represent how many characters from $t$ are already included in the window, and variables $k$ and $\\textit{mi}$ to represent the starting position and length of the minimum window substring.\n\nWe traverse the string $s$ from left to right. For the current character $s[r]$:\n\n- We add it to the window, i.e., $\\textit{window}[s[r]] = \\textit{window}[s[r]] + 1$. If $\\textit{need}[s[r]] \\geq \\textit{window}[s[r]]$, it means $s[r]$ is a \"necessary character\", and we increment $\\textit{cnt}$ by one.\n- If $\\textit{cnt}$ equals the length of $t$, it means the window already contains all characters from $t$, and we can try to update the starting position and length of the minimum window substring. If $r - l + 1 < \\textit{mi}$, it means the current window represents a shorter substring, so we update $\\textit{mi} = r - l + 1$ and $k = l$.\n- Then, we try to move the left boundary $l$. If $\\textit{need}[s[l]] \\geq \\textit{window}[s[l]]$, it means $s[l]$ is a \"necessary character\", and moving the left boundary will remove $s[l]$ from the window. Therefore, we need to decrement $\\textit{cnt}$ by one, update $\\textit{window}[s[l]] = \\textit{window}[s[l]] - 1$, and move $l$ one position to the right.\n- If $\\textit{cnt}$ is not equal to the length of $t$, it means the window does not yet contain all characters from $t$, so we do not need to move the left boundary. Instead, we move $r$ one position to the right and continue traversing.\n\nAfter the traversal, if no minimum window substring is found, return an empty string. Otherwise, return $s[k:k+\\textit{mi}]$.\n\nThe time complexity is $O(m + n)$, and the space complexity is $O(|\\Sigma|)$. Here, $m$ and $n$ are the lengths of strings $s$ and $t$, respectively; and $|\\Sigma|$ is the size of the character set, which is $128$ in this problem." }, "is_english": true, "time_complexity": "O(m + n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 77, "explanations": { "1": "We design a function $dfs(i)$, which represents starting the search from number $i$, with the current search path as $t$, and the answer as $ans$.\n\nThe execution logic of the function $dfs(i)$ is as follows:\n\n- If the length of the current search path $t$ equals $k$, then add the current search path to the answer and return.\n- If $i \\gt n$, it means the search has ended, return.\n- Otherwise, we can choose to add the number $i$ to the search path $t$, and then continue the search, i.e., execute $dfs(i + 1)$, and then remove the number $i$ from the search path $t$; or we do not add the number $i$ to the search path $t$, and directly execute $dfs(i + 1)$.\n\nThe above method is actually enumerating whether to select the current number or not, and then recursively searching the next number. We can also enumerate the next number $j$ to be selected, where $i \\leq j \\leq n$. If the next number to be selected is $j$, then we add the number $j$ to the search path $t$, and then continue the search, i.e., execute $dfs(j + 1)$, and then remove the number $j$ from the search path $t$.\n\nIn the main function, we start the search from number $1$, i.e., execute $dfs(1)$.\n\nThe time complexity is $(C_n^k \\times k)$, and the space complexity is $O(k)$. Here, $C_n^k$ represents the combination number.\n\nSimilar problems:\n\n- [39. Combination Sum](https://github.com/doocs/leetcode/blob/main/solution/0000-0099/0039.Combination%20Sum/README_EN.md)\n- [40. Combination Sum II](https://github.com/doocs/leetcode/blob/main/solution/0000-0099/0040.Combination%20Sum%20II/README_EN.md)\n- [216. Combination Sum III](https://github.com/doocs/leetcode/blob/main/solution/0200-0299/0216.Combination%20Sum%20III/README_EN.md)", "2": "" }, "is_english": true, "time_complexity": "O(k)", "space_complexity": "O(k)" }, { "problem_id": 78, "explanations": { "1": "We design a function $dfs(i)$, which represents starting the search from the $i$th element of the array for all subsets. The execution logic of the function $dfs(i)$ is as follows:\n\n- If $i = n$, it means the current search has ended. Add the current subset $t$ to the answer array $ans$, and then return.\n- Otherwise, we can choose not to select the current element and directly execute $dfs(i + 1)$; or we can choose the current element, i.e., add the current element $nums[i]$ to the subset $t$, and then execute $dfs(i + 1)$. Note that we need to remove $nums[i]$ from the subset $t$ after executing $dfs(i + 1)$ (backtracking).\n\nIn the main function, we call $dfs(0)$, i.e., start searching all subsets from the first element of the array. Finally, return the answer array $ans$.\n\nThe time complexity is $O(n \\times 2^n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array. There are a total of $2^n$ subsets, and each subset takes $O(n)$ time to construct.", "2": "We can also use the method of binary enumeration to get all subsets.\n\nWe can use $2^n$ binary numbers to represent all subsets of $n$ elements. For the current binary number $mask$, if the $i$th bit is $1$, it means that the $i$th element is selected, otherwise it means that the $i$th element is not selected.\n\nThe time complexity is $O(n \\times 2^n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array. There are a total of $2^n$ subsets, and each subset takes $O(n)$ time to construct." }, "is_english": true, "time_complexity": "O(n \\times 2^n)", "space_complexity": "O(n)" }, { "problem_id": 79, "explanations": { "1": "We can enumerate each position $(i, j)$ in the grid as the starting point of the search, and then start a depth-first search from the starting point. If we can search to the end of the word, it means the word exists, otherwise, it means the word does not exist.\n\nTherefore, we design a function $dfs(i, j, k)$, which represents whether we can successfully search from the $(i, j)$ position of the grid, starting from the $k$th character of the word. The execution steps of the function $dfs(i, j, k)$ are as follows:\n\n- If $k = |word|-1$, it means that we have searched to the last character of the word. At this time, we only need to judge whether the character at the $(i, j)$ position of the grid is equal to $word[k]$. If they are equal, it means the word exists, otherwise, it means the word does not exist. Whether the word exists or not, there is no need to continue to search, so return the result directly.\n- Otherwise, if the $word[k]$ character is not equal to the character at the $(i, j)$ position of the grid, it means that the search failed this time, so return `false` directly.\n- Otherwise, we temporarily store the character at the $(i, j)$ position of the grid in $c$, and then modify the character at this position to a special character `'0'`, indicating that the character at this position has been used to prevent it from being reused in subsequent searches. Then we start from the up, down, left, and right directions of the $(i, j)$ position to search for the $k+1$th character in the grid. If any direction is successful, it means the search is successful, otherwise, it means the search failed. At this time, we need to restore the character at the $(i, j)$ position of the grid, that is, put $c$ back to the $(i, j)$ position (backtracking).\n\nIn the main function, we enumerate each position $(i, j)$ in the grid as the starting point. If calling $dfs(i, j, 0)$ returns `true`, it means the word exists, otherwise, it means the word does not exist, so return `false`.\n\nThe time complexity is $O(m \\times n \\times 3^k)$, and the space complexity is $O(\\min(m \\times n, k))$. Here, $m$ and $n$ are the number of rows and columns of the grid, respectively; and $k$ is the length of the string $word$." }, "is_english": true, "time_complexity": "O(m \\times n \\times 3^k)", "space_complexity": "O(\\min(m \\times n, k))" }, { "problem_id": 80, "explanations": { "1": "We use a variable $k$ to record the current length of the array that has been processed. Initially, $k=0$, representing an empty array.\n\nThen we traverse the array from left to right. For each element $x$ we traverse, if $k < 2$ or $x \\neq nums[k-2]$, we put $x$ in the position of $nums[k]$, and then increment $k$ by $1$. Otherwise, $x$ is the same as $nums[k-2]$, we directly skip this element. Continue to traverse until the entire array is traversed.\n\nIn this way, when the traversal ends, the first $k$ elements in $nums$ are the answer we want, and $k$ is the length of the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the array.\n\nSupplement:\n\nThe original problem requires that the same number appears at most $2$ times. We can extend it to keep at most $k$ identical numbers.\n\n- Since the same number can be kept at most $k$ times, we can directly keep the first $k$ elements of the original array;\n- For the later numbers, the premise of being able to keep them is: the current number $x$ compares with the $k$th element from the end of the previously kept numbers. If they are different, keep it, otherwise skip it.\n\nSimilar problems:\n\n- [26. Remove Duplicates from Sorted Array](https://github.com/doocs/leetcode/blob/main/solution/0000-0099/0026.Remove%20Duplicates%20from%20Sorted%20Array/README_EN.md)" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 81, "explanations": { "1": "We define the left boundary of the binary search as $l = 0$ and the right boundary as $r = n - 1$, where $n$ is the length of the array.\n\nEach time during the binary search, we get the current midpoint $\\textit{mid} = (l + r) / 2$.\n\n- If $\\textit{nums}[\\textit{mid}] > \\textit{nums}[r]$, it means $[l, \\textit{mid}]$ is ordered. If $\\textit{nums}[l] \\le \\textit{target} \\le \\textit{nums}[\\textit{mid}]$, it means $\\textit{target}$ is in $[l, \\textit{mid}]$. Otherwise, $\\textit{target}$ is in $[\\textit{mid} + 1, r]$.\n- If $\\textit{nums}[\\textit{mid}] < \\textit{nums}[r]$, it means $[\\textit{mid} + 1, r]$ is ordered. If $\\textit{nums}[\\textit{mid}] < \\textit{target} \\le \\textit{nums}[r]$, it means $\\textit{target}$ is in $[\\textit{mid} + 1, r]$. Otherwise, $\\textit{target}$ is in $[l, \\textit{mid}]$.\n- If $\\textit{nums}[\\textit{mid}] = \\textit{nums}[r]$, it means the elements $\\textit{nums}[\\textit{mid}]$ and $\\textit{nums}[r]$ are equal. In this case, we cannot determine which interval $\\textit{target}$ is in, so we can only decrease $r$ by $1$.\n\nAfter the binary search, if $\\textit{nums}[l] = \\textit{target}$, it means the target value $\\textit{target}$ exists in the array. Otherwise, it does not exist.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 82, "explanations": { "1": "First, we create a dummy head node $dummy$, and set $dummy.next = head$. Then we create a pointer $pre$ pointing to $dummy$, and a pointer $cur$ pointing to $head$, and start traversing the linked list.\n\nWhen the node value pointed by $cur$ is the same as the node value pointed by $cur.next$, we let $cur$ keep moving forward until the node value pointed by $cur$ is different from the node value pointed by $cur.next$. At this point, we check whether $pre.next$ is equal to $cur$. If they are equal, it means there are no duplicate nodes between $pre$ and $cur$, so we move $pre$ to the position of $cur$; otherwise, it means there are duplicate nodes between $pre$ and $cur$, so we set $pre.next$ to $cur.next$. Then we continue to move $cur$ forward. Continue the above operation until $cur$ is null, and the traversal ends.\n\nFinally, return $dummy.next$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the linked list." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 83, "explanations": { "1": "We use a pointer $cur$ to traverse the linked list. If the element corresponding to the current $cur$ is the same as the element corresponding to $cur.next$, we set the $next$ pointer of $cur$ to point to the next node of $cur.next$. Otherwise, it means that the element corresponding to $cur$ in the linked list is not duplicated, so we can move the $cur$ pointer to the next node.\n\nAfter the traversal ends, return the head node of the linked list.\n\nThe time complexity is $O(n)$, where $n$ is the length of the linked list. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 84, "explanations": { "1": "We can enumerate the height $h$ of each bar as the height of the rectangle. Using a monotonic stack, we find the index $left_i$, $right_i$ of the first bar with a height less than $h$ to the left and right. The area of the rectangle at this time is $h \\times (right_i-left_i-1)$. We can find the maximum value.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ represents the length of $heights$.\n\nCommon model of monotonic stack: Find the **nearest** number to the left/right of each number that is **larger/smaller** than it. Template:\n\n```python\nstk = []\nfor i in range(n):\n while stk and check(stk[-1], i):\n stk.pop()\n stk.append(i)\n```", "2": "" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 85, "explanations": { "1": "We can treat each row as the base of a histogram and calculate the maximum area of the histogram for each row.\n\nSpecifically, we maintain an array $\\textit{heights}$ with the same length as the number of columns in the matrix, where $\\textit{heights}[j]$ represents the height of the column at the $j$-th position with the current row as the base. For each row, we iterate through each column:\n\n- If the current element is '1', increment $\\textit{heights}[j]$ by $1$.\n- If the current element is '0', set $\\textit{heights}[j]$ to $0$.\n\nThen, we use the monotonic stack algorithm to calculate the maximum rectangle area of the current histogram and update the answer.\n\nThe specific steps of the monotonic stack are as follows:\n\n1. Initialize an empty stack $\\textit{stk}$ to store the indices of the columns.\n2. Initialize two arrays $\\textit{left}$ and $\\textit{right}$, representing the index of the first column to the left and right of each column that is shorter than the current column.\n3. Iterate through the heights array $\\textit{heights}$, first calculating the index of the first column to the left of each column that is shorter than the current column, and store it in $\\textit{left}$.\n4. Then iterate through the heights array $\\textit{heights}$ in reverse order, calculating the index of the first column to the right of each column that is shorter than the current column, and store it in $\\textit{right}$.\n5. Finally, calculate the maximum rectangle area for each column and update the answer.\n\nThe time complexity is $O(m \\times n)$, where $m$ is the number of rows in $matrix$ and $n$ is the number of columns in $matrix$." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": null }, { "problem_id": 86, "explanations": { "1": "We create two linked lists $l$ and $r$, one to store nodes less than $x$ and the other to store nodes greater than or equal to $x$. Then we concatenate them.\n\nThe time complexity is $O(n)$, where $n$ is the length of the original linked list. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 87, "explanations": { "1": "We design a function $dfs(i, j, k)$, which means whether the substring starting from $i$ with length $k$ in $s_1$ can be converted into the substring starting from $j$ with length $k$ in $s_2$. If it can be converted, return `true`, otherwise return `false`. The answer is $dfs(0, 0, n)$, where $n$ is the length of the string.\n\nThe calculation method of function $dfs(i, j, k)$ is as follows:\n\n- If $k=1$, then we only need to judge whether $s_1[i]$ and $s_2[j]$ are equal. If they are equal, return `true`, otherwise return `false`;\n- If $k \\gt 1$, we enumerate the length of the split part $h$, then there are two cases: if the two substrings of the split are not swapped, then it is $dfs(i, j, h) \\land dfs(i+h, j+h, k-h)$; if the two substrings of the split are swapped, then it is $dfs(i, j+k-h, h) \\land dfs(i+h, j, k-h)$. If one of the two cases is true, then $dfs(i, j, k)$ is true, return `true`, otherwise return `false`.\n\nFinally, we return $dfs(0, 0, n)$.\n\nIn order to avoid repeated calculation, we can use memory search.\n\nThe time complexity is $O(n^4)$, and the space complexity is $O(n^3)$. Where $n$ is the length of the string.", "2": "We define $f[i][j][k]$ as whether the substring of length $k$ starting from $i$ of string $s_1$ can be transformed into the substring of length $k$ starting from $j$ of string $s_2$. Then the answer is $f[0][0][n]$, where $n$ is the length of the string.\n\nFor substring of length $1$, if $s_1[i] = s_2[j]$, then $f[i][j][1] = true$, otherwise $f[i][j][1] = false$.\n\nNext, we enumerate the length $k$ of the substring from small to large, and enumerate $i$ from $0$, and enumerate $j$ from $0$. If $f[i][j][h] \\land f[i + h][j + h][k - h]$ or $f[i][j + k - h][h] \\land f[i + h][j][k - h]$ is true, then $f[i][j][k]$ is also true.\n\nFinally, we return $f[0][0][n]$.\n\nThe time complexity is $O(n^4)$, and the space complexity is $O(n^3)$. Where $n$ is the length of the string." }, "is_english": true, "time_complexity": "O(n^4)", "space_complexity": "O(n^3)" }, { "problem_id": 88, "explanations": { "1": "We use two pointers $i$ and $j$ pointing to the end of two arrays, and a pointer $k$ pointing to the end of the merged array.\n\nEvery time we compare the two elements at the end of the two arrays, and move the larger one to the end of the merged array. Then we move the pointer one step forward, and repeat this process until the two pointers reach the start of the arrays.\n\nThe time complexity is $O(m + n)$, where $m$ and $n$ are the lengths of two arrays. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m + n)", "space_complexity": "O(1)" }, { "problem_id": 89, "explanations": { "1": "Gray code is a type of encoding method that we often encounter in engineering. Its basic feature is that only one bit of binary number is different between any two adjacent codes.\n\nThe rule for converting binary code to binary Gray code is to keep the highest bit of the binary code as the highest bit of the Gray code, and the second highest bit of the Gray code is the XOR of the highest bit and the second highest bit of the binary code. The calculation of the remaining bits of the Gray code is similar to the second highest bit.\n\nAssume that a binary number is represented as $B_{n-1}B_{n-2}...B_2B_1B_0$, and its Gray code is represented as $G_{n-1}G_{n-2}...G_2G_1G_0$. The highest bit is retained, so $G_{n-1} = B_{n-1}$; and the other bits $G_i = B_{i+1} \\oplus B_{i}$, where $i=0,1,2..,n-2$.\n\nTherefore, for an integer $x$, we can use the function $gray(x)$ to get its Gray code:\n\n```java\nint gray(x) {\n return x ^ (x >> 1);\n}\n```\n\nWe directly map the integers $[0,..2^n - 1]$ to the corresponding Gray codes to get the answer array.\n\nThe time complexity is $O(2^n)$, where $n$ is the integer given in the problem. Ignoring the space consumption of the answer, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(2^n)", "space_complexity": "O(1)" }, { "problem_id": 90, "explanations": { "1": "We can first sort the array $\\textit{nums}$ to facilitate deduplication.\n\nThen, we design a function $\\textit{dfs}(i)$, which represents the current search for subsets starting from the $i$-th element. The execution logic of the function $\\textit{dfs}(i)$ is as follows:\n\nIf $i \\geq n$, it means all elements have been searched, add the current subset to the answer array, and end the recursion.\n\nIf $i < n$, add the $i$-th element to the subset, execute $\\textit{dfs}(i + 1)$, then remove the $i$-th element from the subset. Next, we check if the $i$-th element is the same as the next element. If they are the same, skip the element in a loop until we find the first element different from the $i$-th element, then execute $\\textit{dfs}(i + 1)$.\n\nFinally, we only need to call $\\textit{dfs}(0)$ and return the answer array.\n\nThe time complexity is $O(n \\times 2^n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$.", "2": "Similar to Solution 1, we first sort the array $\\textit{nums}$ to facilitate deduplication.\n\nNext, we enumerate a binary number $\\textit{mask}$ in the range $[0, 2^n)$, where the binary representation of $\\textit{mask}$ is an $n$-bit bit string. If the $i$-th bit of $\\textit{mask}$ is $1$, it means selecting $\\textit{nums}[i]$, and $0$ means not selecting $\\textit{nums}[i]$. Note that if the $(i - 1)$-th bit of $\\textit{mask}$ is $0$ and $\\textit{nums}[i] = \\textit{nums}[i - 1]$, it means that the $i$-th element is the same as the $(i - 1)$-th element in the current enumeration scheme. To avoid duplication, we skip this case. Otherwise, we add the subset corresponding to $\\textit{mask}$ to the answer array.\n\nAfter the enumeration, we return the answer array.\n\nThe time complexity is $O(n \\times 2^n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times 2^n)", "space_complexity": "O(n)" }, { "problem_id": 91, "explanations": { "1": "We define $f[i]$ to represent the number of decoding methods for the first $i$ characters of the string. Initially, $f[0]=1$, and the rest $f[i]=0$.\n\nConsider how $f[i]$ transitions.\n\n- If the $i$th character (i.e., $s[i-1]$) forms a code on its own, it corresponds to one decoding method, i.e., $f[i]=f[i-1]$. The premise is $s[i-1] \\neq 0$.\n- If the string formed by the $i-1$th character and the $i$th character is within the range $[1,26]$, then they can be treated as a whole, corresponding to one decoding method, i.e., $f[i] = f[i] + f[i-2]$. The premise is $s[i-2] \\neq 0$, and $s[i-2]s[i-1]$ is within the range $[1,26]$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 92, "explanations": { "1": "Define a dummy head node `dummy`, pointing to the head node `head` of the linked list. Then define a pointer `pre` pointing to `dummy`. Start traversing the linked list from the dummy head node. When you traverse to the `left` node, point `pre` to this node. Then start traversing `right - left + 1` times from this node, and insert the nodes you traverse into the back of `pre`. Finally, return `dummy.next`.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the linked list." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 93, "explanations": { "1": "We define a function $dfs(i)$, which represents the list of IP addresses that can be formed starting from the $i$th position of string $s$.\n\nThe execution steps of function $dfs(i)$ are as follows:\n\nIf $i$ is greater than or equal to the length of string $s$, it means that we have completed the splicing of four segments of the IP address. At this point, we need to check whether it meets the requirements of the four segments of the IP address. If it does, add the current $IP$ to the answer.\n\nIf $i$ is less than the length of string $s$, it means that we still need to splice a segment of the IP address. At this point, we need to determine the value of this segment of the IP address. If the value is greater than $255$, or the current position $i$ is $0$ and the value of several positions after $i$ is greater than $0$, it means that it does not meet the requirements, so we return directly. Otherwise, add it to the IP address list, and continue to search for the next segment of the IP address.\n\nThe time complexity is $O(n \\times 3^4)$, and the space complexity is $O(n)$. Here, $n$ is the length of string $s$." }, "is_english": true, "time_complexity": "O(n \\times 3^4)", "space_complexity": "O(n)" }, { "problem_id": 94, "explanations": { "1": "We first recursively traverse the left subtree, then visit the root node, and finally recursively traverse the right subtree.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree, and the space complexity mainly depends on the stack space of the recursive call.", "2": "The non-recursive approach is as follows:\n\n1. Define a stack `stk`.\n2. Push the left nodes of the tree into the stack in sequence.\n3. When the left node is null, pop and process the top element of the stack.\n4. Repeat steps 2-3.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree, and the space complexity mainly depends on the stack space.", "3": "Morris traversal does not require a stack, so the space complexity is $O(1)$. The core idea is:\n\nTraverse the binary tree nodes,\n\n1. If the left subtree of the current node `root` is null, **add the current node value to the result list `ans`**, and update the current node to `root.right`.\n2. If the left subtree of the current node `root` is not null, find the rightmost node `prev` of the left subtree (which is the predecessor node of the `root` node in in-order traversal):\n - If the right subtree of the predecessor node `prev` is null, point the right subtree of the predecessor node to the current node `root`, and update the current node to `root.left`.\n - If the right subtree of the predecessor node `prev` is not null, **add the current node value to the result list `ans`**, then point the right subtree of the predecessor node to null (i.e., disconnect `prev` and `root`), and update the current node to `root.right`.\n3. Repeat the above steps until the binary tree node is null, and the traversal ends.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 95, "explanations": { "1": "We design a function $dfs(i, j)$ that returns all feasible binary search trees composed of $[i, j]$, so the answer is $dfs(1, n)$.\n\nThe execution steps of the function $dfs(i, j)$ are as follows:\n\n1. If $i > j$, it means that there are no numbers to form a binary search tree at this time, so return a list consisting of a null node.\n2. If $i \\leq j$, we enumerate the numbers $v$ in $[i, j]$ as the root node. The left subtree of the root node $v$ is composed of $[i, v - 1]$, and the right subtree is composed of $[v + 1, j]$. Finally, we take the Cartesian product of all combinations of the left and right subtrees, i.e., $left \\times right$, add the root node $v$, and get all binary search trees with $v$ as the root node.\n\nThe time complexity is $O(n \\times G(n))$, and the space complexity is $O(n \\times G(n))$. Where $G(n)$ is the Catalan number." }, "is_english": true, "time_complexity": "O(n \\times G(n))", "space_complexity": "O(n \\times G(n))" }, { "problem_id": 96, "explanations": { "1": "We define $f[i]$ to represent the number of binary search trees that can be generated from $[1, i]$. Initially, $f[0] = 1$, and the answer is $f[n]$.\n\nWe can enumerate the number of nodes $i$, then the number of nodes in the left subtree $j \\in [0, i - 1]$, and the number of nodes in the right subtree $k = i - j - 1$. The number of combinations of the number of nodes in the left subtree and the right subtree is $f[j] \\times f[k]$, so $f[i] = \\sum_{j = 0}^{i - 1} f[j] \\times f[i - j - 1]$.\n\nFinally, return $f[n]$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 97, "explanations": { "1": "Let's denote the length of string $s_1$ as $m$ and the length of string $s_2$ as $n$. If $m + n \\neq |s_3|$, then $s_3$ is definitely not an interleaving string of $s_1$ and $s_2$, so we return `false`.\n\nNext, we design a function $dfs(i, j)$, which represents whether the remaining part of $s_3$ can be interleaved from the $i$th character of $s_1$ and the $j$th character of $s_2$. The answer is $dfs(0, 0)$.\n\nThe calculation process of function $dfs(i, j)$ is as follows:\n\nIf $i \\geq m$ and $j \\geq n$, it means that both $s_1$ and $s_2$ have been traversed, so we return `true`.\n\nIf $i < m$ and $s_1[i] = s_3[i + j]$, it means that the character $s_1[i]$ is part of $s_3[i + j]$. Therefore, we recursively call $dfs(i + 1, j)$ to check whether the next character of $s_1$ can match the current character of $s_2$. If it can match, we return `true`.\n\nSimilarly, if $j < n$ and $s_2[j] = s_3[i + j]$, it means that the character $s_2[j]$ is part of $s_3[i + j]$. Therefore, we recursively call $dfs(i, j + 1)$ to check whether the next character of $s_2$ can match the current character of $s_1$. If it can match, we return `true`.\n\nOtherwise, we return `false`.\n\nTo avoid repeated calculations, we can use memoization search.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the lengths of strings $s_1$ and $s_2$ respectively.", "2": "We can convert the memoization search in Solution 1 into dynamic programming.\n\nWe define $f[i][j]$ to represent whether the first $i$ characters of string $s_1$ and the first $j$ characters of string $s_2$ can interleave to form the first $i + j$ characters of string $s_3$. When transitioning states, we can consider whether the current character is obtained from the last character of $s_1$ or the last character of $s_2$. Therefore, we have the state transition equation:\n\n$$\nf[i][j] = \\begin{cases}\nf[i - 1][j] & \\textit{if } s_1[i - 1] = s_3[i + j - 1] \\\\\n\\textit{or } f[i][j - 1] & \\textit{if } s_2[j - 1] = s_3[i + j - 1] \\\\\n\\textit{false} & \\textit{otherwise}\n\\end{cases}\n$$\n\nwhere $f[0][0] = \\textit{true}$ indicates that an empty string is an interleaving string of two empty strings.\n\nThe answer is $f[m][n]$.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the lengths of strings $s_1$ and $s_2$ respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 98, "explanations": { "1": "We can perform a recursive in-order traversal on the binary tree. If the result of the traversal is strictly ascending, then this tree is a binary search tree.\n\nTherefore, we use a variable `prev` to save the last node we traversed. Initially, `prev = -∞`. Then we recursively traverse the left subtree. If the left subtree is not a binary search tree, we directly return `False`. Otherwise, we check whether the value of the current node is greater than `prev`. If not, we return `False`. Otherwise, we update `prev` to the value of the current node, and then recursively traverse the right subtree.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 99, "explanations": { "1": "In-order traversal of a binary search tree results in an increasing sequence. If two nodes' values are mistakenly swapped, there will definitely be two reverse pairs in the sequence obtained from the in-order traversal. We use `first` and `second` to record the smaller and larger values of these two reverse pairs, respectively. Finally, swapping the values of these two nodes will correct the mistake.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary search tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 100, "explanations": { "1": "We can use the DFS recursive method to solve this problem.\n\nFirst, determine whether the root nodes of the two binary trees are the same. If both root nodes are null, then the two binary trees are the same. If only one of the root nodes is null, then the two binary trees are definitely different. If both root nodes are not null, then determine whether their values are the same. If they are not the same, then the two binary trees are definitely different. If they are the same, then determine whether the left subtrees of the two binary trees are the same and whether the right subtrees are the same. The two binary trees are the same only when all the above conditions are met.\n\nThe time complexity is $O(\\min(m, n))$, and the space complexity is $O(\\min(m, n))$. Here, $m$ and $n$ are the number of nodes in the two binary trees, respectively. The space complexity mainly depends on the number of layers of recursive calls, which will not exceed the number of nodes in the smaller binary tree.", "2": "We can also use the BFS iterative method to solve this problem.\n\nFirst, add the root nodes of the two binary trees to two queues. Each time, take out one node from each of the two queues and perform the following comparison operations. If the values of the two nodes are not the same, then the structures of the two binary trees are definitely different. If the values of the two nodes are the same, then determine whether the child nodes of the two nodes are null. If only the left child node of one node is null, then the structures of the two binary trees are definitely different. If only the right child node of one node is null, then the structures of the two binary trees are definitely different. If the structures of the left and right child nodes are the same, then add the left and right child nodes of the two nodes to the two queues respectively. For the next iteration, take out one node from each of the two queues for comparison. When both queues are empty at the same time, it means that we have compared all the nodes, and the structures of the two binary trees are completely the same.\n\nThe time complexity is $O(\\min(m, n))$, and the space complexity is $O(\\min(m, n))$. Here, $m$ and $n$ are the number of nodes in the two binary trees, respectively. The space complexity mainly depends on the number of elements in the queue, which will not exceed the number of nodes in the smaller binary tree." }, "is_english": true, "time_complexity": "O(\\min(m, n))", "space_complexity": "O(\\min(m, n))" }, { "problem_id": 101, "explanations": { "1": "We design a function $\\textit{dfs}(\\textit{root1}, \\textit{root2})$ to determine whether two binary trees are symmetric. The answer is $\\textit{dfs}(\\textit{root.left}, \\textit{root.right})$.\n\nThe logic of the function $\\textit{dfs}(\\textit{root1}, \\textit{root2})$ is as follows:\n\n- If both $\\textit{root1}$ and $\\textit{root2}$ are null, the two binary trees are symmetric, and we return `true`;\n- If only one of $\\textit{root1}$ and $\\textit{root2}$ is null, or $\\textit{root1.val} \\neq \\textit{root2.val}$, we return `false`;\n- Otherwise, we check whether the left subtree of $\\textit{root1}$ is symmetric with the right subtree of $\\textit{root2}$, and whether the right subtree of $\\textit{root1}$ is symmetric with the left subtree of $\\textit{root2}$, using recursion.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 102, "explanations": { "1": "We can use the BFS method to solve this problem. First, enqueue the root node, then continuously perform the following operations until the queue is empty:\n\n- Traverse all nodes in the current queue, store their values in a temporary array $t$, and then enqueue their child nodes.\n- Store the temporary array $t$ in the answer array.\n\nFinally, return the answer array.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 103, "explanations": { "1": "To implement zigzag level order traversal, we need to add a flag `left` on the basis of level order traversal. This flag is used to mark the order of the node values in the current level. If `left` is `true`, the node values of the current level are stored in the result array `ans` from left to right. If `left` is `false`, the node values of the current level are stored in the result array `ans` from right to left.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 104, "explanations": { "1": "Recursively traverse the left and right subtrees, calculate the maximum depth of the left and right subtrees, and then take the maximum value plus $1$.\n\nThe time complexity is $O(n)$, where $n$ is the number of nodes in the binary tree. Each node is traversed only once in the recursion." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": null }, { "problem_id": 105, "explanations": { "1": "The first node $preorder[0]$ in the pre-order sequence is the root node. We find the position $k$ of the root node in the in-order sequence, which can divide the in-order sequence into the left subtree $inorder[0..k]$ and the right subtree $inorder[k+1..]$.\n\nThrough the intervals of the left and right subtrees, we can calculate the number of nodes in the left and right subtrees, assumed to be $a$ and $b$. Then in the pre-order nodes, the $a$ nodes after the root node are the left subtree, and the $b$ nodes after that are the right subtree.\n\nTherefore, we design a function $dfs(i, j, n)$, where $i$ and $j$ represent the starting positions of the pre-order sequence and the in-order sequence, respectively, and $n$ represents the number of nodes. The return value of the function is the binary tree constructed with $preorder[i..i+n-1]$ as the pre-order sequence and $inorder[j..j+n-1]$ as the in-order sequence.\n\nThe execution process of the function $dfs(i, j, n)$ is as follows:\n\n- If $n \\leq 0$, it means there are no nodes, return a null node.\n- Take out the first node $v = preorder[i]$ of the pre-order sequence as the root node, and then use the hash table $d$ to find the position $k$ of the root node in the in-order sequence. Then the number of nodes in the left subtree is $k - j$, and the number of nodes in the right subtree is $n - k + j - 1$.\n- Recursively construct the left subtree $l = dfs(i + 1, j, k - j)$ and the right subtree $r = dfs(i + 1 + k - j, k + 1, n - k + j - 1)$.\n- Finally, return the binary tree with $v$ as the root node and $l$ and $r$ as the left and right subtrees, respectively.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 106, "explanations": { "1": "The last node in the post-order traversal is the root node. We can find the position of the root node in the in-order traversal, and then recursively construct the left and right subtrees.\n\nSpecifically, we first use a hash table $d$ to store the position of each node in the in-order traversal. Then we design a recursive function $dfs(i, j, n)$, where $i$ and $j$ represent the starting positions of the in-order and post-order traversals, respectively, and $n$ represents the number of nodes in the subtree. The function logic is as follows:\n\n- If $n \\leq 0$, it means the subtree is empty, return a null node.\n- Otherwise, take out the last node $v$ of the post-order traversal, and then find the position $k$ of $v$ in the in-order traversal using the hash table $d$. Then the number of nodes in the left subtree is $k - i$, and the number of nodes in the right subtree is $n - k + i - 1$.\n- Recursively construct the left subtree $dfs(i, j, k - i)$ and the right subtree $dfs(k + 1, j + k - i, n - k + i - 1)$, connect them to the root node, and finally return the root node.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 107, "explanations": { "1": "We can use the BFS (Breadth-First Search) method to solve this problem. First, enqueue the root node, then continuously perform the following operations until the queue is empty:\n\n- Traverse all nodes in the current queue, store their values in a temporary array $t$, and then enqueue their child nodes.\n- Store the temporary array $t$ in the answer array.\n\nFinally, return the reversed answer array.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 108, "explanations": { "1": "We design a recursive function $\\textit{dfs}(l, r)$, which represents that the values of the nodes to be constructed in the current binary search tree are within the index range $[l, r]$ of the array $\\textit{nums}$. This function returns the root node of the constructed binary search tree.\n\nThe execution process of the function $\\textit{dfs}(l, r)$ is as follows:\n\n1. If $l > r$, it means the current array is empty, so return `null`.\n2. If $l \\leq r$, take the element at index $\\textit{mid} = \\lfloor \\frac{l + r}{2} \\rfloor$ of the array as the root node of the current binary search tree, where $\\lfloor x \\rfloor$ denotes the floor function of $x$.\n3. Recursively construct the left subtree of the current binary search tree, with the root node's value being the element at index $\\textit{mid} - 1$ of the array. The values of the nodes in the left subtree are within the index range $[l, \\textit{mid} - 1]$ of the array.\n4. Recursively construct the right subtree of the current binary search tree, with the root node's value being the element at index $\\textit{mid} + 1$ of the array. The values of the nodes in the right subtree are within the index range $[\\textit{mid} + 1, r]$ of the array.\n5. Return the root node of the current binary search tree.\n\nThe answer is the return value of the function $\\textit{dfs}(0, n - 1)$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(\\log n)" }, { "problem_id": 109, "explanations": { "1": "We first convert the linked list to an array $\\textit{nums}$, and then use depth-first search to construct the binary search tree.\n\nWe define a function $\\textit{dfs}(i, j)$, where $i$ and $j$ represent the current interval $[i, j]$. Each time, we choose the number at the middle position $\\textit{mid}$ of the interval as the root node, recursively construct the left subtree for the interval $[i, \\textit{mid} - 1]$, and the right subtree for the interval $[\\textit{mid} + 1, j]$. Finally, we return the node corresponding to $\\textit{mid}$ as the root node of the current subtree.\n\nIn the main function, we just need to call $\\textit{dfs}(0, n - 1)$ and return the result.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the linked list." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 110, "explanations": { "1": "We define a function $height(root)$ to calculate the height of a binary tree, with the following logic:\n\n- If the binary tree $root$ is null, return $0$.\n- Otherwise, recursively calculate the heights of the left and right subtrees, denoted as $l$ and $r$ respectively. If either $l$ or $r$ is $-1$, or the absolute difference between $l$ and $r$ is greater than $1$, then return $-1$. Otherwise, return $max(l, r) + 1$.\n\nTherefore, if the function $height(root)$ returns $-1$, it means the binary tree $root$ is not balanced. Otherwise, it is balanced.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 111, "explanations": { "1": "The termination condition for recursion is when the current node is null, at which point return $0$. If one of the left or right subtrees of the current node is null, return the minimum depth of the non-null subtree plus $1$. If neither the left nor right subtree of the current node is null, return the smaller value of the minimum depths of the left and right subtrees plus $1$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree.", "2": "Use a queue to implement breadth-first search, initially adding the root node to the queue. Each time, take a node from the queue. If this node is a leaf node, directly return the current depth. If this node is not a leaf node, add all non-null child nodes of this node to the queue. Continue to search the next layer of nodes until a leaf node is found.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 112, "explanations": { "1": "Starting from the root node, recursively traverse the tree and update the value of the node to the path sum from the root node to that node. When you traverse to a leaf node, determine whether this path sum is equal to the target value. If it is equal, return `true`, otherwise return `false`.\n\nThe time complexity is $O(n)$, where $n$ is the number of nodes in the binary tree. Each node is visited once." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": null }, { "problem_id": 113, "explanations": { "1": "We start from the root node, recursively traverse all paths from the root node to the leaf nodes, and record the path sum. When we traverse to a leaf node, if the current path sum equals `targetSum`, then we add this path to the answer.\n\nThe time complexity is $O(n^2)$, where $n$ is the number of nodes in the binary tree. The space complexity is $O(n)$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 114, "explanations": { "1": "The visit order of preorder traversal is \"root, left subtree, right subtree\". After the last node of the left subtree is visited, the right subtree node of the root node will be visited next.\n\nTherefore, for the current node, if its left child node is not null, we find the rightmost node of the left subtree as the predecessor node, and then assign the right child node of the current node to the right child node of the predecessor node. Then assign the left child node of the current node to the right child node of the current node, and set the left child node of the current node to null. Then take the right child node of the current node as the next node and continue processing until all nodes are processed.\n\nThe time complexity is $O(n)$, where $n$ is the number of nodes in the tree. The space complexity is $O(1)$.", "2": "" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 115, "explanations": { "1": "We define $f[i][j]$ as the number of schemes where the first $i$ characters of string $s$ form the first $j$ characters of string $t$. Initially, $f[i][0]=1$ for all $i \\in [0,m]$.\n\nWhen $i > 0$, we consider the calculation of $f[i][j]$:\n\n- When $s[i-1] \\ne t[j-1]$, we cannot select $s[i-1]$, so $f[i][j]=f[i-1][j]$;\n- Otherwise, we can select $s[i-1]$, so $f[i][j]=f[i-1][j-1]$.\n\nTherefore, we have the following state transition equation:\n\n$$\nf[i][j]=\\left\\{\n\\begin{aligned}\n&f[i-1][j], &s[i-1] \\ne t[j-1] \\\\\n&f[i-1][j-1]+f[i-1][j], &s[i-1]=t[j-1]\n\\end{aligned}\n\\right.\n$$\n\nThe final answer is $f[m][n]$, where $m$ and $n$ are the lengths of strings $s$ and $t$ respectively.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$.\n\nWe notice that the calculation of $f[i][j]$ is only related to $f[i-1][..]$. Therefore, we can optimize the first dimension, reducing the space complexity to $O(n)$.", "2": "" }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 116, "explanations": { "1": "Use a queue for level order traversal, and each time you traverse a level, connect the nodes of the current level in order.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree.", "2": "Use recursion for preorder traversal, and each time you traverse to a node, connect its left and right child nodes in order.\n\nSpecifically, we design a function $dfs(left, right)$, which points the $next$ pointer of the $left$ node to the $right$ node. In the function, we first check whether $left$ and $right$ are null. If both are not null, point $left.next$ to $right$, and then recursively call $dfs(left.left, left.right)$, $dfs(left.right, right.left)$, $dfs(right.left, right.right)$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 117, "explanations": { "1": "We use a queue $q$ for level order traversal. Each time we traverse a level, we connect the nodes of the current level in order.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree.", "2": "The space complexity of Solution 1 is relatively high because it requires a queue to store the nodes of each level. We can implement it with constant space.\n\nWe define two pointers $prev$ and $next$, which point to the previous node and the first node of the next level, respectively. When traversing the nodes of the current level, we string the nodes of the next level together and find the first node of the next level. After the current level is traversed, we assign the first node $next$ of the next level to $node$ and continue to traverse.\n\nThe time complexity is $O(n)$, where $n$ is the number of nodes in the binary tree. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 118, "explanations": { "1": "We first create an answer array $f$, then set the first row of $f$ to $[1]$. Next, starting from the second row, the first and last elements of each row are $1$, and for other elements $f[i][j] = f[i - 1][j - 1] + f[i - 1][j]$.\n\nThe time complexity is $O(n^2)$, where $n$ is the given number of rows. Ignoring the space consumption of the answer, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(1)" }, { "problem_id": 119, "explanations": { "1": "We create an array $f$ of length $rowIndex + 1$, initially all elements are $1$.\n\nNext, starting from the second row, we calculate the value of the $j$th element in the current row from back to front, $f[j] = f[j] + f[j - 1]$, where $j \\in [1, i - 1]$.\n\nFinally, return $f$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ is the given number of rows." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 120, "explanations": { "1": "We define $f[i][j]$ as the minimum path sum from the bottom of the triangle to position $(i, j)$. Here, position $(i, j)$ refers to the position in row $i$ and column $j$ of the triangle (both indexed from $0$). We have the following state transition equation:\n\n$$\nf[i][j] = \\min(f[i + 1][j], f[i + 1][j + 1]) + \\text{triangle}[i][j]\n$$\n\nThe answer is $f[0][0]$.", "2": "We notice that the state $f[i][j]$ only depends on states $f[i + 1][j]$ and $f[i + 1][j + 1]$. Therefore, we can use a one-dimensional array instead of a two-dimensional array, reducing the space complexity from $O(n^2)$ to $O(n)$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$, where $n$ is the number of rows in the triangle." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 121, "explanations": { "1": "We can enumerate each element of the array $nums$ as the selling price. Then we need to find a minimum value in front of it as the purchase price to maximize the profit.\n\nTherefore, we use a variable $mi$ to maintain the prefix minimum value of the array $nums$. Then we traverse the array $nums$ and for each element $v$, calculate the difference between it and the minimum value $mi$ in front of it, and update the answer to the maximum of the difference. Then update $mi = min(mi, v)$. Continue to traverse the array $nums$ until the traversal ends.\n\nFinally, return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 122, "explanations": { "1": "Starting from the second day, if the stock price is higher than the previous day, buy on the previous day and sell on the current day to make a profit. If the stock price is lower than the previous day, do not buy or sell. In other words, buy and sell on all rising trading days, and do not trade on all falling trading days. The final profit will be the maximum.\n\nThe time complexity is $O(n)$, where $n$ is the length of the `prices` array. The space complexity is $O(1)$.", "2": "We define $f[i][j]$ as the maximum profit after trading on the $i$th day, where $j$ indicates whether we currently hold the stock. When holding the stock, $j=0$, and when not holding the stock, $j=1$. The initial state is $f[0][0]=-prices[0]$, and all other states are $0$.\n\nIf we currently hold the stock, it may be that we held the stock the day before and do nothing today, i.e., $f[i][0]=f[i-1][0]$. Or it may be that we did not hold the stock the day before and bought the stock today, i.e., $f[i][0]=f[i-1][1]-prices[i]$.\n\nIf we currently do not hold the stock, it may be that we did not hold the stock the day before and do nothing today, i.e., $f[i][1]=f[i-1][1]$. Or it may be that we held the stock the day before and sold the stock today, i.e., $f[i][1]=f[i-1][0]+prices[i]$.\n\nTherefore, we can write the state transition equation as:\n\n$$\n\\begin{cases}\nf[i][0]=\\max(f[i-1][0],f[i-1][1]-prices[i])\\\\\nf[i][1]=\\max(f[i-1][1],f[i-1][0]+prices[i])\n\\end{cases}\n$$\n\nThe final answer is $f[n-1][1]$, where $n$ is the length of the `prices` array.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the `prices` array.", "3": "We can find that in Solution 2, the state of the $i$th day is only related to the state of the $i-1$th day. Therefore, we can use only two variables to maintain the state of the $i-1$th day, thereby optimizing the space complexity to $O(1)$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the `prices` array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 123, "explanations": { "1": "We define the following variables:\n\n- `f1` represents the maximum profit after the first purchase of the stock;\n- `f2` represents the maximum profit after the first sale of the stock;\n- `f3` represents the maximum profit after the second purchase of the stock;\n- `f4` represents the maximum profit after the second sale of the stock.\n\nDuring the traversal, we directly calculate `f1`, `f2`, `f3`, `f4`. We consider that buying and selling on the same day will result in a profit of $0$, which will not affect the answer.\n\nFinally, return `f4`.\n\nThe time complexity is $O(n)$, where $n$ is the length of the `prices` array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 124, "explanations": { "1": "When thinking about the classic routine of recursion problems in binary trees, we consider:\n\n1. Termination condition (when to terminate recursion)\n2. Recursively process the left and right subtrees\n3. Merge the calculation results of the left and right subtrees\n\nFor this problem, we design a function $dfs(root)$, which returns the maximum path sum of the binary tree with $root$ as the root node.\n\nThe execution logic of the function $dfs(root)$ is as follows:\n\nIf $root$ does not exist, then $dfs(root)$ returns $0$;\n\nOtherwise, we recursively calculate the maximum path sum of the left and right subtrees of $root$, denoted as $left$ and $right$. If $left$ is less than $0$, then we set it to $0$, similarly, if $right$ is less than $0$, then we set it to $0$.\n\nThen, we update the answer with $root.val + left + right$. Finally, the function returns $root.val + \\max(left, right)$.\n\nIn the main function, we call $dfs(root)$ to get the maximum path sum of each node, and the maximum value among them is the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 125, "explanations": { "1": "We use two pointers $i$ and $j$ to point to the two ends of the string $s$, and then loop through the following process until $i \\geq j$:\n\n1. If $s[i]$ is not a letter or a number, move the pointer $i$ one step to the right and continue to the next loop.\n2. If $s[j]$ is not a letter or a number, move the pointer $j$ one step to the left and continue to the next loop.\n3. If the lowercase form of $s[i]$ and $s[j]$ are not equal, return `false`.\n4. Otherwise, move the pointer $i$ one step to the right and the pointer $j$ one step to the left, and continue to the next loop.\n\nAt the end of the loop, return `true`.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 126, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 127, "explanations": { "1": "BFS minimum step model. This problem can be solved with naive BFS, or it can be optimized with bidirectional BFS to reduce the search space and improve efficiency.\n\nBidirectional BFS is a common optimization method for BFS, with the main implementation ideas as follows:\n\n1. Create two queues, q1 and q2, for \"start -> end\" and \"end -> start\" search directions, respectively.\n2. Create two hash maps, m1 and m2, to record the visited nodes and their corresponding expansion times (steps).\n3. During each search, prioritize the queue with fewer elements for search expansion. If a node visited from the other direction is found during the expansion, it means the shortest path has been found.\n4. If one of the queues is empty, it means that the search in the current direction cannot continue, indicating that the start and end points are not connected, and there is no need to continue the search.\n\n```python\nwhile q1 and q2:\n if len(q1) <= len(q2):\n # Prioritize the queue with fewer elements for expansion\n extend(m1, m2, q1)\n else:\n extend(m2, m1, q2)\n\n\ndef extend(m1, m2, q):\n # New round of expansion\n for _ in range(len(q)):\n p = q.popleft()\n step = m1[p]\n for t in next(p):\n if t in m1:\n # Already visited before\n continue\n if t in m2:\n # The other direction has been searched, indicating that a shortest path has been found\n return step + 1 + m2[t]\n q.append(t)\n m1[t] = step + 1\n```", "2": "" }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 128, "explanations": { "1": "We can use a hash table $\\textit{s}$ to store all the elements in the array, a variable $\\textit{ans}$ to record the length of the longest consecutive sequence, and a hash table $\\textit{d}$ to record the length of the consecutive sequence each element $x$ belongs to.\n\nNext, we iterate through each element $x$ in the array, using a temporary variable $y$ to record the maximum value of the current consecutive sequence, initially $y = x$. Then, we continuously try to match $y+1, y+2, y+3, \\dots$ until we can no longer match. During this process, we remove the matched elements from the hash table $\\textit{s}$. The length of the consecutive sequence that the current element $x$ belongs to is $d[x] = d[y] + y - x$, and then we update the answer $\\textit{ans} = \\max(\\textit{ans}, d[x])$.\n\nAfter the iteration, we return the answer $\\textit{ans}$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$.", "2": "Similar to Solution 1, we use a hash table $\\textit{s}$ to store all the elements in the array and a variable $\\textit{ans}$ to record the length of the longest consecutive sequence. However, we no longer use a hash table $\\textit{d}$ to record the length of the consecutive sequence each element $x$ belongs to. During the iteration, we skip elements where $x-1$ is also in the hash table $\\textit{s}$. If $x-1$ is in the hash table $\\textit{s}$, then $x$ is definitely not the start of a consecutive sequence, so we can directly skip $x$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 129, "explanations": { "1": "We can design a function $dfs(root, s)$, which represents the sum of all path numbers from the current node $root$ to the leaf nodes, given that the current path number is $s$. The answer is $dfs(root, 0)$.\n\nThe calculation of the function $dfs(root, s)$ is as follows:\n\n- If the current node $root$ is null, return $0$.\n- Otherwise, add the value of the current node to $s$, i.e., $s = s \\times 10 + root.val$.\n- If the current node is a leaf node, return $s$.\n- Otherwise, return $dfs(root.left, s) + dfs(root.right, s)$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(\\log n)" }, { "problem_id": 130, "explanations": { "1": "We can start from the boundary of the matrix, taking each 'O' on the matrix boundary as a starting point, and perform depth-first search. All 'O's found in the search are replaced with '.'.\n\nThen we traverse the matrix again, for each position:\n\n- If it is '.', replace it with 'O';\n- Otherwise, if it is 'O', replace it with 'X'.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the number of rows and columns in the matrix, respectively.", "2": "We can also use a union-find set, connecting each 'O' on the matrix boundary with a super node $m \\times n$, and connecting each 'O' in the matrix with the 'O's above, below, left, and right of it.\n\nThen we traverse this matrix, for each position, if it is 'O' and it is not connected to the super node, then we replace it with 'X'.\n\nThe time complexity is $O(m \\times n \\times \\alpha(m \\times n))$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the number of rows and columns in the matrix, respectively, and $\\alpha$ is the inverse Ackermann function." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 131, "explanations": { "1": "We can use dynamic programming to preprocess whether any substring in the string is a palindrome, i.e., $f[i][j]$ indicates whether the substring $s[i..j]$ is a palindrome.\n\nNext, we design a function $dfs(i)$, which represents starting from the $i$-th character of the string and partitioning it into several palindromic substrings, with the current partition scheme being $t$.\n\nIf $i = |s|$, it means the partitioning is complete, and we add $t$ to the answer array and then return.\n\nOtherwise, we can start from $i$ and enumerate the end position $j$ from small to large. If $s[i..j]$ is a palindrome, we add $s[i..j]$ to $t$, then continue to recursively call $dfs(j+1)$. When backtracking, we need to pop $s[i..j]$.\n\nThe time complexity is $O(n \\times 2^n)$, and the space complexity is $O(n^2)$. Here, $n$ is the length of the string." }, "is_english": true, "time_complexity": "O(n \\times 2^n)", "space_complexity": "O(n^2)" }, { "problem_id": 132, "explanations": { "1": "First, we preprocess the string $s$ to determine whether each substring $s[i..j]$ is a palindrome, and record this in a 2D array $g[i][j]$, where $g[i][j]$ indicates whether the substring $s[i..j]$ is a palindrome.\n\nNext, we define $f[i]$ to represent the minimum number of cuts needed for the substring $s[0..i-1]$. Initially, $f[i] = i$.\n\nNext, we consider how to transition the state for $f[i]$. We can enumerate the previous cut point $j$. If the substring $s[j..i]$ is a palindrome, then $f[i]$ can be transitioned from $f[j]$. If $j = 0$, it means that $s[0..i]$ itself is a palindrome, and no cuts are needed, i.e., $f[i] = 0$. Therefore, the state transition equation is as follows:\n\n$$\nf[i] = \\min_{0 \\leq j \\leq i} \\begin{cases} f[j-1] + 1, & \\textit{if}\\ g[j][i] = \\textit{True} \\\\ 0, & \\textit{if}\\ g[0][i] = \\textit{True} \\end{cases}\n$$\n\nThe answer is $f[n]$, where $n$ is the length of the string $s$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 133, "explanations": { "1": "We use a hash table $\\textit{g}$ to record the correspondence between each node in the original graph and its copy, and then perform depth-first search.\n\nWe define the function $\\text{dfs}(node)$, which returns the copy of the $\\textit{node}$. The process of $\\text{dfs}(node)$ is as follows:\n\n- If $\\textit{node}$ is $\\text{null}$, then the return value of $\\text{dfs}(node)$ is $\\text{null}$.\n- If $\\textit{node}$ is in $\\textit{g}$, then the return value of $\\text{dfs}(node)$ is $\\textit{g}[node]$.\n- Otherwise, we create a new node $\\textit{cloned}$ and set the value of $\\textit{g}[node]$ to $\\textit{cloned}$. Then, we traverse all the neighbor nodes $\\textit{nxt}$ of $\\textit{node}$ and add $\\text{dfs}(nxt)$ to the neighbor list of $\\textit{cloned}$.\n- Finally, return $\\textit{cloned}$.\n\nIn the main function, we return $\\text{dfs}(node)$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 134, "explanations": { "1": "我们用 $i$, $j$ 分别标记起点和终点,用 $s$ 表示当前剩余汽油,而 $cnt$ 表示当前行驶过的加油站数量。初始时,我们将起点设在最后一个位置,即 $i=n-1$。\n\n开始行驶,移动 $j$。若发现当前剩余汽油小于 $0$,说明当前 $i$ 作为起点不符合要求,我们将起点 $i$ 循环左移,并且更新剩余汽油,直至剩余汽油是非负数。\n\n当行驶过的加油站数量达到 $n$ 时,结束行驶过程。若此时剩余汽油 $s$ 仍然小于 $0$,说明不存在这样的起点,返回 $-1$。否则,返回起点 $i$。\n\n时间复杂度 $O(n)$,其中 $n$ 表示加油站的数量。空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 135, "explanations": { "1": "We initialize two arrays $left$ and $right$, where $left[i]$ represents the minimum number of candies the current child should get when the current child's score is higher than the left child's score, and $right[i]$ represents the minimum number of candies the current child should get when the current child's score is higher than the right child's score. Initially, $left[i]=1$, $right[i]=1$.\n\nWe traverse the array from left to right once, and if the current child's score is higher than the left child's score, then $left[i]=left[i-1]+1$; similarly, we traverse the array from right to left once, and if the current child's score is higher than the right child's score, then $right[i]=right[i+1]+1$.\n\nFinally, we traverse the array of scores once, and the minimum number of candies each child should get is the maximum of $left[i]$ and $right[i]$, and we add them up to get the answer.\n\nTime complexity $O(n)$, space complexity $O(n)$. Where $n$ is the length of the array of scores." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 136, "explanations": { "1": "The XOR operation has the following properties:\n\n- Any number XOR 0 is still the original number, i.e., $x \\oplus 0 = x$;\n- Any number XOR itself is 0, i.e., $x \\oplus x = 0$;\n\nPerforming XOR operation on all elements in the array will result in the number that only appears once.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$.", "2": "" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 137, "explanations": { "1": "We can enumerate each binary bit $i$, and for each binary bit, we calculate the sum of all numbers on that bit. If the sum of the numbers on that bit can be divided by 3, then the number that only appears once on that bit is 0, otherwise it is 1.\n\nThe time complexity is $O(n \\times \\log M)$, where $n$ and $M$ are the length of the array and the range of elements in the array, respectively. The space complexity is $O(1)$.", "2": "We can use a more efficient method that uses digital circuits to simulate the above bitwise operation.\n\nEach binary bit of an integer can only represent 2 states, 0 or 1. However, we need to represent the sum of the $i$-th bit of all integers traversed so far modulo 3. Therefore, we can use two integers $a$ and $b$ to represent it. There are three possible cases:\n\n1. The $i$-th bit of integer $a$ is 0 and the $i$-th bit of integer $b$ is 0, which means the modulo 3 result is 0;\n2. The $i$-th bit of integer $a$ is 0 and the $i$-th bit of integer $b$ is 1, which means the modulo 3 result is 1;\n3. The $i$-th bit of integer $a$ is 1 and the $i$-th bit of integer $b$ is 0, which means the modulo 3 result is 2.\n\nWe use integer $c$ to represent the number to be read in, and the truth table is as follows:\n\n| $a_i$ | $b_i$ | $c_i$ | New $a_i$ | New $b_i$ |\n| ----- | ----- | ----- | --------- | --------- |\n| 0 | 0 | 0 | 0 | 0 |\n| 0 | 0 | 1 | 0 | 1 |\n| 0 | 1 | 0 | 0 | 1 |\n| 0 | 1 | 1 | 1 | 0 |\n| 1 | 0 | 0 | 1 | 0 |\n| 1 | 0 | 1 | 0 | 0 |\n\nBased on the truth table, we can write the logical expression:\n\n$$\na_i = a_i' b_i c_i + a_i b_i' c_i'\n$$\n\nand:\n\n$$\nb_i = a_i' b_i' c_i + a_i' b_i c_i' = a_i' (b_i \\oplus c_i)\n$$\n\nThe final result is $b$, because when the binary bit of $b$ is 1, it means that the number appears only once.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$.", "3": "", "4": "" }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(1)" }, { "problem_id": 138, "explanations": { "1": "We can define a dummy head node $\\textit{dummy}$ and use a pointer $\\textit{tail}$ to point to the dummy head node. Then, we traverse the linked list, copying each node and storing the mapping between each node and its copy in a hash table $\\textit{d}$, while also connecting the $\\textit{next}$ pointers of the copied nodes.\n\nNext, we traverse the linked list again and use the mappings stored in the hash table to connect the $\\textit{random}$ pointers of the copied nodes.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the linked list.", "2": "In Solution 1, we used an additional hash table to store the mapping between the original nodes and the copied nodes. We can also achieve this without using extra space, as follows:\n\n1. Traverse the original linked list, and for each node, create a new node and insert it between the original node and the original node's next node.\n2. Traverse the linked list again, and set the $\\textit{random}$ pointer of the new node based on the $\\textit{random}$ pointer of the original node.\n3. Finally, split the linked list into the original linked list and the copied linked list.\n\nThe time complexity is $O(n)$, where $n$ is the length of the linked list. Ignoring the space occupied by the answer linked list, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 139, "explanations": { "1": "我们定义 $f[i]$ 表示字符串 $s$ 的前 $i$ 个字符能否拆分成 $wordDict$ 中的单词,初始时 $f[0]=true$,其余为 $false$。答案为 $f[n]$。\n\n考虑 $f[i]$,如果存在 $j \\in [0, i)$ 使得 $f[j] \\land s[j:i] \\in wordDict$,则 $f[i]=true$。为了优化效率,我们可以使用哈希表存储 $wordDict$ 中的单词,这样可以快速判断 $s[j:i]$ 是否在 $wordDict$ 中。\n\n时间复杂度 $O(n^3)$,空间复杂度 $O(n)$。其中 $n$ 为字符串 $s$ 的长度。", "2": "我们先将 $wordDict$ 中的单词存入前缀树中,然后使用动态规划求解。\n\n我们定义 $f[i]$ 表示从字符串 $s$ 的第 $i$ 个字符开始往后拆分,能否拆分成 $wordDict$ 中的单词,初始时 $f[n]=true$,其余为 $false$。答案为 $f[0]$。\n\n接下来,我们从大到小枚举 $i$,对于每个 $i$,我们从 $i$ 开始往后拆分,如果 $s[i:j]$ 在前缀树中,且 $f[j+1]=true$,则 $f[i]=true$。\n\n时间复杂度 $O(n^2)$,空间复杂度 $O(n)$。其中 $n$ 为字符串 $s$ 的长度。" }, "is_english": false, "time_complexity": "O(n^3)", "space_complexity": "O(n)" }, { "problem_id": 140, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 141, "explanations": { "1": "We can traverse the linked list and use a hash table $s$ to record each node. When a node appears for the second time, it indicates that there is a cycle, and we directly return `true`. Otherwise, when the linked list traversal ends, we return `false`.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of nodes in the linked list.", "2": "We define two pointers, $fast$ and $slow$, both initially pointing to $head$.\n\nThe fast pointer moves two steps at a time, and the slow pointer moves one step at a time, in a continuous loop. When the fast and slow pointers meet, it indicates that there is a cycle in the linked list. If the loop ends without the pointers meeting, it indicates that there is no cycle in the linked list.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$, where $n$ is the number of nodes in the linked list." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 142, "explanations": { "1": "We first use the fast and slow pointers to judge whether the linked list has a ring. If there is a ring, the fast and slow pointers will definitely meet, and the meeting node must be in the ring.\n\nIf there is no ring, the fast pointer will reach the tail of the linked list first, and return `null` directly.\n\nIf there is a ring, we then define an answer pointer $ans$ to point to the head of the linked list, and then let $ans$ and the slow pointer move forward together, moving one step at a time, until $ans$ and the slow pointer meet, and the meeting node is the ring entrance node.\n\nWhy can this find the entrance node of the ring?\n\nLet's assume that the distance from the head node of the linked list to the entrance of the ring is $x$, the distance from the entrance of the ring to the meeting node is $y$, and the distance from the meeting node to the entrance of the ring is $z$. Then the distance traveled by the slow pointer is $x + y$, and the distance traveled by the fast pointer is $x + y + k \\times (y + z)$, where $k$ is the number of times the fast pointer goes around the ring.\n\n

\n\nBecause the speed of the fast pointer is twice that of the slow pointer, it is $2 \\times (x + y) = x + y + k \\times (y + z)$, which can be deduced that $x + y = k \\times (y + z)$, that is $x = (k - 1) \\times (y + z) + z$.\n\nThat is to say, if we define an answer pointer $ans$ to point to the head of the linked list, and the $ans$ and the slow pointer move forward together, they will definitely meet at the ring entrance.\n\nThe time complexity is $O(n)$, where $n$ is the number of nodes in the linked list. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 143, "explanations": { "1": "We first use fast and slow pointers to find the midpoint of the linked list, then reverse the second half of the list, and finally merge the two halves.\n\nThe time complexity is $O(n)$, where $n$ is the length of the linked list. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 144, "explanations": { "1": "We first visit the root node, then recursively traverse the left and right subtrees.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree. The space complexity mainly depends on the stack space used for recursive calls.", "2": "The idea of using a stack to implement non-recursive traversal is as follows:\n\n1. Define a stack $stk$, and first push the root node into the stack.\n2. If the stack is not empty, pop a node from the stack each time.\n3. Process the node.\n4. First push the right child of the node into the stack, then push the left child of the node into the stack (if there are child nodes).\n5. Repeat steps 2-4.\n6. Return the result.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree. The space complexity mainly depends on the stack space.", "3": "Morris traversal does not require a stack, and its space complexity is $O(1)$. The core idea is:\n\nTraverse the binary tree nodes,\n\n1. If the left subtree of the current node `root` is empty, add the current node value to the result list $ans$, and update the current node to `root.right`.\n1. If the left subtree of the current node `root` is not empty, find the rightmost node `pre` of the left subtree (which is the predecessor of the `root` node in inorder traversal):\n - If the right subtree of the predecessor node `pre` is empty, add the current node value to the result list $ans$, then point the right subtree of the predecessor node to the current node `root`, and update the current node to `root.left`.\n - If the right subtree of the predecessor node `pre` is not empty, point the right subtree of the predecessor node to null (i.e., disconnect `pre` and `root`), and update the current node to `root.right`.\n1. Repeat the above steps until the binary tree node is null, and the traversal ends.\n\nThe time complexity is $O(n)$, where $n$ is the number of nodes in the binary tree. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 145, "explanations": { "1": "We first recursively traverse the left and right subtrees, then visit the root node.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree. The space complexity mainly depends on the stack space used for recursive calls.", "2": "The order of preorder traversal is: root, left, right. If we change the order of the left and right children, the order becomes: root, right, left. Finally, reversing the result gives us the postorder traversal result.\n\nTherefore, the idea of using a stack to implement non-recursive traversal is as follows:\n\n1. Define a stack $stk$, and first push the root node into the stack.\n2. If the stack is not empty, pop a node from the stack each time.\n3. Process the node.\n4. First push the left child of the node into the stack, then push the right child of the node into the stack (if there are child nodes).\n5. Repeat steps 2-4.\n6. Reverse the result to get the postorder traversal result.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree. The space complexity mainly depends on the stack space.", "3": "Morris traversal does not require a stack, and its space complexity is $O(1)$. The core idea is:\n\nTraverse the binary tree nodes,\n\n1. If the right subtree of the current node `root` is empty, add the current node value to the result list $ans$, and update the current node to `root.left`.\n1. If the right subtree of the current node `root` is not empty, find the leftmost node `next` of the right subtree (which is the successor of the `root` node in inorder traversal):\n - If the left subtree of the successor node `next` is empty, add the current node value to the result list $ans$, then point the left subtree of the successor node to the current node `root`, and update the current node to `root.right`.\n - If the left subtree of the successor node `next` is not empty, point the left subtree of the successor node to null (i.e., disconnect `next` and `root`), and update the current node to `root.left`.\n1. Repeat the above steps until the binary tree node is null, and the traversal ends.\n1. Finally, return the reverse of the result list.\n\n> The idea of Morris postorder traversal is consistent with Morris preorder traversal, just change the \"root-left-right\" of preorder to \"root-right-left\", and finally reverse the result to become \"left-right-root\".\n\nThe time complexity is $O(n)$, where $n$ is the number of nodes in the binary tree. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 146, "explanations": { "1": "We can implement an LRU (Least Recently Used) cache using a \"hash table\" and a \"doubly linked list\".\n\n- Hash Table: Used to store the key and its corresponding node location.\n- Doubly Linked List: Used to store node data, sorted by access time.\n\nWhen accessing a node, if the node exists, we delete it from its original position and reinsert it at the head of the list. This ensures that the node stored at the tail of the list is the least recently used node. When the number of nodes exceeds the maximum cache space, we eliminate the node at the tail of the list.\n\nWhen inserting a node, if the node exists, we delete it from its original position and reinsert it at the head of the list. If it does not exist, we first check if the cache is full. If it is full, we delete the node at the tail of the list and insert the new node at the head of the list.\n\nThe time complexity is $O(1)$, and the space complexity is $O(\\textit{capacity})$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(\\textit{capacity})" }, { "problem_id": 147, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 148, "explanations": { "1": "We can use the merge sort approach to solve this problem.\n\nFirst, we use the fast and slow pointers to find the middle of the linked list and break the list from the middle to form two separate sublists $\\textit{l1}$ and $\\textit{l2}$.\n\nThen, we recursively sort $\\textit{l1}$ and $\\textit{l2}$, and finally merge $\\textit{l1}$ and $\\textit{l2}$ into a sorted linked list.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the linked list." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 149, "explanations": { "1": "我们可以枚举任意两个点 $(x_1, y_1), (x_2, y_2)$,把这两个点连成一条直线,那么此时这条直线上的点的个数就是 2,接下来我们再枚举其他点 $(x_3, y_3)$,判断它们是否在同一条直线上,如果在,那么直线上的点的个数就加 1,如果不在,那么直线上的点的个数不变。找出所有直线上的点的个数的最大值,即为答案。\n\n时间复杂度 $O(n^3)$,空间复杂度 $O(1)$。其中 $n$ 是数组 `points` 的长度。", "2": "我们可以枚举一个点 $(x_1, y_1)$,把其他所有点 $(x_2, y_2)$ 与 $(x_1, y_1)$ 连成的直线的斜率存入哈希表中,斜率相同的点在同一条直线上,哈希表的键为斜率,值为直线上的点的个数。找出哈希表中的最大值,即为答案。为了避免精度问题,我们可以将斜率 $\\frac{y_2 - y_1}{x_2 - x_1}$ 进行约分,约分的方法是求最大公约数,然后分子分母同时除以最大公约数,将求得的分子分母作为哈希表的键。\n\n时间复杂度 $O(n^2 \\times \\log m)$,空间复杂度 $O(n)$。其中 $n$ 和 $m$ 分别是数组 `points` 的长度和数组 `points` 所有横纵坐标差的最大值。\n\n相似题目:\n\n- [面试题 16.14. 最佳直线](https://github.com/doocs/leetcode/blob/main/lcci/16.14.Best%20Line/README.md)" }, "is_english": false, "time_complexity": "O(n^3)", "space_complexity": "O(1)" }, { "problem_id": 150, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 151, "explanations": { "1": "We can use two pointers $i$ and $j$ to find each word, add it to the result list, then reverse the result list, and finally concatenate it into a string.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string.", "2": "We can use the built-in string split function to split the string into a list of words by spaces, then reverse the list, and finally concatenate it into a string.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 152, "explanations": { "1": "我们定义两个变量 $f$ 和 $g$,其中 $f$ 表示以 $nums[i]$ 结尾的乘积最大子数组的乘积,而 $g$ 表示以 $nums[i]$ 结尾的乘积最小子数组的乘积。初始时 $f$ 和 $g$ 都等于 $nums[0]$。答案为所有 $f$ 中的最大值。\n\n从 $i=1$ 开始,我们可以考虑将第 $i$ 个数 $nums[i]$ 添加到前面的乘积最大或者乘积最小的子数组乘积的后面,或者单独作为一个子数组乘积(即此时子数组长度只有 $1$)。我们将此前的乘积最大值记为 $ff$,乘积最小值记为 $gg$,那么 $f = \\max(f, ff \\times nums[i], gg \\times nums[i])$,而 $g = \\min(g, ff \\times nums[i], gg \\times nums[i])$。接下来,我们更新答案 $ans = \\max(ans, f)$,然后继续计算下一个位置。\n\n最后的答案即为 $ans$。\n\n时间复杂度 $O(n)$,其中 $n$ 是数组 $nums$ 的长度。我们只需要遍历数组一次即可求得答案。空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 153, "explanations": { "1": "初始,判断数组首尾元素的大小关系,若 `nums[0] <= nums[n - 1]` 条件成立,则说明当前数组已经是递增数组,最小值一定是数组第一个元素,提前返回 `nums[0]`。\n\n否则,进行二分判断。若 `nums[0] <= nums[mid]`,说明 `[left, mid]` 范围内的元素构成递增数组,最小值一定在 `mid` 的右侧,否则说明 `[mid + 1, right]` 范围内的元素构成递增数组,最小值一定在 `mid` 的左侧。\n\n---\n\n除了 `nums[0]`,也可以以 `nums[right]` 作为参照物,若 `nums[mid] < nums[right]` 成立,则最小值存在于 `[left, mid]` 范围当中,否则存在于 `[mid + 1, right]`。\n\n时间复杂度:$O(logN)$" }, "is_english": false, "time_complexity": "O(logN)", "space_complexity": null }, { "problem_id": 154, "explanations": { "1": "若 `nums[mid] > nums[right]`,说明最小值在 mid 的右边;若 `nums[mid] < nums[right]`,说明最小值在 mid 的左边(包括 mid);若相等,无法判断,直接将 right 减 1。循环比较。\n\n最后返回 `nums[left]` 即可。\n\n时间复杂度 O(logn)。" }, "is_english": false, "time_complexity": "O(logn)", "space_complexity": null }, { "problem_id": 155, "explanations": { "1": "我们用两个栈来实现,其中 `stk1` 用来存储数据,`stk2` 用来存储当前栈中的最小值。初始时,`stk2` 中存储一个极大值。\n\n- 当我们向栈中压入一个元素 $x$ 时,我们将 $x$ 压入 `stk1`,并将 `min(x, stk2[-1])` 压入 `stk2`。\n- 当我们从栈中弹出一个元素时,我们将 `stk1` 和 `stk2` 的栈顶元素都弹出。\n- 当我们要获取当前栈中的栈顶元素时,我们只需要返回 `stk1` 的栈顶元素即可。\n- 当我们要获取当前栈中的最小值时,我们只需要返回 `stk2` 的栈顶元素即可。\n\n每个操作的时间复杂度为 $O(1)$。整体的空间复杂度为 $O(n)$,其中 $n$ 为栈中元素的个数。" }, "is_english": false, "time_complexity": "O(1)", "space_complexity": "O(n)" }, { "problem_id": 156, "explanations": { "1": "若根节点为空,或者根节点左子树为空,直接返回根节点。\n\n递归处理左子树,返回的根节点 newRoot,也就是二叉树上下翻转后的根节点。\n\n然后处理根节点 root,根节点变成左子节点的右子节点,而根节点的右子节点变成左子节点的左子节点。\n\n接着将根节点 root 的左右子节点置为空,最后返回 newRoot 即可。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉树节点个数。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 157, "explanations": { "1": "直接模拟读取文件的过程,每次读取 4 个字符,然后将读取的字符存入缓存数组中,直到读取的字符数目达到 n 或者文件读取完毕。\n\n时间复杂度 $O(n)$。其中 $n$ 为要读取的字符数目。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": null }, { "problem_id": 158, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 159, "explanations": { "1": "我们维护一个哈希表 `cnt` 记录当前滑动窗口中各个字符出现的次数,如果哈希表中的键值对个数超过 $2$,则说明当前滑动窗口中包含了超过 $2$ 个不同的字符,此时需要移动左指针 `j`,直到哈希表中的键值对个数不超过 $2$ 为止,然后更新窗口的最大长度。\n\n时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为字符串 $s$ 的长度。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 160, "explanations": { "1": "We use two pointers $a$ and $b$ to point to the heads of the two linked lists $\\textit{headA}$ and $\\textit{headB}$, respectively.\n\nTraverse the linked lists simultaneously. When $a$ reaches the end of $\\textit{headA}$, redirect it to the head of $\\textit{headB}$. Similarly, when $b$ reaches the end of $\\textit{headB}$, redirect it to the head of $\\textit{headA}$.\n\nIf the two pointers meet, the node they point to is the first common node. If they do not meet, it means the two linked lists have no common nodes, and both pointers will point to `null`. Return either pointer.\n\nThe time complexity is $O(m + n)$, where $m$ and $n$ are the lengths of the linked lists $\\textit{headA}$ and $\\textit{headB}$, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m + n)", "space_complexity": "O(1)" }, { "problem_id": 161, "explanations": { "1": "Let $m$ represent the length of string $s$, and $n$ represent the length of string $t$. We can assume that $m$ is always greater than or equal to $n$.\n\nIf $m-n > 1$, return false directly;\n\nOtherwise, iterate through $s$ and $t$, if $s[i]$ is not equal to $t[i]$:\n\n- If $m \\neq n$, compare $s[i+1:]$ with $t[i:]$, return true if they are equal, otherwise return false;\n- If $m = n$, compare $s[i:]$ with $t[i:]$, return true if they are equal, otherwise return false.\n\nIf the iteration ends, it means that all the characters of $s$ and $t$ that have been iterated are equal, at this time it needs to satisfy $m=n+1$.\n\nThe time complexity is $O(m)$, where $m$ is the length of string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m)", "space_complexity": "O(1)" }, { "problem_id": 162, "explanations": { "1": "We define the left boundary of binary search as $left=0$ and the right boundary as $right=n-1$, where $n$ is the length of the array. In each step of binary search, we find the middle element $mid$ of the current interval, and compare the values of $mid$ and its right neighbor $mid+1$:\n\n- If the value of $mid$ is greater than the value of $mid+1$, there exists a peak element on the left side, and we update the right boundary $right$ to $mid$.\n- Otherwise, there exists a peak element on the right side, and we update the left boundary $left$ to $mid+1$.\n- Finally, when the left boundary $left$ is equal to the right boundary $right$, we have found the peak element of the array.\n\nThe time complexity is $O(\\log n)$, where $n$ is the length of the array $nums$. Each step of binary search can reduce the search interval by half, so the time complexity is $O(\\log n)$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 163, "explanations": { "1": "We can simulate the problem directly according to the requirements.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. Ignoring the space consumption of the answer, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 164, "explanations": { "1": "Let $m$ represent the length of string $s$, and $n$ represent the length of string $t$. We can assume that $m$ is always greater than or equal to $n$.\n\nIf $m-n > 1$, return false directly;\n\nOtherwise, iterate through $s$ and $t$, if $s[i]$ is not equal to $t[i]$:\n\n- If $m \\neq n$, compare $s[i+1:]$ with $t[i:]$, return true if they are equal, otherwise return false;\n- If $m = n$, compare $s[i:]$ with $t[i:]$, return true if they are equal, otherwise return false.\n\nIf the iteration ends, it means that all the characters of $s$ and $t$ that have been iterated are equal, at this time it needs to satisfy $m=n+1$.\n\nThe time complexity is $O(m)$, where $m$ is the length of string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m)", "space_complexity": "O(1)" }, { "problem_id": 165, "explanations": { "1": "Traverse both strings simultaneously using two pointers $i$ and $j$, which point to the current positions in each string, starting with $i = j = 0$.\n\nEach time, extract the corresponding revision numbers from both strings, denoted as $a$ and $b$. Compare $a$ and $b$: if $a \\lt b$, return $-1$; if $a \\gt b$, return $1$; if $a = b$, continue to compare the next pair of revision numbers.\n\nThe time complexity is $O(\\max(m, n))$, and the space complexity is $O(1)$, where $m$ and $n$ are the lengths of the two strings." }, "is_english": true, "time_complexity": "O(\\max(m, n))", "space_complexity": "O(1)" }, { "problem_id": 166, "explanations": { "1": "First, we check if the $numerator$ is $0$. If it is, we return `\"0\"` directly.\n\nNext, we check if the $numerator$ and $denominator$ have different signs. If they do, the result is negative, and we set the first character of the result to `\"-\"`.\n\nThen we take the absolute values of the $numerator$ and $denominator$, denoted as $a$ and $b$. Since the range of the numerator and denominator is $[-2^{31}, 2^{31} - 1]$, taking the absolute value directly may cause overflow, so we convert both $a$ and $b$ to long integers.\n\nNext, we calculate the integer part, which is the integer part of $a$ divided by $b$, convert it to a string, and add it to the result. Then we take the remainder of $a$ divided by $b$, denoted as $a$.\n\nIf $a$ is $0$, it means the result is an integer, and we return the result directly.\n\nNext, we calculate the decimal part. We use a hash table $d$ to record the length of the result corresponding to each remainder. We continuously multiply $a$ by $10$, then add the integer part of $a$ divided by $b$ to the result, then take the remainder of $a$ divided by $b$, denoted as $a$. If $a$ is $0$, it means the result is a finite decimal, and we return the result directly. If $a$ has appeared in the hash table, it means the result is a recurring decimal. We find the starting position of the cycle, insert the result into parentheses, and then return the result.\n\nThe time complexity is $O(l)$, and the space complexity is $O(l)$, where $l$ is the length of the result. In this problem, $l < 10^4$." }, "is_english": true, "time_complexity": "O(l)", "space_complexity": "O(l)" }, { "problem_id": 167, "explanations": { "1": "Note that the array is sorted in non-decreasing order, so for each `numbers[i]`, we can find the position of `target - numbers[i]` by binary search, and return $[i + 1, j + 1]$ if it exists.\n\nThe time complexity is $O(n \\times \\log n)$, where $n$ is the length of the array `numbers`. The space complexity is $O(1)$.", "2": "We define two pointers $i$ and $j$, which point to the first element and the last element of the array respectively. Each time we calculate $numbers[i] + numbers[j]$. If the sum is equal to the target value, return $[i + 1, j + 1]$ directly. If the sum is less than the target value, move $i$ to the right by one position, and if the sum is greater than the target value, move $j$ to the left by one position.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array `numbers`. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(1)" }, { "problem_id": 168, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 169, "explanations": { "1": "The basic steps of the Moore voting algorithm are as follows:\n\nInitialize the element $m$ and initialize the counter $cnt = 0$. Then, for each element $x$ in the input list:\n\n1. If $cnt = 0$, then $m = x$ and $cnt = 1$;\n1. Otherwise, if $m = x$, then $cnt = cnt + 1$, otherwise $cnt = cnt - 1$.\n\nIn general, the Moore voting algorithm requires **two passes** over the input list. In the first pass, we generate the candidate value $m$, and if there is a majority, the candidate value is the majority value. In the second pass, we simply compute the frequency of the candidate value to confirm whether it is the majority value. Since this problem has clearly stated that there is a majority value, we can directly return $m$ after the first pass, without the need for a second pass to confirm whether it is the majority value.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 170, "explanations": { "1": "We use a hash table `cnt` to store the count of each number.\n\nWhen the `add` method is called, we increment the count of the number `number`.\n\nWhen the `find` method is called, we iterate over the hash table `cnt`. For each key `x`, we check if `value - x` is also a key in the hash table `cnt`. If it is, we check if `x` is equal to `value - x`. If they are not equal, it means we have found a pair of numbers whose sum is `value`, and we return `true`. If they are equal, we check if the count of `x` is greater than `1`. If it is, it means we have found a pair of numbers whose sum is `value`, and we return `true`. If it is less than or equal to `1`, it means we have not found a pair of numbers whose sum is `value`, and we continue to iterate over the hash table `cnt`. If we have not found a pair after the iteration, we return `false`.\n\nTime complexity:\n\n- The time complexity of the `add` method is $O(1)$.\n- The time complexity of the `find` method is $O(n)$.\n\nSpace complexity is $O(n)$, where $n$ is the size of the hash table `cnt`." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(n)" }, { "problem_id": 171, "explanations": { "1": "The column name in Excel is a representation in base 26. For example, \"AB\" represents the column number $1 \\times 26 + 2 = 28$.\n\nTherefore, we can iterate through the string `columnTitle`, convert each character to its corresponding value, and then calculate the result.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string `columnTitle`. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 172, "explanations": { "1": "The problem is actually asking how many factors of $5$ are there in $[1,n]$.\n\nLet's take $130$ as an example for analysis:\n\n1. Divide by $5$ for the first time, get $26$, indicating that there are $26$ numbers containing the factor $5$;\n2. Divide by $5$ for the second time, get $5$, indicating that there are $5$ numbers containing the factor $5^2$;\n3. Divide by $5$ for the third time, get $1$, indicating that there is $1$ number containing the factor $5^3$;\n4. Sum up to get the count of all factors of $5$ in $[1,n]$.\n\nThe time complexity is $O(\\log n)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 173, "explanations": { "1": "初始化数据时,递归中序遍历,将二叉搜索树每个结点的值保存在列表 `vals` 中。用 `cur` 指针记录外部即将遍历的位置,初始化为 0。\n\n调用 `next()` 时,返回 `vals[cur]`,同时 `cur` 指针自增。调用 `hasNext()` 时,判断 `cur` 指针是否已经达到 `len(vals)` 个数,若是,说明已经遍历结束,返回 false,否则返回 true。", "2": "初始化时,从根节点一路遍历所有左子节点,压入栈 `stack` 中。\n\n调用 `next()`时,弹出栈顶元素 `cur`,获取 `cur` 的右子节点 `node`,若 `node` 不为空,一直循环压入左节点。最后返回 `cur.val` 即可。调用 `hasNext()` 时,判断 `stack` 是否为空,空则表示迭代结束。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 174, "explanations": { "1": "We define $dp[i][j]$ as the minimum initial value needed from $(i, j)$ to the end point. The value of $dp[i][j]$ can be obtained from $dp[i+1][j]$ and $dp[i][j+1]$, that is:\n\n$$\ndp[i][j] = \\max(\\min(dp[i+1][j], dp[i][j+1]) - dungeon[i][j], 1)\n$$\n\nInitially, $dp[m][n-1]$ and $dp[m-1][n]$ are both $1$, and the values at other positions are maximum.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Where $m$ and $n$ are the number of rows and columns of the dungeon, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 175, "explanations": { "1": "We can use a left join to join the `Person` table with the `Address` table on the condition `Person.personId = Address.personId`, which will give us the first name, last name, city, and state of each person. If the address of a `personId` is not in the `Address` table, it will be reported as `null`." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 176, "explanations": { "1": "我们可以按照薪水降序排列,然后使用 `LIMIT` 语句来获取第二高的薪水,如果不存在第二高的薪水,那么就返回 `null`。", "2": "我们也可以使用 `MAX()` 函数,从小于 `MAX()` 的薪水中挑选一个最大的薪水即可。", "3": "我们还可以先通过 `DENSE_RANK()` 函数计算出每个员工的薪水排名,然后再筛选出排名为 $2$ 的员工薪水即可。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 177, "explanations": { "1": "我们可以先对 `salary` 进行降序排序,然后使用 `LIMIT` 语句获取第 $n$ 高的工资。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 178, "explanations": { "1": "使用 `DENSE_RANK()` 函数,语法如下:\n\n```sql\nDENSE_RANK() OVER (\n PARTITION BY [{,...}]\n ORDER BY [ASC|DESC], [{,...}]\n)\n```\n\n在这个语法中:\n\n- 首先,`PARTITION BY` 子句将 `FROM` 子句生成的结果集划分为分区。`DENSE_RANK()`函数应用于每个分区。\n- 其次,`ORDER BY` 子句指定 `DENSE_RANK()` 函数操作的每个分区中的行顺序。\n\n与 `RANK()` 函数不同,`DENSE_RANK()` 函数始终返回连续的排名值。", "2": "MySQL 8 开始才提供了 `ROW_NUMBER()`,`RANK()`,`DENSE_RANK()` 等[窗口函数](https://dev.mysql.com/doc/refman/8.0/en/window-function-descriptions.html),在之前的版本,可以使用变量实现类似的功能。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 179, "explanations": { "1": "先转成字符串列表,再对字符串列表进行字典序降序排列。最后将列表所有字符串拼接即可。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 180, "explanations": { "1": "We can use two joins to solve this problem.\n\nFirst, we perform a self-join with the condition `l1.num = l2.num` and `l1.id = l2.id - 1`, so that we can find all numbers that appear at least twice in a row. Then, we perform another self-join with the condition `l2.num = l3.num` and `l2.id = l3.id - 1`, so that we can find all numbers that appear at least three times in a row. Finally, we only need to select the distinct `l2.num`.", "2": "We can use the window functions `LAG` and `LEAD` to obtain the `num` of the previous row and the next row of the current row, and record them in the fields $a$ and $b$, respectively. Finally, we only need to filter out the rows where $a = num$ and $b = num$, which are the numbers that appear at least three times in a row. Note that we need to use the `DISTINCT` keyword to remove duplicates from the results.\n\nWe can also group the numbers by using the `IF` function to determine whether the `num` of the current row is equal to the `num` of the previous row. If they are equal, we set it to $0$, otherwise we set it to $1$. Then, we use the window function `SUM` to calculate the prefix sum, which is the grouping identifier. Finally, we only need to group by the grouping identifier and filter out the numbers with a row count greater than or equal to $3$ in each group. Similarly, we need to use the `DISTINCT` keyword to remove duplicates from the results.", "3": "" }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 181, "explanations": { "1": "We can find employees' salaries and their managers' salaries by self-joining the `Employee` table, then filter out employees whose salaries are higher than their managers' salaries." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 182, "explanations": { "1": "We can use the `GROUP BY` statement to group the data by the `email` field, and then use the `HAVING` statement to filter out the `email` addresses that appear more than once.", "2": "We can use a self-join to join the `Person` table with itself, and then filter out the records where the `id` is different but the `email` is the same." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 183, "explanations": { "1": "List all customer IDs of existing orders, and use `NOT IN` to find customers who are not in the list.", "2": "Use `LEFT JOIN` to join the tables and return the data where `CustomerId` is `NULL`." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 184, "explanations": { "1": "We can use an equi-join to join the `Employee` table and the `Department` table based on `Employee.departmentId = Department.id`, and then use a subquery to find the highest salary for each department. Finally, we can use a `WHERE` clause to filter out the employees with the highest salary in each department.", "2": "We can use an equi-join to join the `Employee` table and the `Department` table based on `Employee.departmentId = Department.id`, and then use the window function `rank()`, which assigns a rank to each employee in each department based on their salary. Finally, we can select the rows with a rank of $1$ for each department." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 185, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 186, "explanations": { "1": "We can iterate through the character array $s$, using two pointers $i$ and $j$ to find the start and end positions of each word, then reverse each word, and finally reverse the entire character array.\n\nThe time complexity is $O(n)$, where $n$ is the length of the character array $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 187, "explanations": { "1": "We define a hash table $cnt$ to store the occurrence count of all substrings of length $10$.\n\nWe iterate through all substrings of length $10$ in the string $s$. For the current substring $t$, we update its count in the hash table. If the count of $t$ is $2$, we add it to the answer.\n\nAfter the iteration, we return the answer array.\n\nThe time complexity is $O(n \\times 10)$, and the space complexity is $O(n \\times 10)$. Here, $n$ is the length of the string $s$.", "2": "This method essentially combines sliding window and hash. Similar to 0028. Find the Index of the First Occurrence in a String, this problem can use a hash function to reduce the time complexity of counting subsequences to $O(1)$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n \\times 10)", "space_complexity": "O(n \\times 10)" }, { "problem_id": 188, "explanations": { "1": "We design a function $dfs(i, j, k)$ to represent the maximum profit that can be obtained when starting from day $i$, completing at most $j$ transactions, and holding the stock with the current state $k$ (not holding the stock is represented by $0$, and holding the stock is represented by $1$). The answer is $dfs(0, k, 0)$.\n\nThe execution logic of the function $dfs(i, j, k)$ is as follows:\n\n- If $i$ is greater than or equal to $n$, return $0$ directly.\n- The i-th day can choose not to do anything, then $dfs(i, j, k) = dfs(i + 1, j, k)$.\n- If $k > 0$, the i-th day can choose to sell the stock, then $dfs(i, j, k) = \\max(dfs(i + 1, j - 1, 0) + prices[i], dfs(i + 1, j, k))$.\n- Otherwise, if $j > 0$, the i-th day can choose to buy the stock, then $dfs(i, j, k) = \\max(dfs(i + 1, j - 1, 1) - prices[i], dfs(i + 1, j, k))$.\n\nThe value of $dfs(i, j, k)$ is the maximum value of the above three cases.\n\nDuring the process, we can use memoization search to save the results of each calculation to avoid repeated calculations.\n\nThe time complexity is $O(n \\times k)$, and the space complexity is $O(n \\times k)$, where $n$ and $k$ are the length of the prices array and the value of $k$, respectively.", "2": "We can also use dynamic programming to define $f[i][j][k]$ as the maximum profit that can be obtained when completing at most j transactions (here we define the number of transactions as the number of purchases), and holding the stock with the current state k on the i-th day. The initial value of $f[i][j][k]$ is 0. The answer is $f[n - 1][k][0]$.\n\nWhen $i = 0$, the stock price is $prices[0]$. For any $j$ \\in [1, k]$, we have $f[0][j][1] = -prices[0]$, which means buying the stock on the 0-th day with a profit of $-prices[0]$.\n\nWhen $i > 0$:\n\n- If the i-th day does not hold the stock, it may be that the stock was held on the i-1-th day and sold on the i-th day, or the stock was not held on the i-1-th day and no operation was performed on the i-th day. Therefore, $f[i][j][0] = \\max(f[i - 1][j][1] + prices[i], f[i - 1][j][0])$.\n- If the i-th day holds the stock, it may be that the stock was not held on the i-1-th day and bought on the i-th day, or the stock was held on the i-1-th day and no operation was performed on the i-th day. Therefore, $f[i][j][1] = max(f[i - 1][j - 1][0] - prices[i], f[i - 1][j][1])$.\n\nTherefore, when $i > 0$, we can get the state transition equation:\n\n$$\n\\begin{aligned}\nf[i][j][0] &= \\max(f[i - 1][j][1] + prices[i], f[i - 1][j][0]) \\\\\nf[i][j][1] &= \\max(f[i - 1][j - 1][0] - prices[i], f[i - 1][j][1])\n\\end{aligned}\n$$\n\nThe final answer is $f[n - 1][k][0]$.\n\nThe time complexity is $O(n \\times k)$, and the space complexity is $O(n \\times k)$, where $n$ and $k$ are the length of the prices array and the value of $k$, respectively.\n\nWe notice that the state $f[i][]$ only depends on the state $f[i - 1][]$, so we can optimize the first dimension of the space and reduce the space complexity to $O(k)$.", "3": "" }, "is_english": true, "time_complexity": "O(n \\times k)", "space_complexity": "O(n \\times k)" }, { "problem_id": 189, "explanations": { "1": "We can assume the length of the array is $n$ and calculate the actual number of steps needed by taking the module of $k$ and $n$, which is $k \\bmod n$.\n\nNext, let us reverse three times to get the final result:\n\n1. Reverse the entire array.\n2. Reverse the first $k$ elements.\n3. Reverse the last $n - k$ elements.\n\nFor example, for the array $[1, 2, 3, 4, 5, 6, 7]$, $k = 3$, $n = 7$, $k \\bmod n = 3$.\n\n1. In the first reverse, reverse the entire array. We get $[7, 6, 5, 4, 3, 2, 1]$.\n2. In the second reverse, reverse the first $k$ elements. We get $[5, 6, 7, 4, 3, 2, 1]$.\n3. In the third reverse, reverse the last $n - k$ elements. We get $[5, 6, 7, 1, 2, 3, 4]$, which is the final result.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 190, "explanations": { "1": "We can extract each bit of $n$ from the lowest bit to the highest bit, and then place it at the corresponding position of $\\textit{ans}$.\n\nFor example, for the $i$-th bit, we can extract the $i$-th bit of $n$ and place it at the $(31 - i)$-th bit of $\\textit{ans}$ by $(n \\& 1) \\ll (31 - i)$, and then right shift $n$ by one bit.\n\nThe time complexity is $O(\\log n)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 191, "explanations": { "1": "利用 `n & (n - 1)` 消除 `n` 中最后一位 1 这一特点,优化过程:\n\n```txt\nHAMMING-WEIGHT(n)\n r = 0\n while n != 0\n n &= n - 1\n r += 1\n r\n```\n\n以 5 为例,演示推演过程:\n\n```txt\n[0, 1, 0, 1] // 5\n[0, 1, 0, 0] // 5 - 1 = 4\n[0, 1, 0, 0] // 5 & 4 = 4\n\n[0, 1, 0, 0] // 4\n[0, 0, 1, 1] // 4 - 1 = 3\n[0, 0, 0, 0] // 4 & 3 = 0\n```", "2": "`x -= (x & -x)` 可以消除二进制形式的最后一位 1。\n\n同 [剑指 Offer 15. 二进制中 1 的个数](https://github.com/doocs/leetcode/blob/main/lcof/面试题15.%20二进制中1的个数/README.md)" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 192, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 193, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 194, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 195, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 196, "explanations": { "1": "", "2": "", "3": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 197, "explanations": { "1": "We can use self-join to compare each row in the `Weather` table with its previous row. If the temperature is higher and the date difference is one day, then it is the result we are looking for.", "2": "" }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 198, "explanations": { "1": "We design a function $\\textit{dfs}(i)$, which represents the maximum amount of money that can be stolen starting from the $i$-th house. Thus, the answer is $\\textit{dfs}(0)$.\n\nThe execution process of the function $\\textit{dfs}(i)$ is as follows:\n\n- If $i \\ge \\textit{len}(\\textit{nums})$, it means all houses have been considered, and we directly return $0$;\n- Otherwise, consider stealing from the $i$-th house, then $\\textit{dfs}(i) = \\textit{nums}[i] + \\textit{dfs}(i+2)$; if not stealing from the $i$-th house, then $\\textit{dfs}(i) = \\textit{dfs}(i+1)$.\n- Return $\\max(\\textit{nums}[i] + \\textit{dfs}(i+2), \\textit{dfs}(i+1))$.\n\nTo avoid repeated calculations, we use memoization search. The result of $\\textit{dfs}(i)$ is saved in an array or hash table. Before each calculation, we first check if it has been calculated. If so, we directly return the result.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array.", "2": "We define $f[i]$ as the maximum total amount that can be robbed from the first $i$ houses, initially $f[0]=0$, $f[1]=nums[0]$.\n\nConsider the case where $i \\gt 1$, the $i$th house has two options:\n\n- Do not rob the $i$th house, the total amount of robbery is $f[i-1]$;\n- Rob the $i$th house, the total amount of robbery is $f[i-2]+nums[i-1]$;\n\nTherefore, we can get the state transition equation:\n\n$$\nf[i]=\n\\begin{cases}\n0, & i=0 \\\\\nnums[0], & i=1 \\\\\n\\max(f[i-1],f[i-2]+nums[i-1]), & i \\gt 1\n\\end{cases}\n$$\n\nThe final answer is $f[n]$, where $n$ is the length of the array.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array.", "3": "We notice that when $i \\gt 2$, $f[i]$ is only related to $f[i-1]$ and $f[i-2]$. Therefore, we can use two variables instead of an array to reduce the space complexity to $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 199, "explanations": { "1": "We can use breadth-first search (BFS) and define a queue $\\textit{q}$ to store the nodes. We start by putting the root node into the queue. Each time, we take out all the nodes of the current level from the queue. For the current node, we first check if the right subtree exists; if it does, we put the right subtree into the queue. Then, we check if the left subtree exists; if it does, we put the left subtree into the queue. This way, the first node taken out from the queue each time is the rightmost node of that level.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree.", "2": "Use DFS (depth-first search) to traverse the binary tree. Each time, traverse the right subtree first, then the left subtree. This way, the first node visited at each level is the rightmost node of that level.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 200, "explanations": { "1": "We can use depth-first search (DFS) to traverse each island. We iterate through each cell $(i, j)$ in the grid. If the cell's value is '1', it means we have found a new island. We can start a DFS from this cell, marking all connected land cells as '0' to avoid duplicate counting. Each time we find a new island, we increment the island count by 1.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Where $m$ and $n$ are the number of rows and columns in the grid, respectively.", "2": "We can also use breadth-first search (BFS) to traverse each island. We iterate through each cell $(i, j)$ in the grid. If the cell's value is '1', it means we have found a new island. We can start a BFS from this cell, marking all connected land cells as '0' to avoid duplicate counting. Each time we find a new island, we increment the island count by 1.\n\nThe specific BFS process is as follows:\n\n1. Enqueue the starting cell $(i, j)$ and mark its value as '0'.\n2. While the queue is not empty, perform the following operations:\n - Dequeue a cell $p$.\n - Iterate through the four adjacent cells $(x, y)$ of $p$. If $(x, y)$ is within the grid bounds and its value is '1', enqueue it and mark its value as '0'.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Where $m$ and $n$ are the number of rows and columns in the grid, respectively.", "3": "We can use the Union-Find data structure to solve this problem. We traverse each cell $(i, j)$ in the grid, and if the cell's value is '1', we merge it with adjacent land cells. Finally, we count the number of distinct root nodes in the Union-Find structure, which represents the number of islands.\n\nThe time complexity is $O(m \\times n \\times \\log (m \\times n))$, and the space complexity is $O(m \\times n)$. Where $m$ and $n$ are the number of rows and columns in the grid, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 201, "explanations": { "1": "题目可以转换为求数字的公共二进制前缀。\n\n当 $left \\lt right$ 时,我们循环将 $right$ 的最后一个二进制位 $1$ 变成 $0$,直到 $left = right$,此时 $right$ 即为数字的公共二进制前缀,返回 $right$ 即可。\n\n时间复杂度 $O(\\log n)$,空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 202, "explanations": { "1": "将每次转换后的数字存入哈希表,如果出现重复数字,说明进入了循环,不是快乐数。否则,如果转换后的数字为 $1$,说明是快乐数。\n\n时间复杂度 $O(\\log n)$,空间复杂度 $O(\\log n)$。", "2": "与判断链表是否存在环原理一致。如果 $n$ 是快乐数,那么快指针最终会与慢指针相遇,且相遇时的数字为 $1$;否则,快指针最终会与慢指针相遇,且相遇时的数字不为 $1$。\n\n因此,最后判断快慢指针相遇时的数字是否为 $1$ 即可。\n\n时间复杂度 $O(\\log n)$,空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(\\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 203, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 204, "explanations": { "1": "如果 $x$ 是质数,那么大于 $x$ 的 $x$ 的倍数 $2x$,$3x$,… 一定不是质数,因此我们可以从这里入手。\n\n设 $primes[i]$ 表示数 $i$ 是不是质数,如果是质数则为 $true$,否则为 $false$。\n\n我们在 $[2,n]$ 范围内顺序遍历每个数 $i$,如果这个数为质数($primes[i]==true$),质数个数增 1,然后将其所有的倍数 $j$ 都标记为合数(除了该质数本身),即 $primes[j]=false$,这样在运行结束的时候我们即能知道质数的个数。\n\n时间复杂度 $O(nloglogn)$。" }, "is_english": false, "time_complexity": "O(nloglogn)", "space_complexity": null }, { "problem_id": 205, "explanations": { "1": "We can use two hash tables or arrays $d_1$ and $d_2$ to record the character mapping relationship between $s$ and $t$.\n\nTraverse $s$ and $t$, if the corresponding character mapping relationships in $d_1$ and $d_2$ are different, return `false`, otherwise update the corresponding character mapping relationships in $d_1$ and $d_2$. After the traversal is complete, it means that $s$ and $t$ are isomorphic, and return `true`.\n\nThe time complexity is $O(n)$ and the space complexity is $O(C)$. Where $n$ is the length of the string $s$; and $C$ is the size of the character set, which is $C = 256$ in this problem.", "2": "" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(C)" }, { "problem_id": 206, "explanations": { "1": "We create a dummy node $\\textit{dummy}$, then traverse the linked list and insert each node after the $\\textit{dummy}$ node. After traversal, return $\\textit{dummy.next}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the linked list. The space complexity is $O(1)$.", "2": "We recursively reverse all nodes from the second node to the end of the list, then attach the $head$ to the end of the reversed list.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the linked list." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 207, "explanations": { "1": "For this problem, we can consider the courses as nodes in a graph, and prerequisites as edges in the graph. Thus, we can transform this problem into determining whether there is a cycle in the directed graph.\n\nSpecifically, we can use the idea of topological sorting. For each node with an in-degree of $0$, we reduce the in-degree of its out-degree nodes by $1$, until all nodes have been traversed.\n\nIf all nodes have been traversed, it means there is no cycle in the graph, and we can complete all courses; otherwise, we cannot complete all courses.\n\nThe time complexity is $O(n + m)$, and the space complexity is $O(n + m)$. Here, $n$ and $m$ are the number of courses and prerequisites respectively." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(n + m)" }, { "problem_id": 208, "explanations": { "1": "前缀树每个节点包括两部分:\n\n1. 指向子节点的指针数组 $children$,对于本题而言,数组长度为 $26$,即小写英文字母的数量。$children[0]$ 对应小写字母 $a$,...,$children[25]$ 对应小写字母 $z$。\n1. 布尔字段 $isEnd$,表示该节点是否为字符串的结尾。\n\n### 1. 插入字符串\n\n我们从字典树的根开始,插入字符串。对于当前字符对应的子节点,有两种情况:\n\n- 子节点存在。沿着指针移动到子节点,继续处理下一个字符。\n- 子节点不存在。创建一个新的子节点,记录在 $children$ 数组的对应位置上,然后沿着指针移动到子节点,继续搜索下一个字符。\n\n重复以上步骤,直到处理字符串的最后一个字符,然后将当前节点标记为字符串的结尾。\n\n### 2. 查找前缀\n\n我们从字典树的根开始,查找前缀。对于当前字符对应的子节点,有两种情况:\n\n- 子节点存在。沿着指针移动到子节点,继续搜索下一个字符。\n- 子节点不存在。说明字典树中不包含该前缀,返回空指针。\n\n重复以上步骤,直到返回空指针或搜索完前缀的最后一个字符。\n\n若搜索到了前缀的末尾,就说明字典树中存在该前缀。此外,若前缀末尾对应节点的 $isEnd$ 为真,则说明字典树中存在该字符串。\n\n时间复杂度方面,插入字符串的时间复杂度为 $O(m \\times |\\Sigma|)$,查找前缀的时间复杂度为 $O(m)$,其中 $m$ 为字符串的长度,而 $|\\Sigma|$ 为字符集的大小(本题中为 $26$)。空间复杂度为 $O(q \\times m \\times |\\Sigma|)$,其中 $q$ 为插入的字符串数量。" }, "is_english": false, "time_complexity": "O(m \\times |\\Sigma|)", "space_complexity": "O(q \\times m \\times |\\Sigma|)" }, { "problem_id": 209, "explanations": { "1": "First, we preprocess the prefix sum array $s$ of the array $nums$, where $s[i]$ represents the sum of the first $i$ elements of the array $nums$. Since all elements in the array $nums$ are positive integers, the array $s$ is also monotonically increasing. Also, we initialize the answer $ans = n + 1$, where $n$ is the length of the array $nums$.\n\nNext, we traverse the prefix sum array $s$. For each element $s[i]$, we can find the smallest index $j$ that satisfies $s[j] \\geq s[i] + target$ by binary search. If $j \\leq n$, it means that there exists a subarray that satisfies the condition, and we can update the answer, i.e., $ans = min(ans, j - i)$.\n\nFinally, if $ans \\leq n$, it means that there exists a subarray that satisfies the condition, return $ans$, otherwise return $0$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$.", "2": "We can use two pointers $j$ and $i$ to maintain a window, where the sum of all elements in the window is less than $target$. Initially, $j = 0$, and the answer $ans = n + 1$, where $n$ is the length of the array $nums$.\n\nNext, the pointer $i$ starts to move to the right from $0$, moving one step each time. We add the element corresponding to the pointer $i$ to the window and update the sum of the elements in the window. If the sum of the elements in the window is greater than or equal to $target$, it means that the current subarray satisfies the condition, and we can update the answer, i.e., $ans = \\min(ans, i - j + 1)$. Then we continuously remove the element $nums[j]$ from the window until the sum of the elements in the window is less than $target$, and then repeat the above process.\n\nFinally, if $ans \\leq n$, it means that there exists a subarray that satisfies the condition, return $ans$, otherwise return $0$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 210, "explanations": { "1": "我们创建一个邻接表 $g$,用于存储每个节点的后继节点,同时还需要一个数组 $indeg$ 存储每个节点的入度。在构建邻接表的同时,我们也统计每个节点的入度。当入度为 $0$ 的节点代表没有任何前置课程,可以直接学习,我们将其加入队列 $q$ 中。\n\n当队列 $q$ 不为空的时候,我们取出队首的节点 $i$:\n\n- 我们将 $i$ 放入答案中;\n- 接下来,我们将 $i$ 的所有后继节点的入度减少 $1$。如果发现某个后继节点 $j$ 的入度变为 $0$,则将 $j$ 放入队列 $q$ 中。\n\n在广度优先搜索的结束时,如果答案中包含了这 $n$ 个节点,那么我们就找到了一种拓扑排序,否则说明图中存在环,也就不存在拓扑排序了。\n\n时间复杂度 $O(n + m)$,空间复杂度 $O(n + m)$。其中 $n$ 和 $m$ 分别是节点数和边数。" }, "is_english": false, "time_complexity": "O(n + m)", "space_complexity": "O(n + m)" }, { "problem_id": 211, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 212, "explanations": { "1": "我们首先将 `words` 中的单词构建成前缀树,前缀树的每个节点包含一个长度为 $26$ 的数组 `children`,表示该节点的子节点,数组的下标表示子节点对应的字符,数组的值表示子节点的引用。同时,每个节点还包含一个整数 `ref`,表示该节点对应的单词在 `words` 中的引用,如果该节点不是单词的结尾,则 `ref` 的值为 $-1$。\n\n接下来,我们对于 `board` 中的每个单元格,从该单元格出发,进行深度优先搜索,搜索过程中,如果当前单词不是前缀树中的单词,则剪枝,如果当前单词是前缀树中的单词,则将该单词加入答案,并将该单词在前缀树中的引用置为 $-1$,表示该单词已经被找到,不需要再次搜索。\n\n最后,我们将答案返回即可。\n\n时间复杂度 $(m \\times n \\times 3^{l-1})$,空间复杂度 $(k \\times l)$。其中 $m$ 和 $n$ 分别是 `board` 的行数和列数。而 $l$ 和 $k$ 分别是 `words` 中的单词的平均长度和单词的个数。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 213, "explanations": { "1": "The circular arrangement means that at most one of the first and last houses can be chosen for theft, so this circular arrangement problem can be reduced to two single-row house problems.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 214, "explanations": { "1": "**字符串哈希**是把一个任意长度的字符串映射成一个非负整数,并且其冲突的概率几乎为 0。字符串哈希用于计算字符串哈希值,快速判断两个字符串是否相等。\n\n取一固定值 BASE,把字符串看作是 BASE 进制数,并分配一个大于 0 的数值,代表每种字符。一般来说,我们分配的数值都远小于 BASE。例如,对于小写字母构成的字符串,可以令 a=1, b=2, ..., z=26。取一固定值 MOD,求出该 BASE 进制对 M 的余数,作为该字符串的 hash 值。\n\n一般来说,取 BASE=131 或者 BASE=13331,此时 hash 值产生的冲突概率极低。只要两个字符串 hash 值相同,我们就认为两个字符串是相等的。通常 MOD 取 2^64,C++ 里,可以直接使用 unsigned long long 类型存储这个 hash 值,在计算时不处理算术溢出问题,产生溢出时相当于自动对 2^64 取模,这样可以避免低效取模运算。\n\n除了在极特殊构造的数据上,上述 hash 算法很难产生冲突,一般情况下上述 hash 算法完全可以出现在题目的标准答案中。我们还可以多取一些恰当的 BASE 和 MOD 的值(例如大质数),多进行几组 hash 运算,当结果都相同时才认为原字符串相等,就更加难以构造出使这个 hash 产生错误的数据。\n\n对于本题,问题等价于**找到字符串 s 的最长回文前缀**。\n\n记 s 的长度为 n,其最长回文前缀的长度为 m,将 s 的后 n-m 个字符反序并添加到 s 的前面即可构成最短回文串。", "2": "According to the problem description, we need to reverse the string $s$ to obtain the string $\\textit{rev}$, and then find the longest common part of the suffix of the string $\\textit{rev}$ and the prefix of the string $s$. We can use the KMP algorithm to concatenate the string $s$ and the string $\\textit{rev}$ and find the longest common part of the longest prefix and the longest suffix.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 215, "explanations": { "1": "Quick Select is an algorithm for finding the $k^{th}$ largest or smallest element in an unsorted array. Its basic idea is to select a pivot element each time, dividing the array into two parts: one part contains elements smaller than the pivot, and the other part contains elements larger than the pivot. Then, based on the position of the pivot, it decides whether to continue the search on the left or right side until the $k^{th}$ largest element is found.\n\nThe time complexity is $O(n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array $\\textit{nums}$.", "2": "We can maintain a min heap $\\textit{minQ}$ of size $k$, and then iterate through the array $\\textit{nums}$, adding each element to the min heap. When the size of the min heap exceeds $k$, we pop the top element of the heap. This way, the final $k$ elements in the min heap are the $k$ largest elements in the array, and the top element of the heap is the $k^{th}$ largest element.\n\nThe time complexity is $O(n\\log k)$, and the space complexity is $O(k)$. Here, $n$ is the length of the array $\\textit{nums}$.", "3": "We can use the idea of counting sort, counting the occurrence of each element in the array $\\textit{nums}$ and recording it in a hash table $\\textit{cnt}$. Then, we iterate over the elements $i$ from largest to smallest, subtracting the occurrence count $\\textit{cnt}[i]$ each time, until $k$ is less than or equal to $0$. At this point, the element $i$ is the $k^{th}$ largest element in the array.\n\nThe time complexity is $O(n + m)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$, and $m$ is the maximum value among the elements in $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(\\log n)" }, { "problem_id": 216, "explanations": { "1": "We design a function $dfs(i, s)$, which represents that we are currently enumerating the number $i$, and there are still numbers with a sum of $s$ to be enumerated. The current search path is $t$, and the answer is $ans$.\n\nThe execution logic of the function $dfs(i, s)$ is as follows:\n\nApproach One:\n\n- If $s = 0$ and the length of the current search path $t$ is $k$, it means that a group of answers has been found. Add $t$ to $ans$ and then return.\n- If $i \\gt 9$ or $i \\gt s$ or the length of the current search path $t$ is greater than $k$, it means that the current search path cannot be the answer, so return directly.\n- Otherwise, we can choose to add the number $i$ to the search path $t$, and then continue to search, i.e., execute $dfs(i + 1, s - i)$. After the search is completed, remove $i$ from the search path $t$; we can also choose not to add the number $i$ to the search path $t$, and directly execute $dfs(i + 1, s)$.", "2": "We can use a binary integer of length $9$ to represent the selection of numbers $1$ to $9$, where the $i$-th bit of the binary integer represents whether the number $i + 1$ is selected. If the $i$-th bit is $1$, it means that the number $i + 1$ is selected, otherwise, it means that the number $i + 1$ is not selected.\n\nWe enumerate binary integers in the range of $[0, 2^9)$. For the currently enumerated binary integer $mask$, if the number of $1$s in the binary representation of $mask$ is $k$, and the sum of the numbers corresponding to $1$ in the binary representation of $mask$ is $n$, it means that the number selection scheme corresponding to $mask$ is a group of answers. We can add the number selection scheme corresponding to $mask$ to the answer.\n\nThe time complexity is $O(2^9 \\times 9)$, and the space complexity is $O(k)$.\n\nSimilar problems:\n\n- [39. Combination Sum](https://github.com/doocs/leetcode/blob/main/solution/0000-0099/0039.Combination%20Sum/README_EN.md)\n- [40. Combination Sum II](https://github.com/doocs/leetcode/blob/main/solution/0000-0099/0040.Combination%20Sum%20II/README_EN.md)\n- [77. Combinations](https://github.com/doocs/leetcode/blob/main/solution/0000-0099/0077.Combinations/README_EN.md)" }, "is_english": true, "time_complexity": "O(2^9 \\times 9)", "space_complexity": "O(k)" }, { "problem_id": 217, "explanations": { "1": "First, we sort the array `nums`.\n\nThen, we traverse the array. If there are two adjacent elements that are the same, it means that there are duplicate elements in the array, and we directly return `true`.\n\nOtherwise, when the traversal ends, we return `false`.\n\nThe time complexity is $O(n \\times \\log n)$, where $n$ is the length of the array `nums`.", "2": "We traverse the array and record the elements that have appeared in the hash table $s$. If an element appears for the second time, it means that there are duplicate elements in the array, and we directly return `true`.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array `nums`." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 218, "explanations": { "1": "记录下所有建筑物的左右边界线,升序排序之后得到序列 lines。对于每一个边界线 lines[i],找出所有包含 lines[i] 的建筑物,并确保建筑物的左边界小于等于 lines[i],右边界大于 lines[i],则这些建筑物中高度最高的建筑物的高度就是该线轮廓点的高度。可以使用建筑物的高度构建优先队列(大根堆),同时需要注意高度相同的轮廓点需要合并为一个。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 219, "explanations": { "1": "We use a hash table $\\textit{d}$ to store the recently traversed numbers and their corresponding indices.\n\nTraverse the array $\\textit{nums}$. For the current element $\\textit{nums}[i]$, if it exists in the hash table and the difference between the indices is no more than $k$, return $\\text{true}$. Otherwise, add the current element to the hash table.\n\nAfter traversing, return $\\text{false}$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 220, "explanations": { "1": "We maintain a sliding window of size $k$, and the elements in the window are kept in order.\n\nWe traverse the array `nums`. For each element $nums[i]$, we look for the first element in the ordered set that is greater than or equal to $nums[i] - t$. If the element exists, and this element is less than or equal to $nums[i] + t$, it means we have found a pair of elements that meet the conditions, and we return `true`. Otherwise, we insert $nums[i]$ into the ordered set, and if the size of the ordered set exceeds $k$, we need to remove the earliest added element from the ordered set.\n\nThe time complexity is $O(n \\times \\log k)$, where $n$ is the length of the array `nums`. For each element, we need $O(\\log k)$ time to find the element in the ordered set, and there are $n$ elements in total, so the total time complexity is $O(n \\times \\log k)$." }, "is_english": true, "time_complexity": "O(n \\times \\log k)", "space_complexity": null }, { "problem_id": 221, "explanations": { "1": "We define $dp[i + 1][j + 1]$ as the maximum square side length with the lower right corner at index $(i, j)$. The answer is the maximum value among all $dp[i + 1][j + 1]$.\n\nThe state transition equation is:\n\n$$\ndp[i + 1][j + 1] =\n\\begin{cases}\n0 & \\textit{if } matrix[i][j] = '0' \\\\\n\\min(dp[i][j], dp[i][j + 1], dp[i + 1][j]) + 1 & \\textit{if } matrix[i][j] = '1'\n\\end{cases}\n$$\n\nThe time complexity is $O(m\\times n)$, and the space complexity is $O(m\\times n)$. Where $m$ and $n$ are the number of rows and columns of the matrix, respectively." }, "is_english": true, "time_complexity": "O(m\\times n)", "space_complexity": "O(m\\times n)" }, { "problem_id": 222, "explanations": { "1": "We recursively traverse the entire tree and count the number of nodes.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of nodes in the tree.", "2": "For this problem, we can also take advantage of the characteristics of a complete binary tree to design a faster algorithm.\n\nCharacteristics of a complete binary tree: leaf nodes can only appear on the bottom and second-to-bottom layers, and the leaf nodes on the bottom layer are concentrated on the left side of the tree. It should be noted that a full binary tree is definitely a complete binary tree, but a complete binary tree is not necessarily a full binary tree.\n\nIf the number of layers in a full binary tree is $h$, then the total number of nodes is $2^h - 1$.\n\nWe first count the heights of the left and right subtrees of $root$, denoted as $left$ and $right$.\n\n1. If $left = right$, it means that the left subtree is a full binary tree, so the total number of nodes in the left subtree is $2^{left} - 1$. Plus the $root$ node, it is $2^{left}$. Then we recursively count the right subtree.\n1. If $left > right$, it means that the right subtree is a full binary tree, so the total number of nodes in the right subtree is $2^{right} - 1$. Plus the $root$ node, it is $2^{right}$. Then we recursively count the left subtree.\n\nThe time complexity is $O(\\log^2 n)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 223, "explanations": { "1": "First, we calculate the area of the two rectangles separately, denoted as $a$ and $b$. Then we calculate the overlapping width $width$ and height $height$. The overlapping area is $max(width, 0) \\times max(height, 0)$. Finally, we subtract the overlapping area from $a$ and $b$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 224, "explanations": { "1": "We use a stack $stk$ to save the current calculation result and operator, a variable $sign$ to save the current sign, and a variable $ans$ to save the final calculation result.\n\nNext, we traverse each character of the string $s$:\n\n- If the current character is a number, we use a loop to read the following consecutive numbers, and then add or subtract it to $ans$ according to the current sign.\n- If the current character is `'+'`, we change the variable $sign$ to positive.\n- If the current character is `'-'`, we change the variable $sign$ to negative.\n- If the current character is `'('`, we push the current $ans$ and $sign$ into the stack, and reset them to empty and 1, and start to calculate the new $ans$ and $sign$.\n- If the current character is `')'`, we pop the top two elements of the stack, one is the operator, and the other is the number calculated before the bracket. We multiply the current number by the operator, and add the previous number to get the new $ans$.\n\nAfter traversing the string $s$, we return $ans$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 225, "explanations": { "1": "We use two queues $q_1$ and $q_2$, where $q_1$ is used to store the elements in the stack, and $q_2$ is used to assist in implementing the stack operations.\n\n- `push` operation: Push the element into $q_2$, then pop the elements in $q_1$ one by one and push them into $q_2$, finally swap the references of $q_1$ and $q_2$. The time complexity is $O(n)$.\n- `pop` operation: Directly pop the front element of $q_1$. The time complexity is $O(1)$.\n- `top` operation: Directly return the front element of $q_1$. The time complexity is $O(1)$.\n- `empty` operation: Check whether $q_1$ is empty. The time complexity is $O(1)$.\n\nThe space complexity is $O(n)$, where $n$ is the number of elements in the stack." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 226, "explanations": { "1": "First, we check if $\\textit{root}$ is null. If it is, we return $\\text{null}$. Then, we recursively invert the left and right subtrees, set the inverted right subtree as the new left subtree, and set the inverted left subtree as the new right subtree. Finally, we return $\\textit{root}$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 227, "explanations": { "1": "We traverse the string $s$, and use a variable `sign` to record the operator before each number. For the first number, its previous operator is considered as a plus sign. Each time we traverse to the end of a number, we decide the calculation method based on `sign`:\n\n- Plus sign: push the number into the stack;\n- Minus sign: push the opposite number into the stack;\n- Multiplication and division signs: calculate the number with the top element of the stack, and replace the top element of the stack with the calculation result.\n\nAfter the traversal ends, the sum of the elements in the stack is the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 228, "explanations": { "1": "We can use two pointers $i$ and $j$ to find the left and right endpoints of each interval.\n\nTraverse the array, when $j + 1 < n$ and $nums[j + 1] = nums[j] + 1$, move $j$ to the right, otherwise the interval $[i, j]$ has been found, add it to the answer, then move $i$ to the position of $j + 1$, and continue to find the next interval.\n\nTime complexity $O(n)$, where $n$ is the length of the array. Space complexity $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 229, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 230, "explanations": { "1": "由于二叉搜索树的性质,中序遍历一定能得到升序序列,因此可以采用中序遍历找出第 k 小的元素。", "2": "预处理每个结点作为根节点的子树的节点数。\n\n这种算法可以用来优化频繁查找第 k 个树、而二叉搜索树本身不被修改的情况。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 231, "explanations": { "1": "According to the properties of bit manipulation, executing $\\texttt{n\\&(n-1)}$ can eliminate the last bit $1$ in the binary form of $n$. Therefore, if $n > 0$ and $\\texttt{n\\&(n-1)}$ results in $0$, then $n$ is a power of $2$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$.", "2": "According to the definition of $\\text{lowbit}$, we know that $\\text{lowbit}(x) = x \\& (-x)$, which can get the decimal number represented by the last bit $1$ of $n$. Therefore, if $n > 0$ and $\\text{lowbit}(n)$ equals $n$, then $n$ is a power of $2$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 232, "explanations": { "1": "We use two stacks, where `stk1` is used for enqueue, and another stack `stk2` is used for dequeue.\n\nWhen enqueueing, we directly push the element into `stk1`. The time complexity is $O(1)$.\n\nWhen dequeueing, we first check whether `stk2` is empty. If it is empty, we pop all elements from `stk1` and push them into `stk2`, and then pop an element from `stk2`. If `stk2` is not empty, we directly pop an element from `stk2`. The amortized time complexity is $O(1)$.\n\nWhen getting the front element, we first check whether `stk2` is empty. If it is empty, we pop all elements from `stk1` and push them into `stk2`, and then get the top element from `stk2`. If `stk2` is not empty, we directly get the top element from `stk2`. The amortized time complexity is $O(1)$.\n\nWhen checking whether the queue is empty, we only need to check whether both stacks are empty. The time complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": null }, { "problem_id": 233, "explanations": { "1": "This problem essentially asks for the number of times the digit $1$ appears in the given range $[l, ..r]$. The count is related to the number of digits and the value of each digit. We can use the concept of Digit DP to solve this problem. In Digit DP, the size of the number has little impact on the complexity.\n\nFor the range $[l, ..r]$ problem, we generally convert it to the problem of $[1, ..r]$ and then subtract the result of $[1, ..l - 1]$, i.e.:\n\n$$\nans = \\sum_{i=1}^{r} ans_i - \\sum_{i=1}^{l-1} ans_i\n$$\n\nHowever, for this problem, we only need to find the value for the range $[1, ..r]$.\n\nHere, we use memoized search to implement Digit DP. We search from the starting point downwards, and at the lowest level, we get the number of solutions. We then return the answers layer by layer upwards, and finally get the final answer from the starting point of the search.\n\nThe basic steps are as follows:\n\nFirst, we convert the number $n$ to a string $s$. Then we design a function $\\textit{dfs}(i, \\textit{cnt}, \\textit{limit})$, where:\n\n- The digit $i$ represents the current position being searched, starting from the highest digit, i.e., $i = 0$ represents the highest digit.\n- The digit $\\textit{cnt}$ represents the current count of the digit $1$ in the number.\n- The boolean $\\textit{limit}$ indicates whether the current number is restricted by the upper bound.\n\nThe function executes as follows:\n\nIf $i$ exceeds the length of the number $n$, it means the search is over, directly return $cnt$. If $\\textit{limit}$ is true, $up$ is the $i$-th digit of the current number. Otherwise, $up = 9$. Next, we iterate $j$ from $0$ to $up$. For each $j$:\n\n- If $j$ equals $1$, we increment $cnt$ by one.\n- Recursively call $\\textit{dfs}(i + 1, \\textit{cnt}, \\textit{limit} \\land j = up)$.\n\nThe answer is $\\textit{dfs}(0, 0, \\text{True})$.\n\nThe time complexity is $O(m^2 \\times D)$, and the space complexity is $O(m^2)$. Here, $m$ is the length of the number $n$, and $D = 10$.\n\nSimilar Problems:\n\nHere is the translation of the similar problems into English:\n\n- [357. Count Numbers with Unique Digits](https://github.com/doocs/leetcode/blob/main/solution/0300-0399/0357.Count%20Numbers%20with%20Unique%20Digits/README_EN.md)\n- [600. Non-negative Integers without Consecutive Ones](https://github.com/doocs/leetcode/blob/main/solution/0600-0699/0600.Non-negative%20Integers%20without%20Consecutive%20Ones/README_EN.md)\n- [788. Rotated Digits](https://github.com/doocs/leetcode/blob/main/solution/0700-0799/0788.Rotated%20Digits/README_EN.md)\n- [902. Numbers At Most N Given Digit Set](https://github.com/doocs/leetcode/blob/main/solution/0900-0999/0902.Numbers%20At%20Most%20N%20Given%20Digit%20Set/README_EN.md)\n- [1012. Numbers with Repeated Digits](https://github.com/doocs/leetcode/blob/main/solution/1000-1099/1012.Numbers%20With%20Repeated%20Digits/README_EN.md)\n- [2376. Count Special Integers](https://github.com/doocs/leetcode/blob/main/solution/2300-2399/2376.Count%20Special%20Integers/README_EN.md)" }, "is_english": true, "time_complexity": "O(m^2 \\times D)", "space_complexity": "O(m^2)" }, { "problem_id": 234, "explanations": { "1": "We can use fast and slow pointers to find the middle of the linked list, then reverse the right half of the list. After that, we traverse both halves simultaneously, checking if the corresponding node values are equal. If any pair of values is unequal, it's not a palindrome linked list; otherwise, it is a palindrome linked list.\n\nThe time complexity is $O(n)$, where $n$ is the length of the linked list. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 235, "explanations": { "1": "Starting from the root node, we traverse the tree. If the current node's value is less than both $\\textit{p}$ and $\\textit{q}$ values, it means that $\\textit{p}$ and $\\textit{q}$ should be in the right subtree of the current node, so we move to the right child. If the current node's value is greater than both $\\textit{p}$ and $\\textit{q}$ values, it means that $\\textit{p}$ and $\\textit{q}$ should be in the left subtree, so we move to the left child. Otherwise, it means the current node is the lowest common ancestor of $\\textit{p}$ and $\\textit{q}$, so we return the current node.\n\nThe time complexity is $O(n)$, where $n$ is the number of nodes in the binary search tree. The space complexity is $O(1)$.", "2": "We can also use a recursive approach to solve this problem.\n\nWe first check if the current node's value is less than both $\\textit{p}$ and $\\textit{q}$ values. If it is, we recursively traverse the right subtree. If the current node's value is greater than both $\\textit{p}$ and $\\textit{q}$ values, we recursively traverse the left subtree. Otherwise, it means the current node is the lowest common ancestor of $\\textit{p}$ and $\\textit{q}$, so we return the current node.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in the binary search tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 236, "explanations": { "1": "We recursively traverse the binary tree:\n\nIf the current node is null or equals to $p$ or $q$, then we return the current node;\n\nOtherwise, we recursively traverse the left and right subtrees, and record the returned results as $left$ and $right$. If both $left$ and $right$ are not null, it means that $p$ and $q$ are in the left and right subtrees respectively, so the current node is the nearest common ancestor; If only one of $left$ and $right$ is not null, we return the one that is not null.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 237, "explanations": { "1": "We can replace the value of the current node with the value of the next node, and then delete the next node. This can achieve the purpose of deleting the current node.\n\nTime complexity $O(1)$, space complexity $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 238, "explanations": { "1": "We define two variables $\\textit{left}$ and $\\textit{right}$ to represent the product of all elements to the left and right of the current element, respectively. Initially, $\\textit{left} = 1$ and $\\textit{right} = 1$. We define an answer array $\\textit{ans}$ of length $n$.\n\nFirst, we traverse the array from left to right. For the $i$-th element, we update $\\textit{ans}[i]$ with $\\textit{left}$, then multiply $\\textit{left}$ by $\\textit{nums}[i]$.\n\nNext, we traverse the array from right to left. For the $i$-th element, we update $\\textit{ans}[i]$ to $\\textit{ans}[i] \\times \\textit{right}$, then multiply $\\textit{right}$ by $\\textit{nums}[i]$.\n\nAfter the traversal, we return the answer array $\\textit{ans}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. Ignoring the space consumption of the answer array, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 239, "explanations": { "1": "We can use a priority queue (max-heap) to maintain the maximum value in the sliding window.\n\nFirst, add the first $k-1$ elements to the priority queue. Then, starting from the $k$-th element, add the new element to the priority queue and check if the top element of the heap is out of the window. If it is, remove the top element. Then, add the top element of the heap to the result array.\n\nThe time complexity is $O(n \\times \\log k)$, and the space complexity is $O(k)$. Here, $n$ is the length of the array.", "2": "To find the maximum value in a sliding window, a common method is to use a monotonic queue.\n\nWe can maintain a queue $q$ that is monotonically decreasing from the front to the back, storing the indices of the elements. As we traverse the array $\\textit{nums}$, for the current element $\\textit{nums}[i]$, we first check if the front element of the queue is out of the window. If it is, we remove the front element. Then, we compare the current element $\\textit{nums}[i]$ with the elements at the back of the queue. If the elements at the back are less than or equal to the current element, we remove them until the element at the back is greater than the current element or the queue is empty. Then, we add the index of the current element to the queue. At this point, the front element of the queue is the maximum value of the current sliding window. Note that we add the front element of the queue to the result array when the index $i$ is greater than or equal to $k-1$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(k)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times \\log k)", "space_complexity": "O(k)" }, { "problem_id": 240, "explanations": { "1": "Since all elements in each row are sorted in ascending order, for each row, we can use binary search to find the first element greater than or equal to $\\textit{target}$, and then check if that element is equal to $\\textit{target}$. If it is equal to $\\textit{target}$, it means the target value is found, and we return $\\text{true}$. If it is not equal to $\\textit{target}$, it means all elements in this row are less than $\\textit{target}$, and we should continue searching the next row.\n\nIf all rows have been searched and the target value is not found, it means the target value does not exist, and we return $\\text{false}$.\n\nThe time complexity is $O(m \\times \\log n)$, where $m$ and $n$ are the number of rows and columns of the matrix, respectively. The space complexity is $O(1)$.", "2": "We start the search from the bottom-left or top-right corner and move towards the top-right or bottom-left direction. Compare the current element $\\textit{matrix}[i][j]$ with $\\textit{target}$:\n\n- If $\\textit{matrix}[i][j] = \\textit{target}$, it means the target value is found, and we return $\\text{true}$.\n- If $\\textit{matrix}[i][j] > \\textit{target}$, it means all elements in this column from the current position upwards are greater than $\\textit{target}$, so we move the $i$ pointer upwards, i.e., $i \\leftarrow i - 1$.\n- If $\\textit{matrix}[i][j] < \\textit{target}$, it means all elements in this row from the current position to the right are less than $\\textit{target}$, so we move the $j$ pointer to the right, i.e., $j \\leftarrow j + 1$.\n\nIf the search ends and the $\\textit{target}$ is not found, return $\\text{false}$.\n\nThe time complexity is $O(m + n)$, where $m$ and $n$ are the number of rows and columns of the matrix, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m \\times \\log n)", "space_complexity": "O(1)" }, { "problem_id": 241, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 242, "explanations": { "1": "We first determine whether the length of the two strings is equal. If they are not equal, the characters in the two strings must be different, so return `false`.\n\nOtherwise, we use a hash table or an array of length $26$ to record the number of times each character appears in the string $s$, and then traverse the other string $t$. Each time we traverse a character, we subtract the number of times the corresponding character appears in the hash table by one. If the number of times after subtraction is less than $0$, the number of times the character appears in the two strings is different, return `false`. If after traversing the two strings, all the character counts in the hash table are $0$, it means that the characters in the two strings appear the same number of times, return `true`.\n\nThe time complexity is $O(n)$, the space complexity is $O(C)$, where $n$ is the length of the string; and $C$ is the size of the character set, which is $C=26$ in this problem.", "2": "" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(C)" }, { "problem_id": 243, "explanations": { "1": "遍历数组 `wordsDict`,找到 `word1` 和 `word2` 的下标 $i$ 和 $j$,求 $i-j$ 的最小值。\n\n时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 `wordsDict` 的长度。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 244, "explanations": { "1": "我们用哈希表 $d$ 存储每个单词在数组中出现的所有下标,然后用双指针 $i$ 和 $j$ 分别指向两个单词在数组中出现的下标列表 $a$ 和 $b$,每次更新下标差值的最小值,然后移动下标较小的指针,直到其中一个指针遍历完下标列表。\n\n初始化的时间复杂度为 $O(n)$,其中 $n$ 为数组的长度。每次调用 `shortest` 方法的时间复杂度为 $O(m + n)$,其中 $m$ 为两个单词在数组中出现的下标列表的长度之和。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": null }, { "problem_id": 245, "explanations": { "1": "First, we check whether $\\textit{word1}$ and $\\textit{word2}$ are equal:\n\n- If they are equal, iterate through the array $\\textit{wordsDict}$ to find two indices $i$ and $j$ of $\\textit{word1}$, and compute the minimum value of $i-j$.\n- If they are not equal, iterate through the array $\\textit{wordsDict}$ to find the indices $i$ of $\\textit{word1}$ and $j$ of $\\textit{word2}$, and compute the minimum value of $i-j$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{wordsDict}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 246, "explanations": { "1": "We define an array $d$, where $d[i]$ represents the number after rotating the digit $i$ by 180°. If $d[i]$ is $-1$, it means that the digit $i$ cannot be rotated 180° to get a valid digit.\n\nWe define two pointers $i$ and $j$, pointing to the left and right ends of the string, respectively. Then we continuously move the pointers towards the center, checking whether $d[num[i]]$ and $num[j]$ are equal. If they are not equal, it means that the string is not a strobogrammatic number, and we can directly return $false$. If $i > j$, it means that we have traversed the entire string, and we return $true$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 247, "explanations": { "1": "If the length is $1$, then the strobogrammatic numbers are only $0, 1, 8$; if the length is $2$, then the strobogrammatic numbers are only $11, 69, 88, 96$.\n\nWe design a recursive function $dfs(u)$, which returns the strobogrammatic numbers of length $u$. The answer is $dfs(n)$.\n\nIf $u$ is $0$, return a list containing an empty string, i.e., `[\"\"]`; if $u$ is $1$, return the list `[\"0\", \"1\", \"8\"]`.\n\nIf $u$ is greater than $1$, we traverse all the strobogrammatic numbers of length $u - 2$. For each strobogrammatic number $v$, we add $1, 8, 6, 9$ to both sides of it, and we can get the strobogrammatic numbers of length `u`.\n\nNote that if $u \\neq n$, we can also add $0$ to both sides of the strobogrammatic number.\n\nFinally, we return all the strobogrammatic numbers of length $n$.\n\nThe time complexity is $O(2^{n+2})$.\n\nSimilar problems:\n\n- [248. Strobogrammatic Number III 🔒](https://github.com/doocs/leetcode/blob/main/solution/0200-0299/0248.Strobogrammatic%20Number%20III/README_EN.md)" }, "is_english": true, "time_complexity": "O(2^{n+2})", "space_complexity": null }, { "problem_id": 248, "explanations": { "1": "If the length is $1$, then the strobogrammatic numbers are only $0, 1, 8$; if the length is $2$, then the strobogrammatic numbers are only $11, 69, 88, 96$.\n\nWe design a recursive function $dfs(u)$, which returns the strobogrammatic numbers of length $u$.\n\nIf $u$ is $0$, return a list containing an empty string, i.e., `[\"\"]`; if $u$ is $1$, return the list `[\"0\", \"1\", \"8\"]`.\n\nIf $u$ is greater than $1$, we traverse all the strobogrammatic numbers of length $u - 2$. For each strobogrammatic number $v$, we add $1, 8, 6, 9$ to both sides of it, and we can get the strobogrammatic numbers of length $u$.\n\nNote that if $u \\neq n$, we can also add $0$ to both sides of the strobogrammatic number.\n\nLet the lengths of $low$ and $high$ be $a$ and $b$ respectively.\n\nNext, we traverse all lengths in the range $[a,..b]$. For each length $n$, we get all strobogrammatic numbers $dfs(n)$, and then check whether they are in the range $[low, high]$. If they are, we increment the answer.\n\nThe time complexity is $O(2^{n+2} \\times \\log n)$.\n\nSimilar problems:\n\n- [247. Strobogrammatic Number II](https://github.com/doocs/leetcode/blob/main/solution/0200-0299/0247.Strobogrammatic%20Number%20II/README_EN.md)" }, "is_english": true, "time_complexity": "O(2^{n+2} \\times \\log n)", "space_complexity": null }, { "problem_id": 249, "explanations": { "1": "We use a hash table $g$ to store each string after shifting and with the first character as '`a`'. That is, $g[t]$ represents the set of all strings that become $t$ after shifting.\n\nWe iterate through each string. For each string, we calculate its shifted string $t$, and then add it to $g[t]$.\n\nFinally, we take out all the values in $g$, which is the answer.\n\nThe time complexity is $O(L)$ and the space complexity is $O(L)$, where $L$ is the sum of the lengths of all strings." }, "is_english": true, "time_complexity": "O(L)", "space_complexity": "O(L)" }, { "problem_id": 250, "explanations": { "1": "我们设计一个递归函数 $dfs(root)$,该函数返回以 $root$ 为根的子树中所有节点的值是否相同。\n\n函数 $dfs(root)$ 的递归过程如下:\n\n- 如果 $root$ 为空,则返回 `true`;\n- 否则,我们递归地计算 $root$ 的左右子树,记为 $l$ 和 $r$;如果 $l$ 为 `false` 或者 $r$ 为 `false`,则返回 `false`;如果 $root$ 的左子树不为空且 $root$ 的左子树的值不等于 $root$ 的值,或者 $root$ 的右子树不为空且 $root$ 的右子树的值不等于 $root$ 的值,则返回 `false`;否则,我们将答案加一,并返回 `true`。\n\n递归结束后,返回答案即可。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点个数。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 251, "explanations": { "1": "我们定义两个指针 $i$ 和 $j$,分别指向当前二维向量的行和列,初始时 $i = 0$,$j = 0$。\n\n接下来,我们设计一个函数 $forward()$,用于将 $i$ 和 $j$ 向后移动,直到指向一个非空的元素。\n\n每次调用 `next` 方法时,我们先调用 $forward()$,然后返回当前指向的元素,最后将 $j$ 向后移动一位。\n\n每次调用 `hasNext` 方法时,我们先调用 $forward()$,然后判断 $i$ 是否小于二维向量的行数,如果是,则返回 `true`,否则返回 `false`。\n\n时间复杂度 $O(1)$,空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 252, "explanations": { "1": "We sort the meetings based on their start times, and then iterate through the sorted meetings. If the start time of the current meeting is less than the end time of the previous meeting, it indicates that there is an overlap between the two meetings, and we return `false`. Otherwise, we continue iterating.\n\nIf no overlap is found by the end of the iteration, we return `true`.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$, where $n$ is the number of meetings." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 253, "explanations": { "1": "We can implement this using a difference array.\n\nFirst, we find the maximum end time of all the meetings, denoted as $m$. Then, we create a difference array $d$ of length $m + 1$. For each meeting, we add to the corresponding positions in the difference array: $d[l] = d[l] + 1$ for the start time, and $d[r] = d[r] - 1$ for the end time.\n\nNext, we calculate the prefix sum of the difference array and find the maximum value of the prefix sum, which represents the minimum number of meeting rooms required.\n\nThe time complexity is $O(n + m)$ and the space complexity is $O(m)$, where $n$ is the number of meetings and $m$ is the maximum end time.", "2": "If the meeting times span a large range, we can use a hash map instead of a difference array.\n\nFirst, we create a hash map $d$, where we add to the corresponding positions for each meeting's start time and end time: $d[l] = d[l] + 1$ for the start time, and $d[r] = d[r] - 1$ for the end time.\n\nThen, we sort the hash map by its keys, calculate the prefix sum of the hash map, and find the maximum value of the prefix sum, which represents the minimum number of meeting rooms required.\n\nThe time complexity is $O(n \\times \\log n)$ and the space complexity is $O(n)$, where $n$ is the number of meetings." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(m)" }, { "problem_id": 254, "explanations": { "1": "我们设计函数 $dfs(n, i)$,其中 $n$ 表示当前待分解的数,$i$ 表示当前分解的数的最大因子,函数的作用是将 $n$ 分解为若干个因子,其中每个因子都不小于 $i$,并将所有分解结果保存到 $ans$ 中。\n\n在函数 $dfs(n, i)$ 中,我们从 $i$ 开始枚举 $n$ 的因子 $j$,如果 $j$ 是 $n$ 的因子,那么我们将 $j$ 加入当前分解结果,然后继续分解 $n / j$,即调用函数 $dfs(n / j, j)$。\n\n时间复杂度 $O(\\sqrt{n})$。" }, "is_english": false, "time_complexity": "O(\\sqrt{n})", "space_complexity": null }, { "problem_id": 255, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 256, "explanations": { "1": "时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 表示房子的数量。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 257, "explanations": { "1": "我们可以使用深度优先搜索的方法遍历整棵二叉树,每一次我们将当前的节点添加到路径中。如果当前的节点是叶子节点,则我们将整个路径加入到答案中。否则我们继续递归遍历节点的孩子节点。最后当我们递归结束返回到当前节点时,我们需要将当前节点从路径中删除。\n\n时间复杂度 $O(n^2)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点数。" }, "is_english": false, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 258, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 259, "explanations": { "1": "Since the order of elements does not affect the result, we can sort the array first and then use the two-pointer method to solve this problem.\n\nFirst, we sort the array and then enumerate the first element $\\textit{nums}[i]$. Within the range $\\textit{nums}[i+1:n-1]$, we use two pointers pointing to $\\textit{nums}[j]$ and $\\textit{nums}[k]$, where $j$ is the next element of $\\textit{nums}[i]$ and $k$ is the last element of the array.\n\n- If $\\textit{nums}[i] + \\textit{nums}[j] + \\textit{nums}[k] < \\textit{target}$, then for any element $j \\lt k' \\leq k$, we have $\\textit{nums}[i] + \\textit{nums}[j] + \\textit{nums}[k'] < \\textit{target}$. There are $k - j$ such $k'$, and we add $k - j$ to the answer. Next, move $j$ one position to the right and continue to find the next $k$ that meets the condition until $j \\geq k$.\n- If $\\textit{nums}[i] + \\textit{nums}[j] + \\textit{nums}[k] \\geq \\textit{target}$, then for any element $j \\leq j' \\lt k$, it is impossible to make $\\textit{nums}[i] + \\textit{nums}[j'] + \\textit{nums}[k] < \\textit{target}$. Therefore, we move $k$ one position to the left and continue to find the next $k$ that meets the condition until $j \\geq k$.\n\nAfter enumerating all $i$, we get the number of triplets that meet the condition.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(\\log n)" }, { "problem_id": 260, "explanations": { "1": "The XOR operation has the following properties:\n\n- Any number XOR 0 is still the original number, i.e., $x \\oplus 0 = x$;\n- Any number XOR itself is 0, i.e., $x \\oplus x = 0$;\n\nSince all numbers in the array appear twice except for two numbers, we can perform XOR operation on all numbers in the array to get the XOR result of the two numbers that only appear once.\n\nSince these two numbers are not equal, there is at least one bit that is 1 in the XOR result. We can use the `lowbit` operation to find the lowest bit of 1 in the XOR result, and divide all numbers in the array into two groups based on whether this bit is 1 or not. This way, the two numbers that only appear once are separated into different groups.\n\nPerform XOR operation on each group separately to obtain the two numbers $a$ and $b$ that only appear once.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$.", "2": "" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 261, "explanations": { "1": "To determine whether it is a tree, the following two conditions must be met:\n\n1. The number of edges is equal to the number of nodes minus one;\n2. There is no cycle.\n\nWe can use a union-find set to determine whether there is a cycle. We traverse the edges, if two nodes are already in the same set, it means there is a cycle. Otherwise, we merge the two nodes into the same set. Then we decrease the number of connected components by one, and finally check whether the number of connected components is $1$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$, where $n$ is the number of nodes.", "2": "We can also use depth-first search to determine whether there is a cycle. We can use an array $vis$ to record the visited nodes. During the search, we first mark the node as visited, then traverse the nodes adjacent to this node. If the adjacent node has been visited, we skip it, otherwise we recursively visit the adjacent node. Finally, we check whether all nodes have been visited. If there are nodes that have not been visited, it means that it cannot form a tree, so we return `false`.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of nodes." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 262, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 263, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 264, "explanations": { "1": "初始时,将第一个丑数 $1$ 加入堆。每次取出堆顶元素 $x$,由于 $2x$, $3x$, $5x$ 也是丑数,因此将它们加入堆中。为了避免重复元素,可以用哈希表 $vis$ 去重。\n\n时间复杂度 $O(n \\times \\log n)$,空间复杂度 $O(n)$。", "2": "定义数组 $dp$,其中 $dp[i-1]$ 表示第 $i$ 个丑数,那么第 $n$ 个丑数就是 $dp[n - 1]$。最小的丑数是 $1$,所以 $dp[0]=1$。\n\n定义 $3$ 个指针 $p_2$, $p_3$ 和 $p_5$,表示下一个丑数是当前指针指向的丑数乘以对应的质因数。初始时,三个指针的值都指向 $0$。\n\n当 $i$ 在 $[1,2..n-1]$ 范围内,我们更新 $dp[i]=\\min(dp[p_2] \\times 2, dp[p_3] \\times 3, dp[p_5] \\times 5)$,然后分别比较 $dp[i]$ 与 $dp[p_2] \\times 2$, $dp[p_3] \\times 3$, $dp[p_5] \\times 5$ 是否相等,若是,则对应的指针加 $1$。\n\n最后返回 $dp[n - 1]$ 即可。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。" }, "is_english": false, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 265, "explanations": { "1": "定义 $f[i][j]$ 表示粉刷前 $i$ 个房子,且最后一个房子被粉刷成第 $j$ 种颜色的最小花费。答案为 $\\min_{0 \\leq j < k} f[n][j]$。\n\n对于 $f[i][j]$,可以从 $f[i - 1][j']$ 转移而来,其中 $j' \\neq j$。因此,可以得到状态转移方程:\n\n$$\nf[i][j] = \\min_{0 \\leq j' < k, j' \\neq j} f[i - 1][j'] + costs[i - 1][j]\n$$\n\n由于 $f[i][j]$ 只与 $f[i - 1][j']$ 有关,因此可以使用滚动数组优化空间复杂度。\n\n时间复杂度 $O(n \\times k^2)$,空间复杂度 $O(k)$。其中 $n$ 和 $k$ 分别为房子数量和颜色数量。" }, "is_english": false, "time_complexity": "O(n \\times k^2)", "space_complexity": "O(n \\times k^2)" }, { "problem_id": 266, "explanations": { "1": "If a string is a palindrome, at most one character can appear an odd number of times, while all other characters must appear an even number of times. Therefore, we only need to count the occurrences of each character and then check if this condition is satisfied.\n\nTime complexity is $O(n)$, and space complexity is $O(|\\Sigma|)$. Here, $n$ is the length of the string, and $|\\Sigma|$ is the size of the character set. In this problem, the character set consists of lowercase letters, so $|\\Sigma|=26$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 267, "explanations": { "1": "回文排列需要满足至多有一个字符出现奇数次数。若不满足条件,答案提前返回。\n\n找到出现奇数次的字符,作为中间字符(可以为空),分别向两边扩展,构造回文串。若串的长度与原串长度相等,将该串添加到答案中。\n\n时间复杂度 $O(n \\times \\frac{n}{2}!)$。其中 $n$ 为字符串 $s$ 的长度。" }, "is_english": false, "time_complexity": "O(n \\times \\frac{n}{2}!)", "space_complexity": null }, { "problem_id": 268, "explanations": { "1": "The XOR operation has the following properties:\n\n- Any number XOR 0 is still the original number, i.e., $x \\oplus 0 = x$;\n- Any number XOR itself is 0, i.e., $x \\oplus x = 0$;\n\nTherefore, we can traverse the array, perform XOR operation between each element and the numbers $[0,..n]$, and the final result will be the missing number.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$.", "2": "We can also solve this problem using mathematics. By calculating the sum of $[0,..n]$, subtracting the sum of all numbers in the array, we can obtain the missing number.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 269, "explanations": { "1": "用数组 $g$ 记录在火星字典中的字母先后关系,$g[i][j] = true$ 表示字母 $i + 'a'$ 在字母 $j + 'a'$ 的前面;用数组 $s$ 记录当前字典出现过的字母,$cnt$ 表示出现过的字母数。\n\n一个很简单的想法是遍历每一个单词,比较该单词和其后的所有单词,把所有的先后关系更新进数组 $g$,这样遍历时间复杂度为 $O(n^3)$;但是我们发现其实比较相邻的两个单词就可以了,比如 $a < b < c$ 则比较 $a < b$ 和 $b < c$, $a$ 和 $c$ 的关系便确定了。因此算法可以优化成比较相邻两个单词,时间复杂度为 $O(n²)$。\n\n出现矛盾的情况:\n\n- $g[i][j]$ = $g[j][i]$ = $true$;\n- 后一个单词是前一个单词的前缀;\n- 在拓扑排序后 $ans$ 的长度小于统计到的字母个数。\n\n拓扑排序:\n\n- 统计所有出现的字母入度;\n- 将所有入度为 $0$ 的字母加入队列;\n- 当队列不空,出队并更新其他字母的入度,入度为 $0$ 则入队,同时出队时将当前字母加入 $ans$ 的结尾;\n- 得到的便是字母的拓扑序,也就是火星字典的字母顺序。" }, "is_english": false, "time_complexity": "O(n^3)", "space_complexity": null }, { "problem_id": 270, "explanations": { "1": "We define a recursive function `dfs(node)`, which starts from the current node `node` and finds the node closest to the target value `target`. We can update the answer by comparing the absolute difference between the current node's value and the target value. If the target value is less than the current node's value, we recursively search the left subtree; otherwise, we recursively search the right subtree.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in the binary search tree.", "2": "We can rewrite the recursive function in an iterative form, using a loop to simulate the recursive process. We start from the root node and check whether the absolute difference between the current node's value and the target value is less than the current minimum difference. If it is, we update the answer. Then, based on the size relationship between the target value and the current node's value, we decide to move to the left subtree or the right subtree. The loop ends when we traverse to a null node.\n\nThe time complexity is $O(n)$, where $n$ is the number of nodes in the binary search tree. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 271, "explanations": { "1": "During encoding, we convert the length of the string into a fixed 4-digit string, add the string itself, and append it to the result string in sequence.\n\nDuring decoding, we first take the first four digits of the string to get the length, and then cut the following string according to the length. We cut it in sequence until we get the list of strings.\n\nThe time complexity is $O(n)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": null }, { "problem_id": 272, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 273, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 274, "explanations": { "1": "We can sort the array `citations` in descending order. Then we enumerate the value $h$ from large to small, if there is an $h$ value satisfying $citations[h-1] \\geq h$, it means that there are at least $h$ papers that have been cited at least $h$ times, just return $h$ directly. If we cannot find such an $h$ value, it means that all the papers have not been cited, return $0$.\n\nTime complexity $O(n \\times \\log n)$, space complexity $O(\\log n)$. Here $n$ is the length of the array `citations`.", "2": "We can use an array $cnt$ of length $n+1$, where $cnt[i]$ represents the number of papers with the reference count of $i$. We traverse the array `citations` and treat the papers with the reference count greater than $n$ as papers with a reference count of $n$. Then we use the reference count as the index and add $1$ to the corresponding element of $cnt$ for each paper. In this way, we have counted the number of papers for each reference count.\n\nThen we enumerate the value $h$ from large to small, and add the element value of $cnt$ with the index of $h$ to the variable $s$, where $s$ represents the number of papers with a reference count greater than or equal to $h$. If $s \\geq h$, it means that at least $h$ papers have been cited at least $h$ times, just return $h$ directly.\n\nTime complexity $O(n)$, space complexity $O(n)$. Here $n$ is the length of the array `citations`.", "3": "We notice that if there is a $h$ value that satisfies at least $h$ papers are cited at least $h$ times, then for any $h' 0$, we have the following state transition equations:\n\n$$\n\\begin{aligned}\nf[i] & = (f[i - 1] + g[i - 1]) \\times (k - 1) \\\\\ng[i] & = f[i - 1]\n\\end{aligned}\n$$\n\nThe final answer is $f[n - 1] + g[n - 1]$.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the number of fence posts.", "2": "We notice that $f[i]$ and $g[i]$ are only related to $f[i - 1]$ and $g[i - 1]$. Therefore, we can use two variables $f$ and $g$ to record the values of $f[i - 1]$ and $g[i - 1]$ respectively, thus optimizing the space complexity to $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 277, "explanations": { "1": "经过验证,若暴力遍历,调用 $O(n^2)$ 次 $knows$ 方法,会报 TLE 错误。因此,我们需要寻找更优的解法。\n\n要找出 $n$ 个人中的名人,题目给我们的关键信息是:1. 名人不认识其他所有人;2. 其他所有人都认识名人。\n\n那么,我们初始时假定名人 $ans=0$。然后在 $[1,n)$ 范围内遍历 $i$,若 $ans$ 认识 $i$,说明 $ans$ 不是我们要找的名人,此时我们可以直接将 $ans$ 更新为 $i$。\n\n为什么呢?我们来举个实际的例子。\n\n```bash\nans = 0\nfor i in [1,n) {\n\tif (ans knows i) {\n\t\tans = i\n\t}\n}\n\nans = 0\n\nans not knows 1\nans not knows 2\nans knows 3\nans = 3\n\nans not knows 4\nans not knows 5\nans not knows 6\nans = 6\n```\n\n这里 $ans$ 认识 $3$,说明 $ans$ 不是名人(即 $0$ 不是名人),那么名人会是 $1$ 或者 $2$ 吗?不会!因为若 $1$ 或者 $2$ 是名人,那么 $0$ 应该认识 $1$ 或者 $2$ 才对,与前面的例子冲突。因此,我们可以直接将 $ans$ 更新为 $i$。\n\n我们找出 $ans$ 之后,接下来再遍历一遍,判断 $ans$ 是否满足名人的条件。若不满足,返回 $-1$。\n\n否则遍历结束,返回 $ans$。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 278, "explanations": { "1": "We define the left boundary of the binary search as $l = 1$ and the right boundary as $r = n$.\n\nWhile $l < r$, we calculate the middle position $\\textit{mid} = \\left\\lfloor \\frac{l + r}{2} \\right\\rfloor$, then call the `isBadVersion(mid)` API. If it returns $\\textit{true}$, it means the first bad version is between $[l, \\textit{mid}]$, so we set $r = \\textit{mid}$; otherwise, the first bad version is between $[\\textit{mid} + 1, r]$, so we set $l = \\textit{mid} + 1$.\n\nFinally, we return $l$.\n\nThe time complexity is $O(\\log n)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 279, "explanations": { "1": "我们定义 $f[i][j]$ 表示使用数字 $1, 2, \\cdots, i$ 的完全平方数组成和为 $j$ 的最少数量。初始时 $f[0][0] = 0$,其余位置的值均为正无穷。\n\n我们可以枚举使用的最后一个数字的数量 $k$,那么:\n\n$$\nf[i][j] = \\min(f[i - 1][j], f[i - 1][j - i^2] + 1, \\cdots, f[i - 1][j - k \\times i^2] + k)\n$$\n\n其中 $i^2$ 表示最后一个数字 $i$ 的完全平方数。\n\n不妨令 $j = j - i^2$,那么有:\n\n$$\nf[i][j - i^2] = \\min(f[i - 1][j - i^2], f[i - 1][j - 2 \\times i^2] + 1, \\cdots, f[i - 1][j - k \\times i^2] + k - 1)\n$$\n\n将二式代入一式,我们可以得到以下状态转移方程:\n\n$$\nf[i][j] = \\min(f[i - 1][j], f[i][j - i^2] + 1)\n$$\n\n最后答案即为 $f[m][n]$。\n\n时间复杂度 $O(m \\times n)$,空间复杂度 $O(m \\times n)$。其中 $m$ 为 $sqrt(n)$ 的整数部分。\n\n注意到 $f[i][j]$ 只与 $f[i - 1][j]$ 和 $f[i][j - i^2]$ 有关,因此我们可以将二维数组优化为一维数组,空间复杂度降为 $O(n)$。\n\n相似题目:\n\n- [322. 零钱兑换](https://github.com/doocs/leetcode/blob/main/solution/0300-0399/0322.Coin%20Change/README.md)", "2": "" }, "is_english": false, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 280, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 281, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 282, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 283, "explanations": { "1": "We use a pointer $k$ to record the current position to insert, initially $k = 0$.\n\nThen we iterate through the array $\\textit{nums}$, and each time we encounter a non-zero number, we swap it with $\\textit{nums}[k]$ and increment $k$ by 1.\n\nThis way, we can ensure that the first $k$ elements of $\\textit{nums}$ are non-zero, and their relative order is the same as in the original array.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 284, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 285, "explanations": { "1": "The in-order traversal of a binary search tree is an ascending sequence, so we can use the binary search method.\n\nThe in-order successor node of a binary search tree node $p$ satisfies:\n\n1. The value of the in-order successor node is greater than the value of node $p$.\n2. The in-order successor is the node with the smallest value among all nodes greater than $p$.\n\nTherefore, for the current node $root$, if $root.val > p.val$, then $root$ could be the in-order successor of $p$. We record $root$ as $ans$ and then search the left subtree, i.e., $root = root.left$. If $root.val \\leq p.val$, then $root$ cannot be the in-order successor of $p$, and we search the right subtree, i.e., $root = root.right$.\n\nThe time complexity is $O(h)$, where $h$ is the height of the binary search tree. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(h)", "space_complexity": "O(1)" }, { "problem_id": 286, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 287, "explanations": { "1": "We can observe that if the number of elements in $[1,..x]$ is greater than $x$, then the duplicate number must be in $[1,..x]$, otherwise the duplicate number must be in $[x+1,..n]$.\n\nTherefore, we can use binary search to find $x$, and check whether the number of elements in $[1,..x]$ is greater than $x$ at each iteration. This way, we can determine which interval the duplicate number is in, and narrow down the search range until we find the duplicate number.\n\nThe time complexity is $O(n \\times \\log n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(1)" }, { "problem_id": 288, "explanations": { "1": "According to the problem description, we define a function $abbr(s)$, which calculates the abbreviation of the word $s$. If the length of the word $s$ is less than $3$, then its abbreviation is itself; otherwise, its abbreviation is its first letter + (its length - 2) + its last letter.\n\nNext, we define a hash table $d$, where the key is the abbreviation of the word, and the value is a set, the elements of which are all words abbreviated as that key. We traverse the given word dictionary, and for each word $s$ in the dictionary, we calculate its abbreviation $abbr(s)$, and add $s$ to $d[abbr(s)]$.\n\nWhen judging whether the word $word$ meets the requirements of the problem, we calculate its abbreviation $abbr(word)$. If $abbr(word)$ is not in the hash table $d$, then $word$ meets the requirements of the problem; otherwise, we judge whether there is only one element in $d[abbr(word)]$. If there is only one element in $d[abbr(word)]$ and that element is $word$, then $word$ meets the requirements of the problem.\n\nIn terms of time complexity, the time complexity of initializing the hash table is $O(n)$, where $n$ is the length of the word dictionary; the time complexity of judging whether a word meets the requirements of the problem is $O(1)$. In terms of space complexity, the space complexity of the hash table is $O(n)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 289, "explanations": { "1": "Let's define two new states. State $2$ indicates that the living cell becomes dead in the next state, and state $-1$ indicates that the dead cell becomes alive in the next state. Therefore, for the current grid we are traversing, if the grid is greater than $0$, it means that the current grid is a living cell, otherwise it is a dead cell.\n\nSo we can traverse the entire board, for each grid, count the number of living neighbors around the grid, and use the variable $live$ to represent it. If the current grid is a living cell, then when $live \\lt 2$ or $live \\gt 3$, the next state of the current grid is a dead cell, that is, state $2$; if the current grid is a dead cell, then when $live = 3$, the next state of the current grid is an active cell, that is, state $-1$.\n\nFinally, we traverse the board again, and update the grid with state $2$ to a dead cell, and update the grid with state $-1$ to an active cell.\n\nThe time complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns of the board, respectively. We need to traverse the entire board. And the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(1)" }, { "problem_id": 290, "explanations": { "1": "First, we split the string $s$ into a word array $ws$ with spaces. If the length of $pattern$ and $ws$ is not equal, return `false` directly. Otherwise, we use two hash tables $d_1$ and $d_2$ to record the correspondence between each character and word in $pattern$ and $ws$.\n\nThen, we traverse $pattern$ and $ws$. For each character $a$ and word $b$, if there is a mapping for $a$ in $d_1$, and the mapped word is not $b$, or there is a mapping for $b$ in $d_2$, and the mapped character is not $a$, return `false`. Otherwise, we add the mapping of $a$ and $b$ to $d_1$ and $d_2$ respectively.\n\nAfter the traversal, return `true`.\n\nThe time complexity is $O(m + n)$ and the space complexity is $O(m + n)$. Here $m$ and $n$ are the length of $pattern$ and string $s$.", "2": "" }, "is_english": true, "time_complexity": "O(m + n)", "space_complexity": "O(m + n)" }, { "problem_id": 291, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 292, "explanations": { "1": "The first player who gets a multiple of $4$ (i.e., $n$ can be divided by $4$) will lose the game.\n\nProof:\n\n1. When $n \\lt 4$, the first player can directly take all the stones, so the first player will win the game.\n1. When $n = 4$, no matter whether the first player chooses $1, 2, 3$, the second player can always choose the remaining number, so the first player will lose the game.\n1. When $4 \\lt n \\lt 8$, i.e., $n = 5, 6, 7$, the first player can correspondingly reduce the number to $4$, then the \"death number\" $4$ is given to the second player, and the second player will lose the game.\n1. When $n = 8$, no matter whether the first player chooses $1, 2, 3$, it will leave a number between $4 \\lt n \\lt 8$ to the second player, so the first player will lose the game.\n1. ...\n1. By induction, when a player gets the number $n$, and $n$ can be divided by $4$, he will lose the game, otherwise, he will win the game.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 293, "explanations": { "1": "We traverse the string. If the current character and the next character are both `+`, we change these two characters to `-`, add the result to the result array, and then change these two characters back to `+`.\n\nAfter the traversal ends, we return the result array.\n\nThe time complexity is $O(n^2)$, where $n$ is the length of the string. Ignoring the space complexity of the result array, the space complexity is $O(n)$ or $O(1)$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 294, "explanations": { "1": "", "2": "Sprague-Grundy 定理为游戏的每一个状态定义了一个 Sprague-Grundy 数(简称 SG 数),游戏状态的组合相当于 SG 数的异或运算。\n\nSprague-Grundy 定理的完整表述如下:\n\n若一个游戏满足以下条件:\n\n1. 双人、回合制\n1. 信息完全公开\n1. 无随机因素\n1. 必然在有限步内结束,且每步的走法数有限\n1. 没有平局\n1. 双方可采取的行动及胜利目标都相同\n1. 这个胜利目标是自己亲手达成终局状态,或者说走最后一步者为胜(normal play)\n\n则游戏中的每个状态可以按如下规则赋予一个非负整数,称为 Sprague-Grundy 数,即 $SG(A)=mex\\{SG(B)|A->B\\}$。(式中 $A$, $B$ 代表状态,代表 $A$ 状态经一步行动可以到达 $B$ 状态,而 $mex$ 表示一个集合所不包含的最小非负整数)\n\nSG 数有如下性质:\n\n1. SG 数为 0 的状态,后手必胜;SG 数为正的状态,先手必胜;\n1. 若一个母状态可以拆分成多个相互独立的子状态,则母状态的 SG 数等于各个子状态的 SG 数的异或。\n\n参考资料:[Sprague-Grundy 定理是怎么想出来的](https://zhuanlan.zhihu.com/p/20611132)\n\n时间复杂度 $O(n^2)$。" }, "is_english": false, "time_complexity": "O(n^2)", "space_complexity": null }, { "problem_id": 295, "explanations": { "1": "We can use two heaps to maintain all the elements, a min heap $\\textit{minQ}$ and a max heap $\\textit{maxQ}$, where the min heap $\\textit{minQ}$ stores the larger half, and the max heap $\\textit{maxQ}$ stores the smaller half.\n\nWhen calling the `addNum` method, we first add the element to the max heap $\\textit{maxQ}$, then pop the top element of $\\textit{maxQ}$ and add it to the min heap $\\textit{minQ}$. If at this time the size difference between $\\textit{minQ}$ and $\\textit{maxQ}$ is greater than $1$, we pop the top element of $\\textit{minQ}$ and add it to $\\textit{maxQ}$. The time complexity is $O(\\log n)$.\n\nWhen calling the `findMedian` method, if the size of $\\textit{minQ}$ is equal to the size of $\\textit{maxQ}$, it means the total number of elements is even, and we can return the average value of the top elements of $\\textit{minQ}$ and $\\textit{maxQ}$; otherwise, we return the top element of $\\textit{minQ}$. The time complexity is $O(1)$.\n\nThe space complexity is $O(n)$, where $n$ is the number of elements." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(n)" }, { "problem_id": 296, "explanations": { "1": "对于每一行,我们可以将所有的 $1$ 的下标排序,然后取中位数 $i$ 作为碰头地点的横坐标。\n\n对于每一列,我们可以将所有的 $1$ 的下标排序,然后取中位数 $i$ 作为碰头地点的纵坐标。\n\n最后,我们计算所有 $1$ 到碰头地点 $(i, j)$ 的曼哈顿距离之和即可。\n\n时间复杂度 $O(m\\times n\\times \\log(m\\times n))$。最多有 $m\\times n$ 个 $1$,排序的时间复杂度为 $\\log(m\\times n)$。\n\n相似题目:\n\n- [462. 最少移动次数使数组元素相等 II](https://github.com/doocs/leetcode/blob/main/solution/0400-0499/0462.Minimum%20Moves%20to%20Equal%20Array%20Elements%20II/README.md)\n- [2448. 使数组相等的最小开销](https://github.com/doocs/leetcode/blob/main/solution/2400-2499/2448.Minimum%20Cost%20to%20Make%20Array%20Equal/README.md)" }, "is_english": false, "time_complexity": "O(m\\times n\\times \\log(m\\times n))", "space_complexity": null }, { "problem_id": 297, "explanations": { "1": "We can use level order traversal to serialize the binary tree. Starting from the root node, we add the nodes of the binary tree to the queue in the order from top to bottom, from left to right. Then we dequeue the nodes in the queue one by one. If the node is not null, we add its value to the serialized string; otherwise, we add a special character `#`. Finally, we return the serialized string.\n\nDuring deserialization, we split the serialized string by the delimiter to get a string array, and then add the elements in the string array to the queue in order. The elements in the queue are the nodes of the binary tree. We dequeue the elements from the queue one by one. If the element is not `#`, we convert it to an integer and use it as the value of the node, and then add the node to the queue; otherwise, we set it to `null`. Finally, we return the root node.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 298, "explanations": { "1": "我们设计一个函数 $dfs(root)$,表示以 $root$ 为连续序列的第一个节点的最长连续序列路径长度。\n\n函数 $dfs(root)$ 的执行过程如下:\n\n如果 $root$ 为空,那么返回 $0$。\n\n否则,我们递归计算 $root$ 的左右子节点,分别得到 $l$ 和 $r$,如果 $root$ 的左子节点和 $root$ 连续,那么 $l$ 的值加 $1$,否则置 $l$ 为 $1$;如果 $root$ 的右子节点和 $root$ 连续,那么 $r$ 的值加 $1$,否则置 $r$ 为 $1$。\n\n然后我们更新答案为 $ans = \\max(ans, l, r)$,并返回 $\\max(l, r)$。\n\n最后,我们调用 $dfs(root)$,返回答案 $ans$。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点数。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 299, "explanations": { "1": "We create two counters, $cnt1$ and $cnt2$, to count the occurrence of each digit in the secret number and the friend's guess respectively. At the same time, we create a variable $x$ to count the number of bulls.\n\nThen we iterate through the secret number and the friend's guess. If the current digit is the same, we increment $x$ by one. Otherwise, we increment the count of the current digit in the secret number and the friend's guess respectively.\n\nFinally, we iterate through each digit in $cnt1$, take the minimum count of the current digit in $cnt1$ and $cnt2$, and add this minimum value to the variable $y$.\n\nIn the end, we return the values of $x$ and $y$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the secret number and the friend's guess. The space complexity is $O(|\\Sigma|)$, where $|\\Sigma|$ is the size of the character set. In this problem, the character set is digits, so $|\\Sigma| = 10$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 300, "explanations": { "1": "我们定义 $f[i]$ 表示以 $nums[i]$ 结尾的最长递增子序列的长度,初始时 $f[i] = 1$,答案为 $f[i]$ 的最大值。\n\n对于 $f[i]$,我们需要枚举 $0 \\le j \\lt i$,如果 $nums[j] \\lt nums[i]$,则 $f[i] = \\max(f[i], f[j] + 1)$。\n\n最后的答案即为 $f[i]$ 的最大值。\n\n时间复杂度 $O(n^2)$,空间复杂度 $O(n)$。其中 $n$ 为数组长度。", "2": "我们将数组中的元素离散化,然后使用树状数组维护不大于某个元素的最长递增子序列的长度。\n\n遍历数组中的每个元素 $x$,将其离散化,然后在树状数组中查找不大于 $x-1$ 的最长递增子序列的长度 $t$,则 $x$ 的最长递增子序列的长度为 $t+1$,更新答案,并且更新树状数组中 $x$ 的最长递增子序列的长度。\n\n遍历完数组中的所有元素,即可得到答案。\n\n时间复杂度 $O(n \\times \\log n)$,空间复杂度 $O(n)$。其中 $n$ 为数组长度。" }, "is_english": false, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 301, "explanations": { "1": "我们首先处理得到字符串 $s$ 待删除的左、右括号的最小数量,分别记为 $l$ 和 $r$。\n\n然后我们设计一个递归函数 `dfs(i, l, r, lcnt, rcnt, t)`,其中:\n\n- `i` 表示当前处理到字符串 $s$ 的第 $i$ 个字符;\n- `l` 和 `r` 分别表示剩余待删除的左、右括号的数量;\n- `t` 表示当前得到的字符串;\n- `lcnt` 和 `rcnt` 分别表示当前得到的字符串中左、右括号的数量。\n\n递归函数的逻辑如下:\n\n- 如果 `i` 等于字符串 $s$ 的长度,且 `l` 和 `r` 都等于 $0$,则将 `t` 加入答案数组中;\n- 如果剩余的待处理字符数 $n-i$ 小于剩余待删除的左右括号数量 $l+r$,或者当前得到的字符串中的左括号数量小于右括号数量,直接返回;\n- 如果当前字符是左括号,我们可以选择删除或者保留,如果删除,需要满足 $l \\gt 0$,然后递归调用 `dfs(i+1, l-1, r, lcnt, rcnt, t)`;\n- 如果当前字符是右括号,我们可以选择删除或者保留,如果删除,需要满足 $r \\gt 0$,然后递归调用 `dfs(i+1, l, r-1, lcnt, rcnt, t)`;\n- 如果选择保留当前字符,我们需要判断当前字符是左括号、右括号还是字母。如果是左括号,我们需要更新 `lcnt`,如果是右括号,我们需要更新 `rcnt`,然后递归调用 `dfs(i+1, l, r, lcnt, rcnt, t+s[i])`。\n\n我们调用 `dfs(0, l, r, 0, 0, \"\")`,搜索所有可能的字符串。\n\n最后返回去重后的答案数组即可。\n\n时间复杂度 $O(n\\times 2^n)$,空间复杂度 $O(n)$。长度为 $n$ 的字符串有 $2^n$ 种可能的删除方式,每种删除方式需要 $O(n)$ 的时间复制字符串。因此总时间复杂度为 $O(n\\times 2^n)$。" }, "is_english": false, "time_complexity": "O(n\\times 2^n)", "space_complexity": "O(n)" }, { "problem_id": 302, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 303, "explanations": { "1": "We create a prefix sum array $s$ of length $n + 1$, where $s[i]$ represents the prefix sum of the first $i$ elements, that is, $s[i] = \\sum_{j=0}^{i-1} nums[j]$. Therefore, the sum of the elements between the indices $[left, right]$ can be expressed as $s[right + 1] - s[left]$.\n\nThe time complexity for initializing the prefix sum array $s$ is $O(n)$, and the time complexity for querying is $O(1)$. The space complexity is $O(n)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 304, "explanations": { "1": "We use $s[i + 1][j + 1]$ to represent the sum of all elements in the upper left part of the $i$th row and $j$th column, where indices $i$ and $j$ both start from $0$. We can get the following prefix sum formula:\n\n$$\ns[i + 1][j + 1] = s[i + 1][j] + s[i][j + 1] - s[i][j] + nums[i][j]\n$$\n\nThen, the sum of the elements of the rectangle with $(x_1, y_1)$ and $(x_2, y_2)$ as the upper left corner and lower right corner respectively is:\n\n$$\ns[x_2 + 1][y_2 + 1] - s[x_2 + 1][y_1] - s[x_1][y_2 + 1] + s[x_1][y_1]\n$$\n\nIn the initialization method, we preprocess the prefix sum array $s$, and in the query method, we directly return the result of the above formula.\n\nThe time complexity for initializing is $O(m \\times n)$, and the time complexity for querying is $O(1)$. The space complexity is $O(m \\times n)$." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 305, "explanations": { "1": "We use a two-dimensional array $grid$ to represent a map, where $0$ and $1$ represent water and land respectively. Initially, all cells in $grid$ are water cells (i.e., all cells are $0$), and we use a variable $cnt$ to record the number of islands. The connectivity between islands can be maintained by a union-find set $uf$.\n\nNext, we traverse each position $(i, j)$ in the array $positions$. If $grid[i][j]$ is $1$, it means that this position is already land, and we directly add $cnt$ to the answer; otherwise, we change the value of $grid[i][j]$ to $1$, and increase the value of $cnt$ by $1$. Then, we traverse the four directions of up, down, left, and right of this position. If a certain direction is $1$, and this position does not belong to the same connected component as $(i, j)$, then we merge this position with $(i, j)$, and decrease the value of $cnt$ by $1$. After traversing the four directions of up, down, left, and right of this position, we add $cnt$ to the answer.\n\nThe time complexity is $O(k \\times \\alpha(m \\times n))$ or $O(k \\times \\log(m \\times n))$, where $k$ is the length of $positions$, and $\\alpha$ is the inverse function of the Ackermann function. In this problem, $\\alpha(m \\times n)$ can be considered as a very small constant." }, "is_english": true, "time_complexity": "O(k \\times \\alpha(m \\times n))", "space_complexity": null }, { "problem_id": 306, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 307, "explanations": { "1": "树状数组,也称作“二叉索引树”(Binary Indexed Tree)或 Fenwick 树。 它可以高效地实现如下两个操作:\n\n1. **单点更新** $update(x, delta)$: 把序列 $x$ 位置的数加上一个值 $delta$;\n1. **前缀和查询** $query(x)$:查询序列 $[1,...x]$ 区间的区间和,即位置 $x$ 的前缀和。\n\n这两个操作的时间复杂度均为 $O(\\log n)$。\n\n树状数组最基本的功能就是求比某点 $x$ 小的点的个数(这里的比较是抽象的概念,可以是数的大小、坐标的大小、质量的大小等等)。\n\n对于本题,我们在构造函数中,先创建一个树状数组,然后遍历数组中每个元素的下标 $i$(从 $1$ 开始)和对应的值 $v$,调用 $update(i, v)$,即可完成树状数组的初始化。时间复杂度为 $O(n \\log n)$。\n\n对于 $sumRange(left, right)$,我们可以通过 $query(right + 1) - query(left)$ 得到区间和。时间复杂度为 $O(\\log n)$。\n\n对于 $update(index, val)$,我们可以先通过 $sumRange(index, index)$ 得到原来的值 $prev$,然后调用 $update(index, val - prev)$,即可完成更新。时间复杂度为 $O(\\log n)$。\n\n空间复杂度为 $O(n)$。", "2": "线段树将整个区间分割为多个不连续的子区间,子区间的数量不超过 $\\log(width)$。更新某个元素的值,只需要更新 $\\log(width)$ 个区间,并且这些区间都包含在一个包含该元素的大区间内。\n\n- 线段树的每个节点代表一个区间;\n- 线段树具有唯一的根节点,代表的区间是整个统计范围,如 $[1, N]$;\n- 线段树的每个叶子节点代表一个长度为 $1$ 的元区间 $[x, x]$;\n- 对于每个内部节点 $[l, r]$,它的左儿子是 $[l, mid]$,右儿子是 $[mid + 1, r]$, 其中 $mid = \\lfloor \\frac{l + r}{2} \\rfloor$(即向下取整)。\n\n对于本题,构造函数的时间复杂度为 $O(n \\log n)$,其他操作的时间复杂度为 $O(\\log n)$。空间复杂度为 $O(n)$。" }, "is_english": false, "time_complexity": "O(\\log n)", "space_complexity": "O(n)" }, { "problem_id": 308, "explanations": { "1": "树状数组,也称作“二叉索引树”(Binary Indexed Tree)或 Fenwick 树。 它可以高效地实现如下两个操作:\n\n1. **单点更新** `update(x, delta)`: 把序列 x 位置的数加上一个值 delta;\n1. **前缀和查询** `query(x)`:查询序列 `[1,...x]` 区间的区间和,即位置 x 的前缀和。\n\n这两个操作的时间复杂度均为 $O(\\log n)$。\n\n对于本题,可以构建二维树状数组。", "2": "线段树将整个区间分割为多个不连续的子区间,子区间的数量不超过 `log(width)`。更新某个元素的值,只需要更新 `log(width)` 个区间,并且这些区间都包含在一个包含该元素的大区间内。\n\n- 线段树的每个节点代表一个区间;\n- 线段树具有唯一的根节点,代表的区间是整个统计范围,如 `[1, N]`;\n- 线段树的每个叶子节点代表一个长度为 1 的元区间 `[x, x]`;\n- 对于每个内部节点 `[l, r]`,它的左儿子是 `[l, mid]`,右儿子是 `[mid + 1, r]`, 其中 `mid = ⌊(l + r) / 2⌋` (即向下取整)。" }, "is_english": false, "time_complexity": "O(\\log n)", "space_complexity": null }, { "problem_id": 309, "explanations": { "1": "We design a function $dfs(i, j)$, which represents the maximum profit that can be obtained starting from the $i$th day with state $j$. The values of $j$ are $0$ and $1$, respectively representing currently not holding a stock and holding a stock. The answer is $dfs(0, 0)$.\n\nThe execution logic of the function $dfs(i, j)$ is as follows:\n\nIf $i \\geq n$, it means that there are no more stocks to trade, so return $0$;\n\nOtherwise, we can choose not to trade, then $dfs(i, j) = dfs(i + 1, j)$. We can also trade stocks. If $j > 0$, it means that we currently hold a stock and can sell it, then $dfs(i, j) = prices[i] + dfs(i + 2, 0)$. If $j = 0$, it means that we currently do not hold a stock and can buy, then $dfs(i, j) = -prices[i] + dfs(i + 1, 1)$. Take the maximum value as the return value of the function $dfs(i, j)$.\n\nThe answer is $dfs(0, 0)$.\n\nTo avoid repeated calculations, we use the method of memoization search, and use an array $f$ to record the return value of $dfs(i, j)$. If $f[i][j]$ is not $-1$, it means that it has been calculated, and we can directly return $f[i][j]$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $prices$.", "2": "We can also use dynamic programming to solve this problem.\n\nWe define $f[i][j]$ to represent the maximum profit that can be obtained on the $i$th day with state $j$. The values of $j$ are $0$ and $1$, respectively representing currently not holding a stock and holding a stock. Initially, $f[0][0] = 0$, $f[0][1] = -prices[0]$.\n\nWhen $i \\geq 1$, if we currently do not hold a stock, then $f[i][0]$ can be obtained by transitioning from $f[i - 1][0]$ and $f[i - 1][1] + prices[i]$, i.e., $f[i][0] = \\max(f[i - 1][0], f[i - 1][1] + prices[i])$. If we currently hold a stock, then $f[i][1]$ can be obtained by transitioning from $f[i - 1][1]$ and $f[i - 2][0] - prices[i]$, i.e., $f[i][1] = \\max(f[i - 1][1], f[i - 2][0] - prices[i])$. The final answer is $f[n - 1][0]$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $prices$.\n\nWe notice that the transition of state $f[i][]$ is only related to $f[i - 1][]$ and $f[i - 2][0]$, so we can use three variables $f$, $f_0$, $f_1$ to replace the array $f$, optimizing the space complexity to $O(1)$.", "3": "" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 310, "explanations": { "1": "If the tree only has one node, then this node is the root of the minimum height tree. We can directly return this node.\n\nIf the tree has multiple nodes, there must be leaf nodes. A leaf node is a node that only has one adjacent node. We can use topological sorting to peel off the leaf nodes from the outside to the inside. When we reach the last layer, the remaining nodes are the root nodes of the minimum height tree.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the number of nodes." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 311, "explanations": { "1": "We can directly calculate each element in the result matrix according to the definition of matrix multiplication.\n\nThe time complexity is $O(m \\times n \\times k)$, and the space complexity is $O(m \\times n)$. Where $m$ and $n$ are the number of rows of matrix $mat1$ and the number of columns of matrix $mat2$ respectively, and $k$ is the number of columns of matrix $mat1$ or the number of rows of matrix $mat2$.", "2": "We can preprocess the sparse representation of the two matrices, i.e., $g1[i]$ represents the column index and value of all non-zero elements in the $i$th row of matrix $mat1$, and $g2[i]$ represents the column index and value of all non-zero elements in the $i$th row of matrix $mat2$.\n\nNext, we traverse each row $i$, traverse each element $(k, x)$ in $g1[i]$, traverse each element $(j, y)$ in $g2[k]$, then $mat1[i][k] \\times mat2[k][j]$ will correspond to $ans[i][j]$ in the result matrix, and we can accumulate all the results.\n\nThe time complexity is $O(m \\times n \\times k)$, and the space complexity is $O(m \\times n)$. Where $m$ and $n$ are the number of rows of matrix $mat1$ and the number of columns of matrix $mat2$ respectively, and $k$ is the number of columns of matrix $mat1$ or the number of rows of matrix $mat2$." }, "is_english": true, "time_complexity": "O(m \\times n \\times k)", "space_complexity": "O(m \\times n)" }, { "problem_id": 312, "explanations": { "1": "Let's denote the length of the array `nums` as $n$. According to the problem description, we can add a $1$ to both ends of the array `nums`, denoted as `arr`.\n\nThen, we define $f[i][j]$ as the maximum number of coins we can get by bursting all the balloons in the interval $[i, j]$. Therefore, the answer is $f[0][n+1]$.\n\nFor $f[i][j]$, we enumerate all positions $k$ in the interval $[i, j]$. Suppose $k$ is the last balloon to burst, then we can get the following state transition equation:\n\n$$\nf[i][j] = \\max(f[i][j], f[i][k] + f[k][j] + arr[i] \\times arr[k] \\times arr[j])\n$$\n\nIn implementation, since the state transition equation of $f[i][j]$ involves $f[i][k]$ and $f[k][j]$, where $i < k < j$, we need to traverse $i$ from large to small and $j$ from small to large. This ensures that when calculating $f[i][j]$, $f[i][k]$ and $f[k][j]$ have already been calculated.\n\nFinally, we return $f[0][n+1]$.\n\nThe time complexity is $O(n^3)$, and the space complexity is $O(n^2)$. Where $n$ is the length of the array `nums`." }, "is_english": true, "time_complexity": "O(n^3)", "space_complexity": "O(n^2)" }, { "problem_id": 313, "explanations": { "1": "We use a priority queue (min heap) to maintain all possible super ugly numbers, initially putting $1$ into the queue.\n\nEach time we take the smallest super ugly number $x$ from the queue, multiply $x$ by each number in the array `primes`, and put the product into the queue. Repeat the above operation $n$ times to get the $n$th super ugly number.\n\nSince the problem guarantees that the $n$th super ugly number is within the range of a 32-bit signed integer, before we put the product into the queue, we can first check whether the product exceeds $2^{31} - 1$. If it does, there is no need to put the product into the queue. In addition, the Euler sieve can be used for optimization.\n\nThe time complexity is $O(n \\times m \\times \\log (n \\times m))$, and the space complexity is $O(n \\times m)$. Where $m$ and $n$ are the length of the array `primes` and the given integer $n$ respectively.", "2": "" }, "is_english": true, "time_complexity": "O(n \\times m \\times \\log (n \\times m))", "space_complexity": "O(n \\times m)" }, { "problem_id": 314, "explanations": { "1": "DFS traverses the binary tree, recording the value, depth, and horizontal offset of each node. Then sort all nodes by horizontal offset from small to large, then by depth from small to large, and finally group by horizontal offset.\n\nThe time complexity is $O(n\\log \\log n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in the binary tree.", "2": "A better approach to this problem should be BFS, traversing from top to bottom level by level.\n\nThe time complexity is $O(n\\log n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n\\log \\log n)", "space_complexity": "O(n)" }, { "problem_id": 315, "explanations": { "1": "树状数组,也称作“二叉索引树”(Binary Indexed Tree)或 Fenwick 树。 它可以高效地实现如下两个操作:\n\n1. **单点更新** `update(x, delta)`: 把序列 x 位置的数加上一个值 delta;\n1. **前缀和查询** `query(x)`:查询序列 `[1,...x]` 区间的区间和,即位置 x 的前缀和。\n\n这两个操作的时间复杂度均为 $O(\\log n)$。\n\n树状数组最基本的功能就是求比某点 x 小的点的个数(这里的比较是抽象的概念,可以是数的大小、坐标的大小、质量的大小等等)。\n\n比如给定数组 `a[5] = {2, 5, 3, 4, 1}`,求 `b[i] = 位置 i 左边小于等于 a[i] 的数的个数`。对于此例,`b[5] = {0, 1, 1, 2, 0}`。\n\n解决方案是直接遍历数组,每个位置先求出 `query(a[i])`,然后再修改树状数组 `update(a[i], 1)` 即可。当数的范围比较大时,需要进行离散化,即先进行去重并排序,然后对每个数字进行编号。", "2": "线段树将整个区间分割为多个不连续的子区间,子区间的数量不超过 `log(width)`。更新某个元素的值,只需要更新 `log(width)` 个区间,并且这些区间都包含在一个包含该元素的大区间内。\n\n- 线段树的每个节点代表一个区间;\n- 线段树具有唯一的根节点,代表的区间是整个统计范围,如 `[1, N]`;\n- 线段树的每个叶子节点代表一个长度为 1 的元区间 `[x, x]`;\n- 对于每个内部节点 `[l, r]`,它的左儿子是 `[l, mid]`,右儿子是 `[mid + 1, r]`, 其中 `mid = ⌊(l + r) / 2⌋` (即向下取整)。" }, "is_english": false, "time_complexity": "O(\\log n)", "space_complexity": null }, { "problem_id": 316, "explanations": { "1": "We use an array `last` to record the last occurrence of each character, a stack to save the result string, and an array `vis` or an integer variable `mask` to record whether the current character is in the stack.\n\nTraverse the string $s$, for each character $c$, if $c$ is not in the stack, we need to check whether the top element of the stack is greater than $c$. If it is greater than $c$ and the top element of the stack will appear later, we pop the top element of the stack and push $c$ into the stack.\n\nFinally, concatenate the elements in the stack into a string and return it as the result.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string $s$.", "2": "" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 317, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 318, "explanations": { "1": "The problem requires us to find two strings without common letters, so that their length product is maximized. We can represent each string with a binary number $mask[i]$, where each bit of this binary number indicates whether the string contains a certain letter. If two strings do not have common letters, then the bitwise AND result of the two binary numbers corresponding to these strings is $0$, that is, $mask[i] \\& mask[j] = 0$.\n\nWe traverse each string. For the current string $words[i]$ we are traversing, we first calculate the corresponding binary number $mask[i]$, and then traverse all strings $words[j]$ where $j \\in [0, i)$. We check whether $mask[i] \\& mask[j] = 0$ holds. If it holds, we update the answer to $\\max(ans, |words[i]| \\times |words[j]|)$.\n\nAfter the traversal, we return the answer.\n\nThe time complexity is $O(n^2 + L)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string array $words$, and $L$ is the sum of the lengths of all strings in the string array.", "2": "" }, "is_english": true, "time_complexity": "O(n^2 + L)", "space_complexity": "O(n)" }, { "problem_id": 319, "explanations": { "1": "We can number the $n$ bulbs as $1, 2, 3, \\cdots, n$. For the $i$-th bulb, it will be operated in the $d$-th round if and only if $d$ is a factor of $i$.\n\nFor a number $i$, the number of its factors is finite. If the number of factors is odd, the final state is on; otherwise, it is off.\n\nTherefore, we only need to find the number of numbers from $1$ to $n$ with an odd number of factors.\n\nFor a number $i$, if it has a factor $d$, then it must have a factor $i/d$. Therefore, numbers with an odd number of factors must be perfect squares.\n\nFor example, the factors of the number $12$ are $1, 2, 3, 4, 6, 12$, and the number of factors is $6$, which is even. For the perfect square number $16$, the factors are $1, 2, 4, 8, 16$, and the number of factors is $5$, which is odd.\n\nTherefore, we only need to find how many perfect squares there are from $1$ to $n$, which is $\\lfloor \\sqrt{n} \\rfloor$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 320, "explanations": { "1": "We design a function $dfs(i)$, which returns all possible abbreviations for the string $word[i:]$.\n\nThe execution logic of the function $dfs(i)$ is as follows:\n\nIf $i \\geq n$, it means that the string $word$ has been processed, and we directly return a list composed of an empty string.\n\nOtherwise, we can choose to keep $word[i]$, and then add $word[i]$ to the front of each string in the list returned by $dfs(i + 1)$, and add the obtained result to the answer.\n\nWe can also choose to delete $word[i]$ and some characters after it. Suppose we delete $word[i..j)$, then the $j$ th character is not deleted, and then add $j - i$ to the front of each string in the list returned by $dfs(j + 1)$, and add the obtained result to the answer.\n\nFinally, we call $dfs(0)$ in the main function.\n\nThe time complexity is $O(n \\times 2^n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string $word$.", "2": "Since the length of the string $word$ does not exceed $15$, we can use the method of binary enumeration to enumerate all abbreviations. We use a binary number $i$ of length $n$ to represent an abbreviation, where $0$ represents keeping the corresponding character, and $1$ represents deleting the corresponding character. We enumerate all $i$ in the range of $[0, 2^n)$, convert it into the corresponding abbreviation, and add it to the answer list.\n\nThe time complexity is $O(n \\times 2^n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string $word$." }, "is_english": true, "time_complexity": "O(n \\times 2^n)", "space_complexity": "O(n)" }, { "problem_id": 321, "explanations": { "1": "我们可以枚举从数组 $nums1$ 中取出 $x$ 个数,那么从数组 $nums2$ 中就需要取出 $k-x$ 个数。其中 $x \\in [max(0, k-n), min(k, m)]$。\n\n对于每一个 $x$,我们可以使用单调栈求出数组 $nums1$ 中长度为 $x$ 的最大子序列,以及数组 $nums2$ 中长度为 $k-x$ 的最大子序列。然后将这两个子序列合并得到长度为 $k$ 的最大子序列。\n\n最后,我们比较所有的长度为 $k$ 的最大子序列,找出最大的序列即可。\n\n时间复杂度 $O(k \\times (m + n + k^2))$,空间复杂度 $O(k)$。其中 $m$ 和 $n$ 分别是数组 $nums1$ 和 $nums2$ 的长度。" }, "is_english": false, "time_complexity": "O(k \\times (m + n + k^2))", "space_complexity": "O(k)" }, { "problem_id": 322, "explanations": { "1": "We define $f[i][j]$ as the minimum number of coins needed to make up the amount $j$ using the first $i$ types of coins. Initially, $f[0][0] = 0$, and the values of other positions are all positive infinity.\n\nWe can enumerate the quantity $k$ of the last coin used, then we have:\n\n$$\nf[i][j] = \\min(f[i - 1][j], f[i - 1][j - x] + 1, \\cdots, f[i - 1][j - k \\times x] + k)\n$$\n\nwhere $x$ represents the face value of the $i$-th type of coin.\n\nLet $j = j - x$, then we have:\n\n$$\nf[i][j - x] = \\min(f[i - 1][j - x], f[i - 1][j - 2 \\times x] + 1, \\cdots, f[i - 1][j - k \\times x] + k - 1)\n$$\n\nSubstituting the second equation into the first one, we can get the following state transition equation:\n\n$$\nf[i][j] = \\min(f[i - 1][j], f[i][j - x] + 1)\n$$\n\nThe final answer is $f[m][n]$.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Where $m$ and $n$ are the number of types of coins and the total amount, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 323, "explanations": { "1": "First, we construct an adjacency list $g$ based on the given edges, where $g[i]$ represents all neighbor nodes of node $i$.\n\nThen we traverse all nodes. For each node, we use DFS to traverse all its adjacent nodes and mark them as visited until all its adjacent nodes have been visited. In this way, we have found a connected component, and the answer is incremented by one. Then we continue to traverse the next unvisited node until all nodes have been visited.\n\nThe time complexity is $O(n + m)$, and the space complexity is $O(n + m)$. Where $n$ and $m$ are the number of nodes and edges, respectively.", "2": "We can use a union-find set to maintain the connected components in the graph.\n\nFirst, we initialize a union-find set, then traverse all the edges. For each edge $(a, b)$, we merge nodes $a$ and $b$ into the same connected component. If the merge is successful, it means that nodes $a$ and $b$ were not in the same connected component before, and the number of connected components decreases by one.\n\nFinally, we return the number of connected components.\n\nThe time complexity is $O(n + m \\times \\alpha(n))$, and the space complexity is $O(n)$. Where $n$ and $m$ are the number of nodes and edges, respectively, and $\\alpha(n)$ is the inverse of the Ackermann function, which can be regarded as a very small constant.", "3": "We can also use BFS (Breadth-First Search) to count the number of connected components in the graph.\n\nSimilar to Solution 1, we first construct an adjacency list $g$ based on the given edges. Then we traverse all nodes. For each node, if it has not been visited, we start BFS traversal from this node, marking all its adjacent nodes as visited, until all its adjacent nodes have been visited. In this way, we have found a connected component, and the answer is incremented by one.\n\nAfter traversing all nodes, we get the number of connected components in the graph.\n\nThe time complexity is $O(n + m)$, and the space complexity is $O(n + m)$. Where $n$ and $m$ are the number of nodes and edges, respectively." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(n + m)" }, { "problem_id": 324, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 325, "explanations": { "1": "We can use a hash table $\\textit{d}$ to record the first occurrence index of each prefix sum in the array $\\textit{nums}$, initializing $\\textit{d}[0] = -1$. Additionally, we define a variable $\\textit{s}$ to keep track of the current prefix sum.\n\nNext, we iterate through the array $\\textit{nums}$. For the current number $\\textit{nums}[i]$, we update the prefix sum $\\textit{s} = \\textit{s} + \\textit{nums}[i]$. If $\\textit{s} - k$ exists in the hash table $\\textit{d}$, let $\\textit{j} = \\textit{d}[\\textit{s} - k]$, then the length of the subarray that ends at $\\textit{nums}[i]$ and satisfies the condition is $i - j$. We use a variable $\\textit{ans}$ to maintain the length of the longest subarray that satisfies the condition. After that, if $\\textit{s}$ does not exist in the hash table, we record $\\textit{s}$ and its corresponding index $i$ by setting $\\textit{d}[\\textit{s}] = i$. Otherwise, we do not update $\\textit{d}[\\textit{s}]$. It is important to note that there may be multiple positions $i$ with the same value of $\\textit{s}$, so we only record the smallest $i$ to ensure the subarray length is the longest.\n\nAfter the iteration ends, we return $\\textit{ans}$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 326, "explanations": { "1": "If $n \\gt 2$, we can continuously divide $n$ by $3$. If it's not divisible, it means $n$ is not a power of $3$, otherwise we continue dividing by $3$ until $n$ is less than or equal to $2$. If $n$ equals $1$, it means $n$ is a power of $3$, otherwise it's not a power of $3$.\n\nTime complexity $O(\\log_3n)$, space complexity $O(1)$.", "2": "If $n$ is a power of $3$, then the maximum value of $n$ is $3^{19} = 1162261467$. Therefore, we only need to check if $n$ is a divisor of $3^{19}$.\n\nTime complexity $O(1)$, space complexity $O(1)$." }, "is_english": true, "time_complexity": "O(\\log_3n)", "space_complexity": "O(1)" }, { "problem_id": 327, "explanations": { "1": "题目要求区间和,因此我们可以先求出前缀和数组 $s$,其中 $s[i]$ 表示 $nums$ 中前 $i$ 个元素的和。那么对于任意的 $i \\lt j$,$s[j+1] - s[i]$ 就是 $nums$ 中下标在 $[i, j]$ 的元素之和。\n\n而 $lower \\leq s[j+1] - s[i] \\leq upper$,可以转换为 $s[j+1] - upper \\leq s[i] \\leq s[j+1] - lower$,也就是说,对于当前前缀和 $s[j+1]$,我们需要统计 $s$ 中有多少个下标 $i$ 满足 $s[j+1] - upper \\leq s[i] \\leq s[j+1] - lower$。\n\n我们可以用树状数组来维护每个前缀和出现的次数,这样对于每个前缀和 $s[j+1]$,我们只需要查询树状数组中有多少个前缀和 $s[i]$ 满足 $s[j+1] - upper \\leq s[i] \\leq s[j+1] - lower$ 即可。\n\n时间复杂度 $O(n \\times \\log n)$,空间复杂度 $O(n)$。其中 $n$ 为数组长度。" }, "is_english": false, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 328, "explanations": { "1": "We can use two pointers $a$ and $b$ to represent the tail nodes of the odd and even nodes respectively. Initially, pointer $a$ points to the head node $head$ of the list, and pointer $b$ points to the second node $head.next$ of the list. In addition, we use a pointer $c$ to point to the head node $head.next$ of the even nodes, which is the initial position of pointer $b$.\n\nWe traverse the list, set pointer $a$ to point to the next node of $b$, i.e., $a.next = b.next$, then move pointer $a$ back by one position, i.e., $a = a.next$; set pointer $b$ to point to the next node of $a$, i.e., $b.next = a.next$, then move pointer $b$ back by one position, i.e., $b = b.next$. Continue to traverse until $b$ reaches the end of the list.\n\nFinally, we set the tail node $a$ of the odd nodes to point to the head node $c$ of the even nodes, i.e., $a.next = c$, then return the head node $head$ of the list.\n\nThe time complexity is $O(n)$, where $n$ is the length of the list, and we need to traverse the list once. The space complexity is $O(1)$. We only need to maintain a limited number of pointers." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 329, "explanations": { "1": "We design a function $dfs(i, j)$, which represents the length of the longest increasing path that can be obtained starting from the coordinate $(i, j)$ in the matrix. The answer is $\\max_{i, j} \\textit{dfs}(i, j)$.\n\nThe execution logic of the function $dfs(i, j)$ is as follows:\n\n- If $(i, j)$ has been visited, directly return $\\textit{f}(i, j)$;\n- Otherwise, search $(i, j)$, search the coordinates $(x, y)$ in four directions. If $0 \\le x < m, 0 \\le y < n$ and $matrix[x][y] > matrix[i][j]$, then search $(x, y)$. After the search is over, update $\\textit{f}(i, j)$ to $\\textit{f}(i, j) = \\max(\\textit{f}(i, j), \\textit{f}(x, y) + 1)$. Finally, return $\\textit{f}(i, j)$.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Where $m$ and $n$ are the number of rows and columns of the matrix, respectively.\n\nSimilar problems:\n\n- [2328. Number of Increasing Paths in a Grid](https://github.com/doocs/leetcode/blob/main/solution/2300-2399/2328.Number%20of%20Increasing%20Paths%20in%20a%20Grid/README_EN.md)" }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 330, "explanations": { "1": "Let's assume that the number $x$ is the smallest positive integer that cannot be represented. Then all the numbers in $[1,..x-1]$ can be represented. In order to represent the number $x$, we need to add a number that is less than or equal to $x$:\n\n- If the added number equals $x$, since all numbers in $[1,..x-1]$ can be represented, after adding $x$, all numbers in the range $[1,..2x-1]$ can be represented, and the smallest positive integer that cannot be represented becomes $2x$.\n- If the added number is less than $x$, let's assume it's $x'$, since all numbers in $[1,..x-1]$ can be represented, after adding $x'$, all numbers in the range $[1,..x+x'-1]$ can be represented, and the smallest positive integer that cannot be represented becomes $x+x' \\lt 2x$.\n\nTherefore, we should greedily add the number $x$ to cover a larger range.\n\nWe use a variable $x$ to record the current smallest positive integer that cannot be represented, initialized to $1$. At this time, $[1,..x-1]$ is empty, indicating that no number can be covered; we use a variable $i$ to record the current index of the array being traversed.\n\nWe perform the following operations in a loop:\n\n- If $i$ is within the range of the array and $nums[i] \\le x$, it means that the current number can be covered, so we add the value of $nums[i]$ to $x$, and increment $i$ by $1$.\n- Otherwise, it means that $x$ is not covered, so we need to supplement a number $x$ in the array, and then update $x$ to $2x$.\n- Repeat the above operations until the value of $x$ is greater than $n$.\n\nThe final answer is the number of supplemented numbers.\n\nThe time complexity is $O(m + \\log n)$, where $m$ is the length of the array $nums$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m + \\log n)", "space_complexity": "O(1)" }, { "problem_id": 331, "explanations": { "1": "We split the string `preorder` into an array by commas, then traverse the array. If we encounter two consecutive `'#'` and the third element is not `'#'`, we replace these three elements with a single `'#'`. This process continues until the array traversal is complete.\n\nFinally, we check whether the length of the array is $1$ and whether the only element in the array is `'#'`.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of the string `preorder`." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 332, "explanations": { "1": "The problem is essentially about finding a path that starts from a specified starting point, passes through all the edges exactly once, and has the smallest lexicographical order among all such paths, given $n$ vertices and $m$ edges. This is a classic Eulerian path problem.\n\nSince the problem guarantees that there is at least one feasible itinerary, we can directly use the Hierholzer algorithm to output the Eulerian path starting from the starting point.\n\nThe time complexity is $O(m \\times \\log m)$, and the space complexity is $O(m)$. Here, $m$ is the number of edges." }, "is_english": true, "time_complexity": "O(m \\times \\log m)", "space_complexity": "O(m)" }, { "problem_id": 333, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 334, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 335, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 336, "explanations": { "1": "**字符串哈希**是把一个任意长度的字符串映射成一个非负整数,并且其冲突的概率几乎为 $0$。字符串哈希用于计算字符串哈希值,快速判断两个字符串是否相等。\n\n取一固定值 $BASE$,把字符串看作是 $BASE$ 进制数,并分配一个大于 $0$ 的数值,代表每种字符。一般来说,我们分配的数值都远小于 $BASE$。例如,对于小写字母构成的字符串,可以令 $a=1$, $b=2$, ..., $z=26$。取一固定值 $MOD$,求出该 $BASE$ 进制对 $M$ 的余数,作为该字符串的 $hash$ 值。\n\n一般来说,取 $BASE=131$ 或者 $BASE=13331$,此时 $hash$ 值产生的冲突概率极低。只要两个字符串 $hash$ 值相同,我们就认为两个字符串是相等的。通常 $MOD$ 取 $2^{64}$,C++ 里,可以直接使用 `unsigned long long` 类型存储这个 $hash$ 值,在计算时不处理算术溢出问题,产生溢出时相当于自动对 $2^{64}$ 取模,这样可以避免低效取模运算。\n\n除了在极特殊构造的数据上,上述 $hash$ 算法很难产生冲突,一般情况下上述 $hash$ 算法完全可以出现在题目的标准答案中。我们还可以多取一些恰当的 $BASE$ 和 $MOD$ 的值(例如大质数),多进行几组 $hash$ 运算,当结果都相同时才认为原字符串相等,就更加难以构造出使这个 $hash$ 产生错误的数据。", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 337, "explanations": { "1": "我们定义一个函数 $dfs(root)$,表示偷取以 $root$ 为根的二叉树的最大金额。该函数返回一个二元组 $(a, b)$,其中 $a$ 表示偷取 $root$ 节点时能得到的最大金额,而 $b$ 表示不偷取 $root$ 节点时能得到的最大金额。\n\n函数 $dfs(root)$ 的计算过程如下:\n\n如果 $root$ 为空,那么显然有 $dfs(root) = (0, 0)$。\n\n否则,我们首先计算出左右子节点的结果,即 $dfs(root.left)$ 和 $dfs(root.right)$,这样就得到了两对值 $(l_a, l_b)$ 以及 $(r_a, r_b)$。对于 $dfs(root)$ 的结果,我们可以分为两种情况:\n\n- 如果偷取 $root$ 节点,那么不能偷取其左右子节点,结果为 $root.val + l_b + r_b$;\n- 如果不偷取 $root$ 节点,那么可以偷取其左右子节点,结果为 $\\max(l_a, l_b) + \\max(r_a, r_b)$。\n\n在主函数中,我们可以直接返回 $dfs(root)$ 的较大值,即 $\\max(dfs(root))$。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点数。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 338, "explanations": { "1": "我们直接枚举 $0 \\leq i \\leq n$ 中的每个数,对于每个数 $i$,我们用库函数或者 $lowbit$ 运算得到 $i$ 中二进制位 $1$ 的个数。\n\n时间复杂度 $O(n \\times \\log n)$,忽略答案的空间消耗,空间复杂度 $O(1)$。", "2": "我们定义一个长度为 $n+1$ 的答案数组 $ans$,初始时 $ans[0]=0$。\n\n对于 $1 \\leq i \\leq n$,我们有 $ans[i] = ans[i \\textit{ and } (i-1)] + 1$。其中 $i \\textit{ and } (i-1)$ 表示将 $i$ 的二进制表示中的最低位 $1$ 变成 $0$ 之后的数,显然 $i \\textit{ and } (i-1) < i$,且 $ans[i \\textit{ and } (i-1)]$ 已经被计算出来了,我们就能以 $O(1)$ 的时间得到 $ans[i]$。\n\n时间复杂度 $O(n)$,空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(1)" }, { "problem_id": 339, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 340, "explanations": { "1": "We can use the idea of a sliding window, with a hash table $\\textit{cnt}$ to record the occurrence count of each character within the window, and $\\textit{l}$ to denote the left boundary of the window.\n\nIterate through the string, adding the character at the right boundary to the hash table each time. If the number of distinct characters in the hash table exceeds $k$, remove the character at the left boundary from the hash table, then update the left boundary $\\textit{l}$.\n\nFinally, return the length of the string minus the length of the left boundary.\n\nThe time complexity is $O(n)$, and the space complexity is $O(k)$. Here, $n$ is the length of the string." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(k)" }, { "problem_id": 341, "explanations": { "1": "根据题意要求可以将 NestedInteger 数据结构视作一个 N 叉树,当元素为一个整数时,该节点是 N 叉树的叶子节点,当元素为一个整数数组时,该节点是 N 叉树的非叶子节点,数组中的每一个元素包含子树的所有节点。故直接递归遍历 N 叉树并记录所有的叶子节点即可。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 342, "explanations": { "1": "If a number is a power of $4$, then it must be greater than $0$. Suppose this number is $4^x$, which is $2^{2x}$. Therefore, its binary representation has only one $1$, and this $1$ appears at an even position.\n\nFirst, we check if the number is greater than $0$. Then, we verify if the number is $2^{2x}$ by checking if the bitwise AND of $n$ and $n-1$ is $0$. Finally, we check if the $1$ appears at an even position by verifying if the bitwise AND of $n$ and $\\textit{0xAAAAAAAA}$ is $0$. If all three conditions are met, then the number is a power of $4$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 343, "explanations": { "1": "When $n < 4$, since the problem requires splitting into at least two integers, $n - 1$ yields the maximum product. When $n \\geq 4$, we split into as many $3$s as possible. If the last segment remaining is $4$, we split it into $2 + 2$ for the maximum product.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 344, "explanations": { "1": "We use two pointers $i$ and $j$, initially pointing to the start and end of the array respectively. Each time, we swap the elements at $i$ and $j$, then move $i$ forward and $j$ backward, until $i$ and $j$ meet.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 345, "explanations": { "1": "We can use two pointers $i$ and $j$, initially pointing to the start and end of the string respectively.\n\nIn each loop, we check whether the character at $i$ is a vowel. If it's not, we move $i$ forward. Similarly, we check whether the character at $j$ is a vowel. If it's not, we move $j$ backward. If $i < j$ at this point, then both characters at $i$ and $j$ are vowels, so we swap these two characters. Then, we move $i$ forward and $j$ backward. We continue the above operations until $i \\ge j$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(|\\Sigma|)$, where $\\Sigma$ is the size of the character set." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 346, "explanations": { "1": "We define a variable $\\textit{s}$ to calculate the sum of the last $\\textit{size}$ elements, and a variable $\\textit{cnt}$ to record the total number of current elements. Additionally, we use an array $\\textit{data}$ of length $\\textit{size}$ to record the value of each element at each position.\n\nWhen calling the $\\textit{next}$ function, we first calculate the index $i$ where $\\textit{val}$ should be stored, then update the sum $s$, set the value at index $i$ to $\\textit{val}$, and increment the element count by one. Finally, we return the value of $\\frac{s}{\\min(\\textit{cnt}, \\textit{size})}$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(n)$, where $n$ is the integer $\\textit{size}$ given in the problem.", "2": "We can use a queue $\\textit{q}$ to store the last $\\textit{size}$ elements, and a variable $\\textit{s}$ to record the sum of these $\\textit{size}$ elements.\n\nWhen calling the $\\textit{next}$ function, we first check if the length of the queue $\\textit{q}$ is equal to $\\textit{size}$. If it is, we dequeue the front element of the queue $\\textit{q}$ and update the value of $\\textit{s}$. Then we enqueue $\\textit{val}$ and update the value of $\\textit{s}$. Finally, we return the value of $\\frac{s}{\\text{len}(q)}$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(n)$, where $n$ is the integer $\\textit{size}$ given in the problem." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(n)" }, { "problem_id": 347, "explanations": { "1": "We can use a hash table $\\textit{cnt}$ to count the occurrence of each element, and then use a min heap (priority queue) to store the top $k$ frequent elements.\n\nFirst, we traverse the array once to count the occurrence of each element. Then, we iterate through the hash table, storing each element and its count into the min heap. If the size of the min heap exceeds $k$, we pop the top element of the heap to ensure the heap size is always $k$.\n\nFinally, we pop the elements from the min heap one by one and place them into the result array.\n\nThe time complexity is $O(n \\log k)$, and the space complexity is $O(k)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n \\log k)", "space_complexity": "O(k)" }, { "problem_id": 348, "explanations": { "1": "We can use an array of length $n \\times 2 + 2$ to record the number of pieces each player has in each row, each column, and the two diagonals. We need two such arrays to record the number of pieces for the two players respectively.\n\nWhen a player has $n$ pieces in a certain row, column, or diagonal, that player wins.\n\nIn terms of time complexity, the time complexity of each move is $O(1)$. The space complexity is $O(n)$, where $n$ is the length of the side of the chessboard." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(n)" }, { "problem_id": 349, "explanations": { "1": "First, we use a hash table or an array $s$ of length $1001$ to record the elements that appear in the array $nums1$. Then, we iterate through each element in the array $nums2$. If an element $x$ is in $s$, we add $x$ to the answer and remove $x$ from $s$.\n\nAfter the iteration is finished, we return the answer array.\n\nThe time complexity is $O(n+m)$, and the space complexity is $O(n)$. Here, $n$ and $m$ are the lengths of the arrays $nums1$ and $nums2$, respectively." }, "is_english": true, "time_complexity": "O(n+m)", "space_complexity": "O(n)" }, { "problem_id": 350, "explanations": { "1": "We can use a hash table $\\textit{cnt}$ to count the occurrences of each element in the array $\\textit{nums1}$. Then, we iterate through the array $\\textit{nums2}$. If an element $x$ is in $\\textit{cnt}$ and the occurrence of $x$ is greater than $0$, we add $x$ to the answer and then decrement the occurrence of $x$ by one.\n\nAfter the iteration is finished, we return the answer array.\n\nThe time complexity is $O(m + n)$, and the space complexity is $O(m)$. Here, $m$ and $n$ are the lengths of the arrays $\\textit{nums1}$ and $\\textit{nums2}$, respectively." }, "is_english": true, "time_complexity": "O(m + n)", "space_complexity": "O(m)" }, { "problem_id": 351, "explanations": { "1": "我们定义一个二维数组 $cross$,其中 $cross[i][j]$ 表示数字 $i$ 和数字 $j$ 之间是否有中间数字,如果有则 $cross[i][j]$ 的值为中间数字,否则为 $0$。\n\n我们还需要一个一维数组 $vis$,用来记录数字是否被使用过。\n\n由于数字 $1$, $3$, $7$, $9$ 是对称的,因此我们只需要计算数字 $1$ 的情况,然后乘以 $4$ 即可。\n\n由于数字 $2$, $4$, $6$, $8$ 也是对称的,因此我们只需要计算数字 $2$ 的情况,然后乘以 $4$ 即可。\n\n最后我们再计算数字 $5$ 的情况。\n\n我们设计一个函数 $dfs(i, cnt)$,表示当前位于数字 $i$,且已经选了 $cnt$ 个数字的情况下,有多少种解锁模式。\n\n函数 $dfs(i, cnt)$ 的执行过程如下:\n\n如果 $cnt \\gt n$,说明当前选中的数字个数超过了 $n$,直接返回 $0$。\n\n否则,我们将数字 $i$ 标记为已使用,然后初始化答案 $ans$ 为 $0$。如果 $cnt \\ge m$,说明当前选中的数字个数不少于 $m$,那么答案 $ans$ 就需要加 $1$。\n\n接下来,我们枚举下一个数字 $j$,如果数字 $j$ 没有被使用过,且数字 $i$ 和数字 $j$ 之间没有中间数字,或者数字 $i$ 和数字 $j$ 之间的中间数字已经被使用过,那么我们就可以从数字 $j$ 出发,继续搜索,此时答案 $ans$ 需要加上 $dfs(j, cnt + 1)$ 的返回值。\n\n最后,我们将数字 $i$ 标记为未使用,然后返回答案 $ans$。\n\n最终的答案即为 $dfs(1, 1) \\times 4 + dfs(2, 1) \\times 4 + dfs(5, 1)$。\n\n时间复杂度 $O(n!)$,空间复杂度 $O(n)$。其中 $n$ 是手势的最大长度。" }, "is_english": false, "time_complexity": "O(n!)", "space_complexity": "O(n)" }, { "problem_id": 352, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 353, "explanations": { "1": "我们可以使用双端队列来模拟蛇的移动。\n\n定义一个双端队列 $q$,其中保存蛇的身体坐标,队头为蛇头,队尾为蛇尾。同时使用一个集合 $vis$ 来保存蛇的身体坐标,用于快速判断蛇头是否与蛇身相撞。\n\n定义一个变量 $score$ 来保存蛇的得分,初始值为 $0$;定义一个变量 $idx$ 来保存当前食物的索引,初始值为 $0$。\n\n每次移动时,首先判断蛇头是否与边界相撞,如果相撞则游戏结束,返回 $-1$;否则,判断蛇头是否与食物重合,如果重合则蛇的得分加 $1$,同时食物索引 $idx$ 加 $1$;否则,蛇的身体长度不变,需要将蛇尾从队尾弹出,并从集合 $vis$ 中删除对应的坐标。\n\n然后,判断蛇头是否与蛇身相撞,如果相撞则游戏结束,返回 $-1$;否则,将蛇头的坐标加入集合 $vis$ 中,并从队头加入蛇头的坐标。\n\n最后,返回蛇的得分 $score$。\n\n时间复杂度 $O(k)$,空间复杂度 $O(k)$,其中 $k$ 为移动的次数。" }, "is_english": false, "time_complexity": "O(k)", "space_complexity": "O(k)" }, { "problem_id": 354, "explanations": { "1": "时间复杂度 O(nlogn)。" }, "is_english": false, "time_complexity": "O(nlogn)", "space_complexity": null }, { "problem_id": 355, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 356, "explanations": { "1": "我们先找出所有点中的最小、最大的 $x$ 坐标 $minX$ 和 $maxX$。若存在满足条件的直线,则直线 $x = (minX + maxX) / 2$,或者说 $s = minX + maxX$。\n\n接下来,我们遍历每个点 $(x, y),若 $(s - x, y)$ 不在点集里,说明不满足条件,直接返回 `false`。遍历结束返回 `true`。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 $points$ 的长度。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 357, "explanations": { "1": "This problem essentially asks for the number of numbers in the given range $[l, ..r]$ that satisfy certain conditions. The conditions are related to the composition of the numbers rather than their size, so we can use the concept of Digit DP to solve it. In Digit DP, the size of the number has little impact on the complexity.\n\nFor the range $[l, ..r]$ problem, we generally convert it to the problem of $[1, ..r]$ and then subtract the result of $[1, ..l - 1]$, i.e.:\n\n$$\nans = \\sum_{i=1}^{r} ans_i - \\sum_{i=1}^{l-1} ans_i\n$$\n\nHowever, for this problem, we only need to find the value for the range $[1, ..10^n-1]$.\n\nHere, we use memoized search to implement Digit DP. We search from the starting point downwards, and at the lowest level, we get the number of solutions. We then return the answers layer by layer upwards, and finally get the final answer from the starting point of the search.\n\nBased on the problem information, we design a function $\\textit{dfs}(i, \\textit{mask}, \\textit{lead})$, where:\n\n- The digit $i$ represents the current position being searched, starting from the highest digit, i.e., $i = 0$ represents the highest digit.\n- The digit $\\textit{mask}$ represents the current state of the number, i.e., the $j$-th bit of $\\textit{mask}$ being $1$ indicates that the digit $j$ has been used.\n- The boolean $\\textit{lead}$ indicates whether the current number only contains leading $0$s.\n\nThe function executes as follows:\n\nIf $i$ exceeds the length of the number $n$, i.e., $i < 0$, it means the search is over, directly return $1$.\n\nOtherwise, we enumerate the digits $j$ from $0$ to $9$ for the position $i$. For each $j$:\n\n- If the $j$-th bit of $\\textit{mask}$ is $1$, it means the digit $j$ has been used, so we skip it.\n- If $\\textit{lead}$ is true and $j = 0$, it means the current number only contains leading $0$s. When we recurse to the next level, $\\textit{lead}$ remains true.\n- Otherwise, we recurse to the next level, update the $j$-th bit of $\\textit{mask}$ to $1$, and set $\\textit{lead}$ to false.\n\nFinally, we sum all the results from the recursive calls to the next level, which is the answer.\n\nThe answer is $\\textit{dfs}(n - 1, 0, \\textit{True})$.\n\nThe time complexity is $O(n \\times 2^D \\times D)$, and the space complexity is $O(n \\times 2^D)$. Here, $n$ is the length of the number $n$, and $D = 10$.\n\nSimilar Problems:\n\n- [233. Number of Digit One](https://github.com/doocs/leetcode/blob/main/solution/0200-0299/0233.Number%20of%20Digit%20One/README_EN.md)\n- [600. Non-negative Integers without Consecutive Ones](https://github.com/doocs/leetcode/blob/main/solution/0600-0699/0600.Non-negative%20Integers%20without%20Consecutive%20Ones/README_EN.md)\n- [788. Rotated Digits](https://github.com/doocs/leetcode/blob/main/solution/0700-0799/0788.Rotated%20Digits/README_EN.md)\n- [902. Numbers At Most N Given Digit Set](https://github.com/doocs/leetcode/blob/main/solution/0900-0999/0902.Numbers%20At%20Most%20N%20Given%20Digit%20Set/README_EN.md)\n- [1012. Numbers with Repeated Digits](https://github.com/doocs/leetcode/blob/main/solution/1000-1099/1012.Numbers%20With%20Repeated%20Digits/README_EN.md)\n- [2376. Count Special Integers](https://github.com/doocs/leetcode/blob/main/solution/2300-2399/2376.Count%20Special%20Integers/README_EN.md)" }, "is_english": true, "time_complexity": "O(n \\times 2^D \\times D)", "space_complexity": "O(n \\times 2^D)" }, { "problem_id": 358, "explanations": { "1": "We use a hash table or array $\\textit{cnt}$ to count the occurrences of each character in the string. Then, we use a max heap $\\textit{pq}$ to store each character and its count. Each element in the heap is a tuple $(v, c)$, where $v$ is the count and $c$ is the character.\n\nWhen rearranging the string, we repeatedly pop the top element $(v, c)$ from the heap, add character $c$ to the result string, and push $(v-1, c)$ into a queue $\\textit{q}$. When the length of the queue $\\textit{q}$ reaches $k$ or more, we pop the front element; if its $v$ is greater than $0$, we push it back into the heap. Repeat this process until the heap is empty.\n\nFinally, we check whether the length of the result string equals the original string. If so, we return the result string; otherwise, we return an empty string.\n\nThe time complexity is $O(n \\log n)$, where $n$ is the length of the string. The space complexity is $O(|\\Sigma|)$, where $|\\Sigma|$ is the size of the character set, which is $26$ in this problem.\n\nRelated problems:\n\n- [767. Reorganize String](https://github.com/doocs/leetcode/blob/main/solution/0700-0799/0767.Reorganize%20String/README.md)" }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 359, "explanations": { "1": "We use a hash table $\\textit{ts}$ to store the next available print timestamp for each message. When the `shouldPrintMessage` method is called, we check whether the current timestamp is greater than or equal to the next available print timestamp for the message. If so, we update the next available print timestamp to the current timestamp plus 10 and return `true`; otherwise, we return `false`.\n\nThe time complexity is $O(1)$. The space complexity is $O(m)$, where $m$ is the number of distinct messages." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(m)" }, { "problem_id": 360, "explanations": { "1": "By mathematical knowledge, the graph of a quadratic function is a parabola. When $a \\gt 0$, the parabola opens upwards and its vertex is the minimum value; when $a \\lt 0$, the parabola opens downwards and its vertex is the maximum value.\n\nSince the array $\\textit{nums}$ is already sorted, we can use two pointers at both ends of the array. Depending on the sign of $a$, we decide whether to fill the result array from the beginning or the end with the larger (or smaller) values.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 361, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 362, "explanations": { "1": "Since `timestamp` is monotonically increasing, we can use an array `ts` to store all `timestamp`s. Then in the `getHits` method, we use binary search to find the first position that is greater than or equal to `timestamp - 300 + 1`, and then return the length of `ts` minus this position.\n\nIn terms of time complexity, the time complexity of the `hit` method is $O(1)$, and the time complexity of the `getHits` method is $O(\\log n)$. Where $n$ is the length of `ts`." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": null }, { "problem_id": 363, "explanations": { "1": "We can enumerate the upper and lower boundaries $i$ and $j$ of the rectangle, then calculate the sum of the elements in each column within this boundary, and record it in the array $nums$. The problem is transformed into how to find the maximum subarray sum not exceeding $k$ in the array $nums$.\n\nWe can use an ordered set to quickly find the maximum value less than or equal to $x$, thereby obtaining a subarray with the maximum subarray sum not exceeding $k$.\n\nThe time complexity is $O(m^2 \\times n \\times \\log n)$, and the space complexity is $O(n)$." }, "is_english": true, "time_complexity": "O(m^2 \\times n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 364, "explanations": { "1": "Let's assume the integers are $a_1, a_2, \\cdots, a_n$, their depths are $d_1, d_2, \\cdots, d_n$, the maximum depth is $\\textit{maxDepth}$, then the answer is:\n\n$$\na_1 \\times \\textit{maxDepth} - a_1 \\times d_1 + a_1 + a_2 \\times \\textit{maxDepth} - a_2 \\times d_2 + a_2 + \\cdots + a_n \\times \\textit{maxDepth} - a_n \\times d_n + a_n\n$$\n\nwhich is:\n\n$$\n(\\textit{maxDepth} + 1) \\times (a_1 + a_2 + \\cdots + a_n) - (a_1 \\times d_1 + a_2 \\times d_2 + \\cdots + a_n \\times d_n)\n$$\n\nIf we denote the sum of all integers as $s$, and the sum of each integer multiplied by its depth as $ws$, then the answer is:\n\n$$\n(\\textit{maxDepth} + 1) \\times s - ws\n$$\n\nTherefore, we design a function $dfs(x, d)$, which starts searching from $x$ with depth $d$. The execution process of $dfs(x, d)$ is as follows:\n\n- We first update $\\textit{maxDepth} = \\max(\\textit{maxDepth}, d)$;\n- If $x$ is an integer, then we update $s = s + x$, $ws = ws + x \\times d$;\n- Otherwise, we recursively traverse each element $y$ of $x$, and call $dfs(y, d + 1)$.\n\nWe traverse the entire list, for each element $x$, we call $dfs(x, 1)$, and finally return $(\\textit{maxDepth} + 1) \\times s - ws$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of integers." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 365, "explanations": { "1": "Let's denote $jug1Capacity$ as $x$, $jug2Capacity$ as $y$, and $targetCapacity$ as $z$.\n\nNext, we design a function $dfs(i, j)$, which represents whether we can get $z$ liters of water when there are $i$ liters of water in $jug1$ and $j$ liters of water in $jug2$.\n\nThe execution process of the function $dfs(i, j)$ is as follows:\n\n- If $(i, j)$ has been visited, return $false$.\n- If $i = z$ or $j = z$ or $i + j = z$, return $true$.\n- If we can get $z$ liters of water by filling $jug1$ or $jug2$, or emptying $jug1$ or $jug2$, return $true$.\n- If we can get $z$ liters of water by pouring water from $jug1$ into $jug2$, or pouring water from $jug2$ into $jug1$, return $true$.\n\nThe answer is $dfs(0, 0)$.\n\nThe time complexity is $O(x + y)$, and the space complexity is $O(x + y)$. Here, $x$ and $y$ are the sizes of $jug1Capacity$ and $jug2Capacity$ respectively." }, "is_english": true, "time_complexity": "O(x + y)", "space_complexity": "O(x + y)" }, { "problem_id": 366, "explanations": { "1": "我们可以使用深度优先搜索的方法,递归遍历二叉树,将每个节点的高度作为索引,将节点的值添加到对应索引的数组中。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉树的节点个数。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 367, "explanations": { "1": "We can use binary search to solve this problem. Define the left boundary $l = 1$ and the right boundary $r = num$ of the binary search, then find the smallest integer $x$ that satisfies $x^2 \\geq num$ in the range $[l, r]$. Finally, if $x^2 = num$, then $num$ is a perfect square.\n\nThe time complexity is $O(\\log n)$, where $n$ is the given number. The space complexity is $O(1)$.", "2": "Since $1 + 3 + 5 + \\cdots + (2n - 1) = n^2$, we can gradually subtract $1, 3, 5, \\cdots$ from $num$. If $num$ finally equals $0$, then $num$ is a perfect square.\n\nThe time complexity is $O(\\sqrt n)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 368, "explanations": { "1": "我们先对数组进行排序,这样可以保证对于任意的 $i \\lt j$,如果 $nums[i]$ 可以整除 $nums[j]$,那么 $nums[i]$ 一定在 $nums[j]$ 的左边。\n\n接下来,我们定义 $f[i]$ 表示以 $nums[i]$ 为最大元素的最大整除子集的大小,初始时 $f[i]=1$。\n\n对于每一个 $i$,我们从左往右枚举 $j$,如果 $nums[i]$ 可以被 $nums[j]$ 整除,那么 $f[i]$ 可以从 $f[j]$ 转移而来,我们更新 $f[i]=max(f[i], f[j]+1)$。过程中,我们记录 $f[i]$ 的最大值的下标 $k$ 以及对应的子集大小 $m$。\n\n最后,我们从 $k$ 开始倒序遍历,如果 $nums[k]$ 可以被 $nums[i]$ 整除,且 $f[i]=m$,那么 $nums[i]$ 就是一个整除子集的元素,我们将 $nums[i]$ 加入答案,并将 $m$ 减 $1$,同时更新 $k=i$。继续倒序遍历,直到 $m=0$。\n\n时间复杂度 $O(n^2)$,空间复杂度 $O(n)$。其中 $n$ 是数组的长度。" }, "is_english": false, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 369, "explanations": { "1": "We first set a dummy head node $\\textit{dummy}$, initially with a value of $0$, and the successor node of $\\textit{dummy}$ is the linked list $\\textit{head}$.\n\nNext, we traverse the linked list starting from the dummy head node, find the last node that is not $9$, increment its value by $1$, and set the values of all nodes after this node to $0$.\n\nFinally, we check if the value of the dummy head node is $1$. If it is $1$, we return $\\textit{dummy}$; otherwise, we return the successor node of $\\textit{dummy}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the linked list. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 370, "explanations": { "1": "This is a template problem for difference arrays.\n\nWe define $d$ as the difference array. To add $c$ to each number in the interval $[l,..r]$, we set $d[l] += c$ and $d[r+1] -= c$. Finally, we compute the prefix sum of the difference array to obtain the original array.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array.", "2": "The time complexity is $O(n \\times \\log n)$.\n\nA Binary Indexed Tree (BIT), also known as a Fenwick Tree, can efficiently perform the following two operations:\n\n1. **Point Update** `update(x, delta)`: Add a value $delta$ to the number at position $x$ in the sequence.\n2. **Prefix Sum Query** `query(x)`: Query the sum of the interval $[1, ... , x]$ in the sequence, i.e., the prefix sum up to position $x$.\n\nThe time complexity for both operations is $O(\\log n)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 371, "explanations": { "1": "两数字的二进制形式 a,b ,求和 s = a + b ,a(i)、b(i) 分别表示 a、b 的第 i 个二进制位。一共有 4 种情况:\n\n| a(i) | b(i) | 不进位的和 | 进位 |\n| ---- | ---- | ---------- | ---- |\n| 0 | 0 | 0 | 0 |\n| 0 | 1 | 1 | 0 |\n| 1 | 0 | 1 | 0 |\n| 1 | 1 | 0 | 1 |\n\n观察可以发现,“不进位的和”与“异或运算”有相同规律,而进位则与“与”运算规律相同,并且需要左移一位。\n\n- 对两数进行按位 `^` 异或运算,得到不进位的和;\n- 对两数进行按位 `&` 与运算,然后左移一位,得到进位;\n- 问题转换为求:“不进位的数 + 进位” 之和;\n- 循环,直至进位为 0,返回不进位的数即可(也可以用递归实现)。\n\n时间复杂度 $O(\\log n)$。" }, "is_english": false, "time_complexity": "O(\\log n)", "space_complexity": null }, { "problem_id": 372, "explanations": { "1": "我们初始化答案变量 $ans = 1$。\n\n接下来,倒序遍历数组 $b$,每次遍历到一个元素 $e$,我们将答案变量 $ans$ 自乘 $a^e$ 并对 $1337$ 取模,然后将 $a$ 自乘 $10$ 次并对 $1337$ 取模。这里需要用到快速幂。\n\n遍历完数组后,返回答案即可。\n\n时间复杂度 $O(\\sum_{i=0}^{n-1} \\log b_i)$,空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(\\sum_{i=0}^{n-1} \\log b_i)", "space_complexity": "O(1)" }, { "problem_id": 373, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 374, "explanations": { "1": "We perform a binary search in the interval $[1,..n]$, and find the first number that satisfies `guess(x) <= 0`, which is the answer.\n\nThe time complexity is $O(\\log n)$, where $n$ is the upper limit given in the problem. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 375, "explanations": { "1": "We define $f[i][j]$ as the minimum cost required to guess any number in the interval $[i, j]$. Initially, $f[i][i] = 0$ because there is no cost to guess the only number, and for $i > j$, we also have $f[i][j] = 0$. The answer is $f[1][n]$.\n\nFor $f[i][j]$, we can enumerate any number $k$ in $[i, j]$, divide the interval $[i, j]$ into two parts, $[i, k - 1]$ and $[k + 1, j]$, choose the larger value of the two parts plus the cost of $k$," }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 376, "explanations": { "1": "We define $f[i]$ as the length of the wiggle sequence ending at the $i$th element with an upward trend, and $g[i]$ as the length of the wiggle sequence ending at the $i$th element with a downward trend. Initially, $f[0] = g[0] = 1$ because when there is only one element, the length of the wiggle sequence is $1$. Initialize the answer as $1$.\n\nFor $f[i]$, where $i \\geq 1$, we enumerate $j$ in the range $[0, i)$, if $nums[j] < nums[i]$, it means that $i$ can be appended after $j$ to form an upward wiggle sequence, then $f[i] = \\max(f[i], g[j] + 1)$; if $nums[j] > nums[i]$, it means that $i$ can be appended after $j$ to form a downward wiggle sequence, then $g[i] = \\max(g[i], f[j] + 1)$. Then we update the answer to $\\max(f[i], g[i])$.\n\nFinally, we return the answer.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 377, "explanations": { "1": "We define $f[i]$ as the number of combinations that sum up to $i$. Initially, $f[0] = 1$, and the rest $f[i] = 0$. The final answer is $f[target]$.\n\nFor $f[i]$, we can enumerate each element $x$ in the array. If $i \\ge x$, then $f[i] = f[i] + f[i - x]$.\n\nFinally, return $f[target]$.\n\nThe time complexity is $O(n \\times target)$, and the space complexity is $O(target)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n \\times target)", "space_complexity": "O(target)" }, { "problem_id": 378, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 379, "explanations": { "1": "We can use a hash set `available` to store unallocated phone numbers. Initially, the hash set contains `[0, 1, 2, ..., maxNumbers - 1]`.\n\nWhen the `get` method is called, we take an unallocated phone number from `available`. If `available` is empty, we return `-1`. The time complexity is $O(1)$.\n\nWhen the `check` method is called, we just need to check whether `number` is in `available`. The time complexity is $O(1)$.\n\nWhen the `release` method is called, we add `number` to `available`. The time complexity is $O(1)$.\n\nThe space complexity is $O(n)$, where $n$ is the value of `maxNumbers`." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(n)" }, { "problem_id": 380, "explanations": { "1": "We define a dynamic list $q$ to store the elements in the set, and a hash table $d$ to store the index of each element in $q$.\n\nWhen inserting an element, if the element already exists in the hash table $d$, return `false` directly; otherwise, we insert the element into the end of the dynamic list $q$, and insert the element and its index in $q$ into the hash table $d$ at the same time, and finally return `true`.\n\nWhen deleting an element, if the element does not exist in the hash table $d$, return `false` directly; otherwise, we obtain the index of the element in the list $q$ from the hash table, then swap the last element $q[-1]$ in the list $q$ with $q[i]$, and then update the index of $q[-1]$ in the hash table to $i$. Then delete the last element in $q$, and remove the element from the hash table at the same time, and finally return `true`.\n\nWhen getting a random element, we can randomly select an element from the dynamic list $q$ and return it.\n\nTime complexity $O(1)$, space complexity $O(n)$, where $n$ is the number of elements in the set." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(n)" }, { "problem_id": 381, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 382, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 383, "explanations": { "1": "We can use a hash table or an array $cnt$ of length $26$ to record the number of times each character appears in the string `magazine`. Then traverse the string `ransomNote`, for each character $c$ in it, we decrease the number of $c$ by $1$ in $cnt$. If the number of $c$ is less than $0$ after the decrease, it means that the number of $c$ in `magazine` is not enough, so it cannot be composed of `ransomNote`, just return $false$.\n\nOtherwise, after the traversal, it means that each character in `ransomNote` can be found in `magazine`. Therefore, return $true$.\n\nThe time complexity is $O(m + n)$, and the space complexity is $O(C)$. Where $m$ and $n$ are the lengths of the strings `ransomNote` and `magazine` respectively; and $C$ is the size of the character set, which is $26$ in this question." }, "is_english": true, "time_complexity": "O(m + n)", "space_complexity": "O(C)" }, { "problem_id": 384, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 385, "explanations": { "1": "We first judge whether the string $s$ is empty or an empty list. If so, simply return an empty `NestedInteger`. If $s$ is an integer, we simply return a `NestedInteger` containing this integer. Otherwise, we traverse the string $s$ from left to right. If the current depth is $0$ and we encounter a comma or the end of the string $s$, we take a substring and recursively call the function to parse the substring and add the return value to the list. Otherwise, if the current encounter is a left parenthesis, we increase the depth by $1$ and continue to traverse. If we encounter a right parenthesis, we decrease the depth by $1$ and continue to traverse.\n\nAfter the traversal is over, return the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string $s$.", "2": "We can use a stack to simulate the recursive process.\n\nWe first judge whether the string $s$ is an integer. If so, we simply return a `NestedInteger` containing this integer. Otherwise, we traverse the string $s$ from left to right. For the character $c$ currently traversed:\n\n- If $c$ is a negative sign, we set the negative sign to `true`;\n- If $c$ is a number, we add the number to the current number $x$, where the initial value of $x$ is $0$;\n- If $c$ is a left parenthesis, we push a new `NestedInteger` onto the stack;\n- If $c$ is a right parenthesis or comma, we judge whether the previous character of the current character is a number. If so, we add the current number $x$ to the top `NestedInteger` of the stack according to the negative sign, and then reset the negative sign to `false` and the current number $x$ to $0$. If $c$ is a right parenthesis and the size of the current stack is greater than $1$, we pop the top `NestedInteger` of the stack and add it to the top `NestedInteger` of the stack.\n\nAfter the traversal is over, return the top `NestedInteger` of the stack.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 386, "explanations": { "1": "We first define a variable $v$, initially $v = 1$. Then we start iterating from $1$, adding $v$ to the answer array each time. Then, if $v \\times 10 \\leq n$, we update $v$ to $v \\times 10$; otherwise, if $v \\bmod 10 = 9$ or $v + 1 > n$, we loop to divide $v$ by $10$. After the loop ends, we increment $v$. Continue iterating until we have added $n$ numbers to the answer array.\n\nThe time complexity is $O(n)$, where $n$ is the given integer $n$. Ignoring the space consumption of the answer array, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 387, "explanations": { "1": "We use a hash table or an array of length $26$ $\\text{cnt}$ to store the frequency of each character. Then, we traverse each character $\\text{s[i]}$ from the beginning. If $\\text{cnt[s[i]]}$ is $1$, we return $i$.\n\nIf no such character is found after the traversal, we return $-1$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(|\\Sigma|)$, where $\\Sigma$ is the character set. In this problem, the character set consists of lowercase letters, so $|\\Sigma|=26$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 388, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 389, "explanations": { "1": "We can use a hash table or array $cnt$ to count the occurrence of each character in string $s$, then traverse string $t$. For each character, we subtract its occurrence in $cnt$. If the corresponding count is negative, it means that the occurrence of this character in $t$ is greater than in $s$, so this character is the added character.\n\nThe time complexity is $O(n)$, and the space complexity is $O(|\\Sigma|)$, where $n$ is the length of the string, and $\\Sigma$ represents the character set. Here the character set is all lowercase letters, so $|\\Sigma|=26$.", "2": "We can sum the ASCII values of each character in string $t$, then subtract the sum of the ASCII values of each character in string $s$. The final result is the ASCII value of the added character.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 390, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 391, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 392, "explanations": { "1": "We define two pointers $i$ and $j$ to point to the initial position of the string $s$ and $t$ respectively. Each time we compare the two characters pointed to by the two pointers, if they are the same, both pointers move right at the same time; if they are not the same, only $j$ moves right. When the pointer $i$ moves to the end of the string $s$, it means that $s$ is the subsequence of $t$.\n\nThe time complexity is $O(m + n)$, where $m$ and $n$ are the lengths of the strings $s$ and $t$ respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m + n)", "space_complexity": "O(1)" }, { "problem_id": 393, "explanations": { "1": "We use a variable $cnt$ to record the current number of bytes that need to be filled starting with $10$, initially $cnt = 0$.\n\nFor each integer $v$ in the array:\n\n- If $cnt > 0$, then check if $v$ starts with $10$. If not, return `false`, otherwise decrement $cnt$.\n- If the highest bit of $v$ is $0$, then $cnt = 0$.\n- If the highest two bits of $v$ are $110$, then $cnt = 1$.\n- If the highest three bits of $v$ are $1110$, then $cnt = 2$.\n- If the highest four bits of $v$ are $11110$, then $cnt = 3$.\n- Otherwise, return `false`.\n\nFinally, if $cnt = 0$, return `true`, otherwise return `false`.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array `data`. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 394, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 395, "explanations": { "1": "对于字符串 $s$,如果存在某个字符 $c$,其出现次数小于 $k$,则任何包含 $c$ 的子串都不可能满足题目要求。因此我们可以将 $s$ 按照每个不满足条件的字符 $c$ 进行分割,分割得到的每个子串都是原字符串的一个「子问题」,我们可以递归地求解每个子问题,最终的答案即为所有子问题的最大值。\n\n时间复杂度 $O(n \\times C)$,空间复杂度 $O(C^2)$。其中 $n$ 为字符串 $s$ 的长度,而 $C$ 为字符集的大小。本题中 $C \\leq 26$。" }, "is_english": false, "time_complexity": "O(n \\times C)", "space_complexity": "O(C^2)" }, { "problem_id": 396, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 397, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 398, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 399, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 400, "explanations": { "1": "The smallest and largest integers with $k$ digits are $10^{k-1}$ and $10^k-1$ respectively, so the total number of digits for $k$-digit numbers is $k \\times 9 \\times 10^{k-1}$.\n\nWe use $k$ to represent the number of digits of the current number, and $cnt$ to represent the total number of numbers with the current number of digits. Initially, $k=1$, $cnt=9$.\n\nEach time we subtract $cnt \\times k$ from $n$, when $n$ is less than or equal to $cnt \\times k$, it means that the number corresponding to $n$ is within the range of numbers with the current number of digits. At this time, we can calculate the corresponding number.\n\nThe specific method is to first calculate which number of the current number of digits corresponds to $n$, and then calculate which digit of this number it is, so as to get the number on this digit.\n\nThe time complexity is $O(\\log_{10} n)$." }, "is_english": true, "time_complexity": "O(\\log_{10} n)", "space_complexity": null }, { "problem_id": 401, "explanations": { "1": "The problem can be converted to finding all possible combinations of $i \\in [0, 12)$ and $j \\in [0, 60)$.\n\nA valid combination must satisfy the condition that the number of 1s in the binary representation of $i$ plus the number of 1s in the binary representation of $j$ equals $\\textit{turnedOn}$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$.", "2": "We can use $10$ binary bits to represent the watch, where the first $4$ bits represent hours and the last $6$ bits represent minutes. Enumerate each number in $[0, 2^{10})$, check if the number of 1s in its binary representation equals $\\textit{turnedOn}$, and if so, convert it to time format and add it to the answer.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 402, "explanations": { "1": "前置知识:两个相同位数的数字大小关系取决于第一个不同位的数的大小。\n\n基本的思路如下:\n\n- 从左到右遍历数组元素;\n- 对于遍历到的当前元素,选择保留;\n- 但可以选择性丢弃前面的相邻元素,丢弃与否取决于当前元素和前面相邻元素的大小;\n- 根据前置知识可知当当前元素小于前面相邻元素时可以移除前面相邻的元素。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 403, "explanations": { "1": "We use a hash table $pos$ to record the index of each stone. Next, we design a function $dfs(i, k)$, which means that the frog jumps from the $i$-th stone and the last jump distance is $k$. If the frog can reach the end, the function returns `true`, otherwise it returns `false`.\n\nThe calculation process of function $dfs(i, k)$ is as follows:\n\nIf $i$ is the index of the last stone, the frog has reached the end, and return `true`;\n\nOtherwise, we need to enumerate the frog's next jump distance $j$, where $j \\in [k-1, k, k+1]$. If $j$ is a positive integer and the hash table $pos$ exists the position $stones[i] + j$, then the frog can choose to jump $j$ units on the $i$-th stone, if $dfs(pos[stones[i] + j], j)$ returns `true`, the frog can successfully jump to the end from the $i$-th stone, and we can return `true`.\n\nThe enumeration is over, indicating that the frog cannot choose the appropriate jump distance on the $i$-th stone to jump to the end, so we return `false`.\n\nIn order to prevent repeated calculations in the function $dfs(i, k)$, we can use memoization, record the result of $dfs(i, k)$ in an array $f$, and assign $f[i][k]$ each time the function $dfs(i, k)$ returns result, and return $f[i][k]$ directly when encountering $dfs(i, k)$ next time.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Where $n$ is the number of stones.", "2": "We define $f[i][k]$ to be true if and only if it is possible to reach stone $i$ with last jump of size $k$. Initially $f[0][0] = true$, and all other elements of $f$ are false.\n\nWe can determine the value of $f[i][k]$ for all $i$ and $k$ using a double loop. For each possible jump size $k$, we look at the stones we could have jumped from: $i-k$, $i-k+1$, $i-k+2$. If any of these stones exist and if we can reach them with a last jump of size $k-1$, $k$, or $k+1$, then we can reach stone $i$ with a last jump of size $k$.\n\nIf we can reach the last stone, the answer is true. Otherwise, the answer is false.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Where $n$ is the number of stones." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 404, "explanations": { "1": "First, we check if `root` is null. If it is, we return $0$.\n\nOtherwise, we recursively call the `sumOfLeftLeaves` function to calculate the sum of all left leaves in `root`'s right subtree, and assign the result to the answer variable $ans$. Then we check if `root`'s left child exists. If it does, we check if it is a leaf node. If it is a leaf node, we add its value to the answer variable $ans$. Otherwise, we recursively call the `sumOfLeftLeaves` function to calculate the sum of all left leaves in `root`'s left subtree, and add the result to the answer variable $ans$.\n\nFinally, we return the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of nodes in the binary tree.", "2": "We can also convert the recursion in Solution 1 to iteration, using a stack to simulate the recursion process.\n\nSimilar to Solution 1, we first check if `root` is null. If it is, we return $0$.\n\nOtherwise, we initialize the answer variable $ans$ to $0$, and then initialize a stack $stk$ and add `root` to the stack.\n\nWhile the stack is not empty, we pop the top element `root` from the stack. If `root`'s left child exists, we check if it is a leaf node. If it is a leaf node, we add its value to the answer variable $ans$. Otherwise, we add its left child to the stack. Then we check if `root`'s right child exists. If it does, we add it to the stack.\n\nFinally, we return the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 405, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 406, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 407, "explanations": { "1": "This is a variant of the trapping rain water problem. Since the heights on the matrix boundaries are fixed, we can add these boundary heights to a priority queue. Then, we repeatedly take out the minimum height from the priority queue and compare it with the heights of its four adjacent cells. If an adjacent cell's height is less than the current height, we can trap water there. The volume of trapped water is the difference between the current height and the adjacent height. We then add the larger height back to the priority queue and repeat this process until the priority queue is empty.\n\nThe time complexity is $O(m \\times n \\times \\log (m \\times n))$, and the space complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns in the matrix, respectively." }, "is_english": true, "time_complexity": "O(m \\times n \\times \\log (m \\times n))", "space_complexity": "O(m \\times n)" }, { "problem_id": 408, "explanations": { "1": "We can directly simulate character matching and replacement.\n\nAssume the lengths of the string $word$ and the string $abbr$ are $m$ and $n$ respectively. We use two pointers $i$ and $j$ to point to the initial positions of the string $word$ and the string $abbr$ respectively, and use an integer variable $x$ to record the current matched number in $abbr$.\n\nLoop to match each character of the string $word$ and the string $abbr$:\n\nIf the character $abbr[j]$ pointed by the pointer $j$ is a number, if $abbr[j]$ is `'0'` and $x$ is $0$, it means that the number in $abbr$ has leading zeros, so it is not a valid abbreviation, return `false`; otherwise, update $x$ to $x \\times 10 + abbr[j] - '0'$.\n\nIf the character $abbr[j]$ pointed by the pointer $j$ is not a number, then we move the pointer $i$ forward by $x$ positions at this time, and then reset $x$ to $0$. If $i \\geq m$ or $word[i] \\neq abbr[j]$ at this time, it means that the two strings cannot match, return `false`; otherwise, move the pointer $i$ forward by $1$ position.\n\nThen we move the pointer $j$ forward by $1$ position, repeat the above process, until $i$ exceeds the length of the string $word$ or $j$ exceeds the length of the string $abbr$.\n\nFinally, if $i + x$ equals $m$ and $j$ equals $n$, it means that the string $word$ can be abbreviated as the string $abbr$, return `true`; otherwise return `false`.\n\nThe time complexity is $O(m + n)$, where $m$ and $n$ are the lengths of the string $word$ and the string $abbr$ respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m + n)", "space_complexity": "O(1)" }, { "problem_id": 409, "explanations": { "1": "A valid palindrome string can have at most one character that appears an odd number of times, and the rest of the characters appear an even number of times.\n\nTherefore, we can first traverse the string $s$, count the number of occurrences of each character, and record it in an array or hash table $cnt$.\n\nThen, we traverse $cnt$, for each count $v$, we divide $v$ by 2, take the integer part, multiply by 2, and add it to the answer $ans$.\n\nFinally, if the answer is less than the length of the string $s$, we increment the answer by one and return $ans$.\n\nThe time complexity is $O(n + |\\Sigma|)$, and the space complexity is $O(|\\Sigma|)$. Where $n$ is the length of the string $s$, and $|\\Sigma|$ is the size of the character set. In this problem, $|\\Sigma| = 128$.", "2": "We can use an array or hash table $odd$ to record whether each character in string $s$ appears an odd number of times, and an integer variable $cnt$ to record the number of characters that appear an odd number of times.\n\nWe iterate through the string $s$. For each character $c$, we flip $odd[c]$, i.e., $0 \\rightarrow 1$, $1 \\rightarrow 0$. If $odd[c]$ changes from $0$ to $1$, then we increment $cnt$ by one; if $odd[c]$ changes from $1$ to $0$, then we decrement $cnt$ by one.\n\nFinally, if $cnt$ is greater than $0$, the answer is $n - cnt + 1$, otherwise, the answer is $n$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(|\\Sigma|)$. Where $n$ is the length of the string $s$, and $|\\Sigma|$ is the size of the character set. In this problem, $|\\Sigma| = 128$." }, "is_english": true, "time_complexity": "O(n + |\\Sigma|)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 410, "explanations": { "1": "We notice that the larger the maximum sum of the subarrays, the fewer the number of subarrays. When there is a maximum sum of the subarrays that meets the condition, then a larger maximum sum of the subarrays will definitely meet the condition. This means that we can perform a binary search for the maximum sum of the subarrays to find the smallest value that meets the condition.\n\nWe define the left boundary of the binary search as $left = \\max(nums)$, and the right boundary as $right = sum(nums)$. Then for each step of the binary search, we take the middle value $mid = \\lfloor \\frac{left + right}{2} \\rfloor$, and then determine whether there is a way to split the array so that the maximum sum of the subarrays does not exceed $mid$. If there is, it means that $mid$ might be the smallest value that meets the condition, so we adjust the right boundary to $mid$. Otherwise, we adjust the left boundary to $mid + 1$.\n\nHow do we determine whether there is a way to split the array so that the maximum sum of the subarrays does not exceed $mid$? We can use a greedy method, traverse the array from left to right, and add the elements of the array to the subarray one by one. If the current sum of the subarray is greater than $mid$, then we add the current element to the next subarray. If we can split the array into no more than $k$ subarrays, and the maximum sum of each subarray does not exceed $mid$, then $mid$ is the smallest value that meets the condition. Otherwise, $mid$ does not meet the condition.\n\nThe time complexity is $O(n \\times \\log m)$, and the space complexity is $O(1)$. Here, $n$ and $m$ are the length of the array and the sum of all elements in the array, respectively." }, "is_english": true, "time_complexity": "O(n \\times \\log m)", "space_complexity": "O(1)" }, { "problem_id": 411, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 412, "explanations": { "1": "We iterate through each integer from 1 to $n$. For each integer, we check whether it is a multiple of both 3 and 5, or just a multiple of 3, or just a multiple of 5. Based on the check result, we add the corresponding string to the answer array.\n\nThe time complexity is $O(n)$, where $n$ is the integer given in the problem. Ignoring the space consumption of the answer array, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 413, "explanations": { "1": "We use $d$ to represent the current difference between two adjacent elements, and $cnt$ to represent the length of the current arithmetic sequence. Initially, $d = 3000$, $cnt = 2$.\n\nWe iterate through the array `nums`. For two adjacent elements $a$ and $b$, if $b - a = d$, it means that the current element $b$ also belongs to the current arithmetic sequence, and we increment $cnt$ by 1. Otherwise, it means that the current element $b$ does not belong to the current arithmetic sequence, and we update $d = b - a$, and $cnt = 2$. If $cnt \\ge 3$, it means that the length of the current arithmetic sequence is at least 3, and the number of arithmetic sequences is $cnt - 2$, which we add to the answer.\n\nAfter the iteration, we can get the answer.\n\nIn the code implementation, we can also initialize $cnt$ to $0$, and when resetting $cnt$, we directly set $cnt$ to $0$. When adding to the answer, we directly add $cnt$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$. Where $n$ is the length of the array `nums`.\n\nSimilar problems:\n\n- [1513. Number of Substrings With Only 1s](https://github.com/doocs/leetcode/blob/main/solution/1500-1599/1513.Number%20of%20Substrings%20With%20Only%201s/README_EN.md)\n- [2348. Number of Zero-Filled Subarrays](https://github.com/doocs/leetcode/blob/main/solution/2300-2399/2348.Number%20of%20Zero-Filled%20Subarrays/README_EN.md)" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 414, "explanations": { "1": "We can use three variables $m_1$, $m_2$, and $m_3$ to represent the first, second, and third largest numbers in the array respectively. Initially, we set these three variables to negative infinity.\n\nThen, we iterate through each number in the array. For each number:\n\n- If it equals any of $m_1$, $m_2$, or $m_3$, we skip this number.\n- If it is greater than $m_1$, we update the values of $m_1$, $m_2$, and $m_3$ to $m_2$, $m_3$, and this number respectively.\n- If it is greater than $m_2$, we update the values of $m_2$ and $m_3$ to $m_3$ and this number respectively.\n- If it is greater than $m_3$, we update the value of $m_3$ to this number.\n\nFinally, if the value of $m_3$ has not been updated, it means that there is no third largest number in the array, so we return $m_1$. Otherwise, we return $m_3$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array `nums`. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 415, "explanations": { "1": "We use two pointers $i$ and $j$ to point to the end of the two strings respectively, and start adding bit by bit from the end. Each time we take out the corresponding digits $a$ and $b$, calculate their sum $a + b + c$, where $c$ represents the carry from the last addition. Finally, we append the units digit of $a + b + c$ to the end of the answer string, and then take the tens digit of $a + b + c$ as the value of the carry $c$, and loop this process until the pointers of both strings have pointed to the beginning of the string and the value of the carry $c$ is $0$.\n\nFinally, reverse the answer string and return it.\n\nThe time complexity is $O(\\max(m, n))$, where $m$ and $n$ are the lengths of the two strings respectively. Ignoring the space consumption of the answer string, the space complexity is $O(1)$.\n\nThe following code also implements string subtraction, refer to the `subStrings(num1, num2)` function." }, "is_english": true, "time_complexity": "O(\\max(m, n))", "space_complexity": "O(1)" }, { "problem_id": 416, "explanations": { "1": "First, we calculate the total sum $s$ of the array. If the total sum is odd, it cannot be divided into two subsets with equal sums, so we directly return `false`. If the total sum is even, we set the target subset sum to $m = \\frac{s}{2}$. The problem is then transformed into: does there exist a subset whose element sum is $m$?\n\nWe define $f[i][j]$ to represent whether it is possible to select several numbers from the first $i$ numbers so that their sum is exactly $j$. Initially, $f[0][0] = true$ and the rest $f[i][j] = false$. The answer is $f[n][m]$.\n\nConsidering $f[i][j]$, if we select the $i$-th number $x$, then $f[i][j] = f[i - 1][j - x]$. If we do not select the $i$-th number $x$, then $f[i][j] = f[i - 1][j]$. Therefore, the state transition equation is:\n\n$$\nf[i][j] = f[i - 1][j] \\textit{ or } f[i - 1][j - x] \\textit{ if } j \\geq x\n$$\n\nThe final answer is $f[n][m]$.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Where $m$ and $n$ are half of the total sum of the array and the length of the array, respectively.", "2": "We notice that in Solution 1, $f[i][j]$ is only related to $f[i - 1][\\cdot]$. Therefore, we can compress the two-dimensional array into a one-dimensional array.\n\nThe time complexity is $O(n \\times m)$, and the space complexity is $O(m)$. Where $n$ is the length of the array, and $m$ is half of the total sum of the array." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 417, "explanations": { "1": "We can start from the boundaries of the Pacific and Atlantic oceans and perform breadth-first search (BFS) respectively to find all cells that can flow to the Pacific and Atlantic oceans. Finally, we take the intersection of the two results, which represents cells that can flow to both the Pacific and Atlantic oceans.\n\nSpecifically, we define a queue $q_1$ to store all cells adjacent to the Pacific ocean, and define a boolean matrix $vis_1$ to record which cells can flow to the Pacific ocean. Similarly, we define queue $q_2$ and boolean matrix $vis_2$ to handle the Atlantic ocean. Initially, we add all cells adjacent to the Pacific ocean to queue $q_1$ and mark them as visited in $vis_1$. Similarly, we add all cells adjacent to the Atlantic ocean to queue $q_2$ and mark them as visited in $vis_2$.\n\nThen, we perform BFS on $q_1$ and $q_2$ respectively. In each BFS, we dequeue a cell $(x, y)$ from the queue and check its four adjacent cells $(nx, ny)$. If an adjacent cell is within the matrix bounds, has not been visited, and its height is not less than the current cell's height (i.e., water can flow to that cell), we add it to the queue and mark it as visited.\n\nFinally, we traverse the entire matrix to find cells that are marked as visited in both $vis_1$ and $vis_2$. These cells are our answer.\n\nThe time complexity is $O(m \\times n)$ and the space complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns in the matrix, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 418, "explanations": { "1": "我们将句子的每个单词拼接上一个空格,然后把句子拼接起来,得到字符串 $s$。例如,对于句子 `[\"hello\", \"world\"]`,得到的字符串为 `\"hello world \"`。记 $s$ 的长度为 $m$。\n\n接下来,我们使用贪心的方法,找到最大的可显示句子数。定义一个变量 $cur$,表示当前已经在屏幕上显示的字符串的长度,初始时 $cur=0$。\n\n我们循环 $rows$ 次,每次循环中,我们首先将 $cur$ 增加 $cols$,如果 $s[cur \\bmod m]$ 是一个空格,说明我们可以将完整的若干个单词放置到当前行,因此我们将 $cur$ 增加一个额外的 $1$;否则,说明我们需要回退 $cur$,直到 $cur$ 指向的字符是一个空格为止。然后继续下一次循环。\n\n循环结束,返回 $\\lfloor \\frac{cur}{m} \\rfloor$ 即可。\n\n时间复杂度 $O(rows \\times M)$,空间复杂度 $O(L)$。其中 $M$ 是单词的最大长度,而 $L$ 是单词的总长度。" }, "is_english": false, "time_complexity": "O(rows \\times M)", "space_complexity": "O(L)" }, { "problem_id": 419, "explanations": { "1": "We can iterate through the matrix, find the top-left corner of each battleship, i.e., the position where the current position is `X` and both the top and left are not `X`, and increment the answer by one.\n\nAfter the iteration ends, return the answer.\n\nThe time complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns of the matrix, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(1)" }, { "problem_id": 420, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 421, "explanations": { "1": "题目是求两个元素的异或最大值,可以从最高位开始考虑。\n\n我们把数组中的每个元素 $x$ 看作一个 $32$ 位的 $01$ 串,按二进制从高位到低位的顺序,插入前缀树(最低位为叶子节点)。\n\n搜索 $x$ 时,尽量走相反的 $01$ 字符指针的策略,因为异或运算的法则是相同得 $0$,不同得 $1$,所以我们尽可能往与 $x$ 当前位相反的字符方向走,才能得到能和 $x$ 产生最大异或值的结果。\n\n时间复杂度 $O(n \\times \\log M)$,空间复杂度 $O(n \\times \\log M)$,其中 $n$ 是数组 $nums$ 的长度,而 $M$ 是数组中元素的最大值。" }, "is_english": false, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(n \\times \\log M)" }, { "problem_id": 422, "explanations": { "1": "We observe that if $words[i][j] \\neq words[j][i]$, we can directly return `false`.\n\nTherefore, we only need to iterate through each row, and then check whether each row satisfies $words[i][j] = words[j][i]$. Note that if the index is out of bounds, we also directly return `false`.\n\nThe time complexity is $O(n^2)$, where $n$ is the length of `words`. The space complexity is $O(1)`." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(1)" }, { "problem_id": 423, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 424, "explanations": { "1": "We use a hash table `cnt` to count the occurrence of each character in the string, and two pointers `l` and `r` to maintain a sliding window, such that the size of the window minus the count of the most frequent character does not exceed $k$.\n\nWe iterate through the string, updating the right boundary `r` of the window each time, updating the count of characters within the window, and updating the maximum count `mx` of the characters that have appeared. When the size of the window minus `mx` is greater than $k$, we need to shrink the left boundary `l` of the window, updating the count of characters within the window, until the size of the window minus `mx` is no longer greater than $k$.\n\nFinally, the answer is $n - l$, where $n$ is the length of the string.\n\nThe time complexity is $O(n)$, and the space complexity is $O(|\\Sigma|)$. Where $n$ is the length of the string, and $|\\Sigma|$ is the size of the character set. In this problem, the character set is uppercase English letters, so $|\\Sigma| = 26$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 425, "explanations": { "1": "根据已添加单词确定下一个单词的前缀,继续进行搜索。\n\n比如已经添加了两个单词 $ball$ 和 $area$,要添加下一个单词,我们首先要获取下一个单词的前缀,第一个字母是第一个单词的第三个位置 $l$,第二个字母是第二个单词的第三个位置 $e$,这样就构成了前缀 $le$。然后找出所有前缀为 $le$ 的单词,作为下一个单词。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 426, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 427, "explanations": { "1": "DFS 递归遍历 grid,先判断 grid 是否为叶子节点,是则返回叶子节点相关信息;否则递归 grid 4 个子节点。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 428, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 429, "explanations": { "1": "First, we check if the root node is null. If it is, we return an empty list directly.\n\nOtherwise, we create a queue $q$ and initially add the root node to the queue.\n\nWhen the queue is not empty, we loop through the following operations:\n\n1. Create an empty list $t$ to store the values of the current level nodes.\n2. For each node in the queue, add its value to $t$ and add its child nodes to the queue.\n3. Add $t$ to the result list $ans$.\n\nFinally, return the result list $ans$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the N-ary tree.", "2": "We can use the Depth-First Search method to traverse the entire tree.\n\nWe define a helper function $dfs(root, i)$, where $root$ represents the current node, and $i$ represents the current level.\n\nIn the $dfs$ function, we first check if $root$ is null. If it is, we return directly.\n\nOtherwise, we check if the length of $ans$ is less than or equal to $i$. If it is, it means that the current level has not been added to $ans$ yet, so we need to add an empty list first. Then we add the value of $root$ to $ans[i]$.\n\nNext, we traverse all child nodes of $root$. For each child node, we call $dfs(child, i + 1)$.\n\nIn the main function, we call $dfs(root, 0)$ and return $ans$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the N-ary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 430, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 431, "explanations": { "1": "We can point the left pointer of the binary tree to the first child of the N-ary tree and the right pointer of the binary tree to the next sibling node of the N-ary tree.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the N-ary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 432, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 433, "explanations": { "1": "We define a queue `q` to store the current gene sequence and the number of changes, and a set `vis` to store the visited gene sequences. Initially, we add the starting gene sequence `start` to the queue `q` and the set `vis`.\n\nThen, we continuously take out a gene sequence from the queue `q`. If this gene sequence equals the target gene sequence, we return the current number of changes. Otherwise, we iterate through the gene bank `bank`, calculate the difference value between the current gene sequence and the gene sequence in the gene bank. If the difference value is $1$ and the gene sequence in the gene bank has not been visited, we add it to the queue `q` and the set `vis`.\n\nIf the queue `q` is empty, it means that the gene change cannot be completed, so we return $-1$.\n\nThe time complexity is $O(C \\times n \\times m)$, and the space complexity is $O(n \\times m)$. Where $n$ and $m$ are the lengths of the gene sequence and the gene bank respectively, and $C$ is the size of the character set of the gene sequence. In this problem, $C = 4$." }, "is_english": true, "time_complexity": "O(C \\times n \\times m)", "space_complexity": "O(n \\times m)" }, { "problem_id": 434, "explanations": { "1": "We split the string $\\textit{s}$ by spaces and then count the number of non-empty words.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the string $\\textit{s}$.", "2": "We can also directly traverse each character $\\text{s[i]}$ in the string. If $\\text{s[i]}$ is not a space and $\\text{s[i-1]}$ is a space or $i = 0$, then $\\text{s[i]}$ marks the beginning of a new word, and we increment the answer by one.\n\nAfter the traversal, we return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $\\textit{s}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 435, "explanations": { "1": "We first sort the intervals in ascending order by their right boundary. We use a variable $\\textit{pre}$ to record the right boundary of the previous interval and a variable $\\textit{ans}$ to record the number of intervals that need to be removed. Initially, $\\textit{ans} = \\textit{intervals.length}$.\n\nThen we iterate through the intervals. For each interval:\n\n- If the left boundary of the current interval is greater than or equal to $\\textit{pre}$, it means that this interval does not need to be removed. We directly update $\\textit{pre}$ to the right boundary of the current interval and decrement $\\textit{ans}$ by one;\n- Otherwise, it means that this interval needs to be removed, and we do not need to update $\\textit{pre}$ and $\\textit{ans}$.\n\nFinally, we return $\\textit{ans}$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$, where $n$ is the number of intervals." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 436, "explanations": { "1": "We can store the start point and index of each interval into an array `arr`, and sort it by the start point. Then we iterate through the interval array, for each interval `[_, ed]`, we can use binary search to find the first interval whose start point is greater than or equal to `ed`, which is its right-side interval. If found, we store its index into the answer array, otherwise, we store `-1`.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the intervals." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 437, "explanations": { "1": "We can use the idea of prefix sums to recursively traverse the binary tree while using a hash table $\\textit{cnt}$ to count the occurrences of each prefix sum along the path from the root to the current node.\n\nWe design a recursive function $\\textit{dfs(node, s)}$, where $\\textit{node}$ represents the current node being traversed, and $s$ represents the prefix sum along the path from the root to the current node. The return value of the function is the number of paths ending at $\\textit{node}$ or its subtree nodes with a sum equal to $\\textit{targetSum}$. The final answer is $\\textit{dfs(root, 0)}$.\n\nThe recursive process of $\\textit{dfs(node, s)}$ is as follows:\n\n- If the current node $\\textit{node}$ is null, return $0$.\n- Calculate the prefix sum $s$ along the path from the root to the current node.\n- Use $\\textit{cnt}[s - \\textit{targetSum}]$ to represent the number of paths ending at the current node with a sum equal to $\\textit{targetSum}$. Here, $\\textit{cnt}[s - \\textit{targetSum}]$ is the count of prefix sums equal to $s - \\textit{targetSum}$ in $\\textit{cnt}$.\n- Increment the count of the prefix sum $s$ by $1$, i.e., $\\textit{cnt}[s] = \\textit{cnt}[s] + 1$.\n- Recursively traverse the left and right child nodes of the current node by calling $\\textit{dfs(node.left, s)}$ and $\\textit{dfs(node.right, s)}$, and add their return values.\n- After the return value is calculated, decrement the count of the prefix sum $s$ by $1$, i.e., $\\textit{cnt}[s] = \\textit{cnt}[s] - 1$.\n- Finally, return the result.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 438, "explanations": { "1": "我们不妨设字符串 $s$ 的长度为 $m$,字符串 $p$ 的长度为 $n$。\n\n如果 $m \\lt n$,那么 $s$ 中不可能存在任何一个子串同 $p$ 为异位词,返回空列表即可。\n\n当 $m \\ge n$ 时,我们可以使用一个固定长度为 $n$ 的滑动窗口来维护 $s$ 的子串。为了判断子串是否为 $p$ 的异位词,我们可以用一个固定长度为 $26$ 的数组 $cnt1$ 记录 $p$ 中每个字母的出现次数,再用另一个数组 $cnt2$ 记录当前滑动窗口中每个字母的出现次数,如果这两个数组相同,那么当前滑动窗口的子串就是 $p$ 的异位词,我们记录下起始位置。\n\n时间复杂度 $O(m \\times C)$,空间复杂度 $O(C)$。其中 $m$ 是字符串 $s$ 的长度;而 $C$ 是字符集大小,在本题中字符集为所有小写字母,所以 $C = 26$。", "2": "我们可以对方法一进行优化,与方法一类似,我们用一个固定长度为 $26$ 的数组 $cnt1$ 记录 $p$ 中每个字母的出现次数,用另一个数组 $cnt2$ 记录当前滑动窗口中每个字母的出现次数,用指针 $i$ 和 $j$ 分别指向滑动窗口的左右边界。每一次移动指针 $j$,将 $cnt2[s[j]]$ 的值加 $1$,如果当前 $cnt2[s[j]]$ 的值大于 $cnt1[s[j]]$,则将指针 $i$ 不断右移,直到 $cnt2[s[j]]$ 的值不大于 $cnt1[s[j]]$。此时,如果滑动窗口的长度等于 $p$ 的长度,我们就找到了一个异位词,将起始位置加入答案。继续移动指针 $j$,重复上述操作,直到指针 $j$ 移动到 $s$ 的末尾。\n\n时间复杂度 $(m + n)$,空间复杂度 $O(C)$。其中 $m$ 和 $n$ 分别是字符串 $s$ 和 $p$ 的长度;而 $C$ 是字符集大小,在本题中字符集为所有小写字母,所以 $C = 26$。" }, "is_english": false, "time_complexity": "O(m \\times C)", "space_complexity": "O(C)" }, { "problem_id": 439, "explanations": { "1": "我们从右到左遍历字符串 `expression`,对于当前遍历到的字符 $c$:\n\n- 如果 $c$ 是字符 `':'`,则跳过;\n- 如果 $c$ 是字符 `'?'`,那么意味着下一个即将遍历到的字符是条件表达式的条件,我们用一个布尔变量 `cond` 标记;\n- 如果 $c$ 的上一个遍历到的字符是 `'?'`,也即布尔变量 `cond` 为 `true`,那么我们判断当前字符 $c$ 是否为字符 `'T'`,如果是,那么我们要保留栈顶第一个元素,弹出栈顶第二个元素;否则,我们要保留栈顶第二个元素,弹出栈顶第一个元素。最后,将 `cond` 置为 `false`;\n- 否则,我们将当前字符 $c$ 入栈。\n\n最后,栈中只剩下一个元素,即为表达式的结果。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为字符串 `expression` 的长度。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 440, "explanations": { "1": "The problem asks for the \\$k\\$-th smallest number in the range $[1, n]$ when all numbers are sorted in **lexicographical order**. Since $n$ can be as large as $10^9$, we cannot afford to generate and sort all the numbers explicitly. Instead, we adopt a strategy based on **greedy traversal over a conceptual Trie**.\n\nWe treat the range $[1, n]$ as a **10-ary prefix tree (Trie)**:\n\n- Each node represents a numeric prefix, starting from an empty root;\n- Each node has 10 children, corresponding to appending digits $0 \\sim 9$;\n- For example, prefix $1$ has children $10, 11, \\ldots, 19$, and node $10$ has children $100, 101, \\ldots, 109$;\n- This tree naturally reflects lexicographical order traversal.\n\n```\nroot\n├── 1\n│ ├── 10\n│ ├── 11\n│ ├── ...\n├── 2\n├── ...\n```\n\nWe use a variable $\\textit{curr}$ to denote the current prefix, initialized as $1$. At each step, we try to expand or skip prefixes until we find the \\$k\\$-th smallest number.\n\nAt each step, we calculate how many valid numbers (i.e., numbers $\\le n$ with prefix $\\textit{curr}$) exist under this prefix subtree. Let this count be $\\textit{count}(\\text{curr})$:\n\n- If $k \\ge \\text{count}(\\text{curr})$: the target number is not in this subtree. We skip the entire subtree by moving to the next sibling:\n\n $$\n \\textit{curr} \\leftarrow \\textit{curr} + 1,\\quad k \\leftarrow k - \\text{count}(\\text{curr})\n $$\n\n- Otherwise: the target is within this subtree. We go one level deeper:\n\n $$\n \\textit{curr} \\leftarrow \\textit{curr} \\times 10,\\quad k \\leftarrow k - 1\n $$\n\nAt each level, we enlarge the current range by multiplying by 10 and continue descending until we exceed $n$.\n\nThe time complexity is $O(\\log^2 n)$, as we perform logarithmic operations for counting and traversing the Trie structure. The space complexity is $O(1)$ since we only use a few variables to track the current prefix and count." }, "is_english": true, "time_complexity": "O(\\log^2 n)", "space_complexity": "O(1)" }, { "problem_id": 441, "explanations": { "1": "`(1 + x) * x / 2 <= n`,求解 x。\n\n`(x + 1/2)² <= 2n + 1/4`,即 `x <= sqrt(2n + 1/4) - 1/2`。\n\n由于 2n 可能溢出,故转换为 `x <= sqrt(2) * sqrt(n + 1/8) - 1/2`。", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 442, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 443, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 444, "explanations": { "1": "We can first traverse each subsequence `seq`. For each pair of adjacent elements $a$ and $b$, we establish a directed edge $a \\to b$. At the same time, we count the in-degree of each node, and finally add all nodes with an in-degree of $0$ to the queue.\n\nWhen the number of nodes in the queue is equal to $1$, we take out the head node $i$, remove $i$ from the graph, and decrease the in-degree of all adjacent nodes of $i$ by $1$. If the in-degree of the adjacent nodes becomes $0$ after decreasing, add these nodes to the queue. Repeat the above operation until the length of the queue is not $1$. At this point, check whether the queue is empty. If it is not empty, it means there are multiple shortest supersequences, return `false`; if it is empty, it means there is only one shortest supersequence, return `true`.\n\nThe time complexity is $O(n + m)$, and the space complexity is $O(n + m)$. Where $n$ and $m$ are the number of nodes and edges, respectively." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(n + m)" }, { "problem_id": 445, "explanations": { "1": "手动翻转链表 `l1` 与 `l2`,将此题转换为 [2. 两数相加](https://leetcode.cn/problems/add-two-numbers/),相加过程一致。对于最后返回的结果链表也需要进行翻转,共计三次。", "2": "我们可以使用两个栈 $s1$ 和 $s2$ 分别存储两个链表元素,然后同时遍历两个栈,并使用变量 $carry$ 表示当前是否有进位。\n\n遍历时,我们弹出对应栈的栈顶元素,计算它们与进位 $carry$ 的和,然后更新进位的值,并创建一个链表节点,插入答案链表的头部。如果两个栈都遍历结束,并且进位为 $0$ 时,遍历结束。\n\n最后我们返回答案链表的头节点即可。\n\n时间复杂度 $O(\\max(m, n))$,空间复杂度 $O(m + n)$。其中 $m$ 和 $n$ 分别为两个链表的长度。" }, "is_english": false, "time_complexity": "O(\\max(m, n))", "space_complexity": "O(m + n)" }, { "problem_id": 446, "explanations": { "1": "我们定义 $f[i][d]$ 表示以 $nums[i]$ 为结尾,公差为 $d$ 的弱等差子序列(最少有两个元素)的个数。由于 $d$ 的范围很大,所以我们使用哈希表来统计。\n\n接下来,我们枚举 $nums$ 中的所有元素对 $(nums[i], nums[j])$,其中 $j \\lt i$。我们将其作为等差数列的最后两个元素,由此即可得到公差 $d = nums[i] - nums[j]$。由于公差相同,我们可以将 $nums[i]$ 加到以 $nums[j]$ 为结尾的弱等差子序列的末尾,此时以 $nums[i]$ 为结尾的等差子序列的数量为 $f[j][d]$,我们将其加入答案。然后,我们再将 $nums[i]$ 加到以 $nums[j]$ 为结尾的弱等差子序列的末尾,这对应着状态转移 $f[i][d] += f[j][d]$。同时,$(nums[i], nums[j])$ 这一对元素也可以当作一个弱等差子序列,因此有状态转移 $f[i][d] += f[j][d] + 1$。\n\n枚举结束,返回答案即可。\n\n时间复杂度 $O(n^2)$,空间复杂度 $O(n^2)$。其中 $n$ 是数组 $nums$ 的长度。" }, "is_english": false, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 447, "explanations": { "1": "We can enumerate each point in `points` as the boomerang's point $i$, and then use a hash table $cnt$ to record the number of times the distance from other points to $i$ appears.\n\nIf there are $x$ points with equal distance to $i$, then we can arbitrarily select two of them as the boomerang's $j$ and $k$. The number of schemes is $A_x^2 = x \\times (x - 1)$. Therefore, for each value $x$ in the hash table, we calculate and accumulate $A_x^2$, which gives us the total number of boomerangs that meet the problem's requirements.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$, where $n$ is the length of the array `points`.", "2": "" }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 448, "explanations": { "1": "我们可以使用数组或哈希表记录数组中的数字,然后遍历 `[1, n]` 区间内的数字,若数字不存在于数组或哈希表中,则说明数组中缺失该数字,将其添加到结果列表中。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组长度。", "2": "我们可以遍历数组 $nums$,将 $|nums[i]|-1$ 位置的数字标记为负数,表示数组 $nums[i]$ 出现过。最后遍历数组 $nums$,若 $nums[i]$ 为正数,则说明数组中缺失 $i+1$,将其添加到结果列表中。\n\n遍历结束后,返回结果列表即可。\n\n时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组长度。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 449, "explanations": { "1": "题目给定的是二叉搜索树,我们知道二叉搜索树的中序遍历是有序的,而通过“先序遍历”和“中序遍历”可以唯一确定一棵二叉树,所以我们可以通过先序遍历的结果和中序遍历的结果来唯一确定一棵二叉搜索树。\n\n在 `serialize` 方法中,我们使用先序遍历的方式将二叉搜索树序列化为空格分隔的字符串,然后在 `deserialize` 方法中,我们将字符串按空格分割为数组,然后使用递归的方式来构建二叉搜索树。递归函数为 $dfs(mi, mx)$,表示当前节点的值必须在 $[mi, mx]$ 之间,如果当前节点的值不在 $[mi, mx]$ 之间,则说明这个节点不是当前递归树的节点,返回 `None`。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉搜索树的节点数。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 450, "explanations": { "1": "二叉搜索树有以下性质:\n\n1. 若任意节点的左子树不空,则左子树上所有节点的值均小于它的根节点的值;\n1. 若任意节点的右子树不空,则右子树上所有节点的值均大于它的根节点的值;\n1. 任意节点的左、右子树也分别为二叉搜索树。\n\n我们可以递归判断当前节点 $root$ 与 $key$ 的大小关系:\n\n1. 若 $root.val>key$,则递归左子树;\n1. 若 $root.vals$,说明第 $i$ 个火柴棒不能被添加到当前子集中,由于我们对 $matchsticks$ 数组进行升序排列,因此从 $matchsticks$ 从第 $i$ 个火柴棒开始的所有数字都不能被添加到当前子集,直接返回 $false$。\n- 否则,将第 $i$ 个火柴棒添加到当前子集中,状态变为 $state \\ |\\ (1<0$。\n\n当 $m=1$ 时,上式 $n=k^0+k^1=1+k$,即 $k=n-1>=2$。\n\n我们来证明一般情况下的两个结论,以帮助解决本题。\n\n**结论一:** $m<\\log _{k} n$\n\n注意到式子 ① 是个首项为 $1$,且公比为 $k$ 的等比数列。利用等比数列求和公式,我们可以得出:\n\n$$\nn=\\frac{1-k^{m+1}}{1-k}\n$$\n\n变形得:\n\n$$\nk^{m+1}=k \\times n-n+1 < k \\times n\n$$\n\n移项得:\n\n$$\nm<\\log _{k} n\n$$\n\n题目 $n$ 取值范围为 $[3, 10^{18}]$,又因为 $k>=2$,因此 $m<\\log _{k} n<\\log _{2} 10^{18}<60$。\n\n**结论二:** $k=\\left \\lfloor \\sqrt[m]{n} \\right \\rfloor $\n\n$$\nn=k^0+k^1+k^2+...+k^m>k^m\n$$\n\n根据二项式定理:\n\n$$\n(a+b)^{n}=\\sum_{k=0}^{n}\\left(\\begin{array}{l}\nn \\\\\nk\n\\end{array}\\right) a^{n-k} b^{k}\n$$\n\n整合,可得:\n\n$$\n(k+1)^{m}=\\left(\\begin{array}{c}\nm \\\\\n0\n\\end{array}\\right) k^{0}+\\left(\\begin{array}{c}\nm \\\\\n1\n\\end{array}\\right) k^{1}+\\left(\\begin{array}{c}\nm \\\\\n2\n\\end{array}\\right) k^{2}+\\cdots+\\left(\\begin{array}{c}\nm \\\\\nm\n\\end{array}\\right) k^{m}\n$$\n\n当 $m>1$ 时,满足:\n\n$$\n\\forall i \\in[1, m-1],\\left(\\begin{array}{c}\nm \\\\\ni\n\\end{array}\\right)>1\n$$\n\n所以有:\n\n$$\n\\begin{aligned}\n(k+1)^{m} &=\\left(\\begin{array}{c}\nm \\\\\n0\n\\end{array}\\right) k^{0}+\\left(\\begin{array}{c}\nm \\\\\n1\n\\end{array}\\right) k^{1}+\\left(\\begin{array}{c}\nm \\\\\n2\n\\end{array}\\right) k^{2}+\\cdots+\\left(\\begin{array}{c}\nm \\\\\nm\n\\end{array}\\right) k^{m} \\\\\n&>k^{0}+k^{1}+k^{2}+\\cdots+k^{m}=n\n\\end{aligned}\n$$\n\n即:\n\n$$\nk < \\sqrt[m]{n} < k+1\n$$\n\n由于 $k$ 是整数,因此 $k=\\left \\lfloor \\sqrt[m]{n} \\right \\rfloor $。\n\n综上,依据结论一,我们知道 $m$ 的取值范围为 $[1,log_{k}n)$,且 $m=1$ 时必然有解。随着 $m$ 的增大,进制 $k$ 不断减小。所以我们只需要从大到小检查每一个 $m$ 可能的取值,利用结论二快速算出对应的 $k$ 值,然后校验计算出的 $k$ 值是否有效即可。如果 $k$ 值有效,我们即可返回结果。\n\n时间复杂度 $O(log^{2}n)$。" }, "is_english": false, "time_complexity": "O(log^{2}n)", "space_complexity": null }, { "problem_id": 484, "explanations": { "1": "先初始化结果数组 `ans` 为 `[1, 2, 3, ..., n+1]`。\n\n假定某个连续 `D` 子数组区间为 `[i, j)`,那么只要翻转 `ans[i: j + 1]` 即可。\n\n因此,遍历字符串 `s`,找出所有的连续 `D` 子数组区间,将其翻转。\n\n时间复杂度 $O(n)$,其中 $n$ 表示字符串 `s` 的长度。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": null }, { "problem_id": 485, "explanations": { "1": "We can iterate through the array, using a variable $\\textit{cnt}$ to record the current number of consecutive 1s, and another variable $\\textit{ans}$ to record the maximum number of consecutive 1s.\n\nWhen we encounter a 1, we increment $\\textit{cnt}$ by one, and then update $\\textit{ans}$ to be the maximum of $\\textit{cnt}$ and $\\textit{ans}$ itself, i.e., $\\textit{ans} = \\max(\\textit{ans}, \\textit{cnt})$. Otherwise, we reset $\\textit{cnt}$ to 0.\n\nAfter the iteration ends, we return the value of $\\textit{ans}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 486, "explanations": { "1": "We design a function $\\textit{dfs}(i, j)$, which represents the maximum difference in scores between the current player and the other player from the $i$-th number to the $j$-th number. The answer is $\\textit{dfs}(0, n - 1) \\geq 0$.\n\nThe function $\\textit{dfs}(i, j)$ is calculated as follows:\n\n- If $i > j$, it means there are no numbers left, so the current player cannot take any points, and the difference is $0$, i.e., $\\textit{dfs}(i, j) = 0$.\n- Otherwise, the current player has two choices. If they choose the $i$-th number, the difference in scores between the current player and the other player is $\\textit{nums}[i] - \\textit{dfs}(i + 1, j)$. If they choose the $j$-th number, the difference in scores between the current player and the other player is $\\textit{nums}[j] - \\textit{dfs}(i, j - 1)$. The current player will choose the option with the larger difference, so $\\textit{dfs}(i, j) = \\max(\\textit{nums}[i] - \\textit{dfs}(i + 1, j), \\textit{nums}[j] - \\textit{dfs}(i, j - 1))$.\n\nFinally, we only need to check if $\\textit{dfs}(0, n - 1) \\geq 0$.\n\nTo avoid repeated calculations, we can use memoization. We use an array $f$ to record all the values of $\\textit{dfs}(i, j)$. When the function is called again, we can directly retrieve the answer from $f$ without recalculating it.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ is the length of the array $\\textit{nums}$.", "2": "We can also use dynamic programming. Define $f[i][j]$ to represent the maximum score difference the current player can achieve in the range $\\textit{nums}[i..j]$. The final answer is $f[0][n - 1] \\geq 0$.\n\nInitially, $f[i][i] = \\textit{nums}[i]$, because with only one number, the current player can only take that number, and the score difference is $\\textit{nums}[i]$.\n\nConsider $f[i][j]$ where $i < j$, there are two cases:\n\n- If the current player takes $\\textit{nums}[i]$, the remaining numbers are $\\textit{nums}[i + 1..j]$, and it is the other player's turn. So, $f[i][j] = \\textit{nums}[i] - f[i + 1][j]$.\n- If the current player takes $\\textit{nums}[j]$, the remaining numbers are $\\textit{nums}[i..j - 1]$, and it is the other player's turn. So, $f[i][j] = \\textit{nums}[j] - f[i][j - 1]$.\n\nTherefore, the state transition equation is $f[i][j] = \\max(\\textit{nums}[i] - f[i + 1][j], \\textit{nums}[j] - f[i][j - 1])$.\n\nFinally, we only need to check if $f[0][n - 1] \\geq 0$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ is the length of the array $\\textit{nums}$.\n\nSimilar problem:\n\n- [877. Stone Game](https://github.com/doocs/leetcode/blob/main/solution/0800-0899/0877.Stone%20Game/README_EN.md)" }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 487, "explanations": { "1": "We can iterate through the array, using a variable $\\textit{cnt}$ to record the current number of 0s in the window. When $\\textit{cnt} > 1$, we move the left boundary of the window to the right by one position.\n\nAfter the iteration ends, the length of the window is the maximum number of consecutive 1s.\n\nNote that in the process above, we do not need to loop to move the left boundary of the window to the right. Instead, we directly move the left boundary to the right by one position. This is because the problem asks for the maximum number of consecutive 1s, so the length of the window will only increase, not decrease. Therefore, we do not need to loop to move the left boundary to the right.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 488, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 489, "explanations": { "1": "我们不妨假设机器人的初始位置为 $(0, 0)$,方向为 $d=0$。我们将初始位置进行打扫,并标记为已访问。然后,我们依次选择上、右、下、左四个方向进行探索,每次探索前都先判断是否已经访问过,如果没有访问过,我们就朝着该方向前进一步,然后递归探索。如果已经访问过,我们就顺时针旋转 $90^\\circ$,然后继续探索下一个方向。当我们探索完所有的方向后,我们需要回到上一个位置,这时我们只需要顺时针旋转 $180^\\circ$,然后前进一步,再顺时针旋转 $180^\\circ$ 即可。\n\n时间复杂度 $O(4^{n-m})$,空间复杂度 $O(n-m)$。其中 $n$ 和 $m$ 分别是房间的数量以及障碍物的数量。" }, "is_english": false, "time_complexity": "O(4^{n-m})", "space_complexity": "O(n-m)" }, { "problem_id": 490, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 491, "explanations": { "1": "DFS 递归枚举每个数字选中或不选中,这里需要满足两个条件:\n\n1. 子序列需要递增(非严格递增),因此序列的后一个数要大于等于前一个数;\n1. 子序列需要去重,这里重复的问题在于前后两个数相等并且不选中的情况,我们只在前后两个数不等的情况下,执行不选中的操作即可达到去重的效果。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 492, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 493, "explanations": { "1": "归并排序的过程中,如果左边的数大于右边的数,则右边的数与左边的数之后的数都构成逆序对。\n\n时间复杂度 $O(n \\times \\log n)$,空间复杂度 $O(n)$。其中 $n$ 为数组长度。", "2": "树状数组,也称作“二叉索引树”(Binary Indexed Tree)或 Fenwick 树。 它可以高效地实现如下两个操作:\n\n1. **单点更新** `update(x, delta)`: 把序列 x 位置的数加上一个值 delta;\n1. **前缀和查询** `query(x)`:查询序列 `[1,...x]` 区间的区间和,即位置 x 的前缀和。\n\n这两个操作的时间复杂度均为 $O(\\log n)$。\n\n树状数组最基本的功能就是求比某点 x 小的点的个数(这里的比较是抽象的概念,可以是数的大小、坐标的大小、质量的大小等等)。\n\n比如给定数组 `a[5] = {2, 5, 3, 4, 1}`,求 `b[i] = 位置 i 左边小于等于 a[i] 的数的个数`。对于此例,`b[5] = {0, 1, 1, 2, 0}`。\n\n解决方案是直接遍历数组,每个位置先求出 `query(a[i])`,然后再修改树状数组 `update(a[i], 1)` 即可。当数的范围比较大时,需要进行离散化,即先进行去重并排序,然后对每个数字进行编号。", "3": "线段树将整个区间分割为多个不连续的子区间,子区间的数量不超过 `log(width)`。更新某个元素的值,只需要更新 `log(width)` 个区间,并且这些区间都包含在一个包含该元素的大区间内。\n\n- 线段树的每个节点代表一个区间;\n- 线段树具有唯一的根节点,代表的区间是整个统计范围,如 `[1, N]`;\n- 线段树的每个叶子节点代表一个长度为 1 的元区间 `[x, x]`;\n- 对于每个内部节点 `[l, r]`,它的左儿子是 `[l, mid]`,右儿子是 `[mid + 1, r]`, 其中 `mid = ⌊(l + r) / 2⌋` (即向下取整)。" }, "is_english": false, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 494, "explanations": { "1": "Let's denote the sum of all elements in the array $\\textit{nums}$ as $s$, and the sum of elements to which we assign a negative sign as $x$. Therefore, the sum of elements with a positive sign is $s - x$. We have:\n\n$$\n(s - x) - x = \\textit{target} \\Rightarrow x = \\frac{s - \\textit{target}}{2}\n$$\n\nSince $x \\geq 0$ and $x$ must be an integer, it follows that $s \\geq \\textit{target}$ and $s - \\textit{target}$ must be even. If these two conditions are not met, we directly return $0$.\n\nNext, we can transform the problem into: selecting several elements from the array $\\textit{nums}$ such that the sum of these elements equals $\\frac{s - \\textit{target}}{2}$. We are asked how many ways there are to make such a selection.\n\nWe can use dynamic programming to solve this problem. Define $f[i][j]$ as the number of ways to select several elements from the first $i$ elements of the array $\\textit{nums}$ such that the sum of these elements equals $j$.\n\nFor $\\textit{nums}[i - 1]$, we have two choices: to select or not to select. If we do not select $\\textit{nums}[i - 1]$, then $f[i][j] = f[i - 1][j]$; if we do select $\\textit{nums}[i - 1]$, then $f[i][j] = f[i - 1][j - \\textit{nums}[i - 1]]$. Therefore, the state transition equation is:\n\n$$\nf[i][j] = f[i - 1][j] + f[i - 1][j - \\textit{nums}[i - 1]]\n$$\n\nThis selection is based on the premise that $j \\geq \\textit{nums}[i - 1]$.\n\nThe final answer is $f[m][n]$, where $m$ is the length of the array $\\textit{nums}$, and $n = \\frac{s - \\textit{target}}{2}$.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$.", "2": "We can observe that in the state transition equation of Solution 1, the value of $f[i][j]$ is only related to $f[i - 1][j]$ and $f[i - 1][j - \\textit{nums}[i - 1]]$. Therefore, we can eliminate the first dimension of the space and use only a one-dimensional array.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(n)$." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 495, "explanations": { "1": "我们先考虑最后一次攻击,此次攻击一定可以使得艾希处于中毒状态,所以总中毒时间至少为 `duration`。\n\n接下来,我们考虑前 $n-1$ 次攻击,每一次攻击的中毒持续时间为 $min(duration, timeSeries[i] - timeSeries[i-1])$,其中 $i$ 从 1 开始。我们将这些中毒持续时间累加起来,即为总中毒时间。\n\n时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 `timeSeries` 的长度。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 496, "explanations": { "1": "We can traverse the array $\\textit{nums2}$ from right to left, maintaining a stack $\\textit{stk}$ that is monotonically increasing from top to bottom. We use a hash table $\\textit{d}$ to record the next greater element for each element.\n\nWhen we encounter an element $x$, if the stack is not empty and the top element of the stack is less than $x$, we keep popping the top elements until the stack is empty or the top element is greater than or equal to $x$. At this point, if the stack is not empty, the top element of the stack is the next greater element for $x$. Otherwise, $x$ has no next greater element.\n\nFinally, we traverse the array $\\textit{nums1}$ and use the hash table $\\textit{d}$ to get the answer.\n\nThe time complexity is $O(m + n)$, and the space complexity is $O(n)$. Here, $m$ and $n$ are the lengths of the arrays $\\textit{nums1}$ and $\\textit{nums2}$, respectively." }, "is_english": true, "time_complexity": "O(m + n)", "space_complexity": "O(n)" }, { "problem_id": 497, "explanations": { "1": "将矩形面积求前缀和 $s$,然后随机获取到一个面积 $v$,利用二分查找定位到是哪个矩形,然后继续随机获取该矩形的其中一个整数点坐标即可。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 498, "explanations": { "1": "For each round $k$, we fix the starting point from the top-right and traverse diagonally to the bottom-left to get $t$. If $k$ is even, we reverse $t$.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(1)$. Ignoring the space used for the answer." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(1)" }, { "problem_id": 499, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 500, "explanations": { "1": "我们将每个键盘行的字符映射到对应的行数,然后遍历字符串数组,判断每个字符串是否都在同一行即可。\n\n时间复杂度 $O(L)$,空间复杂度 $O(C)$。其中 $L$ 为所有字符串的长度之和;而 $C$ 为字符集的大小,本题中 $C = 26$。", "2": "" }, "is_english": false, "time_complexity": "O(L)", "space_complexity": "O(C)" }, { "problem_id": 501, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 502, "explanations": { "1": "将每个项目放入优先队列 $q_1$ 中,按照启动资本从小到大排序。如果堆顶元素启动资本不超过当前已有的资金,则循环弹出,放入另一个优先队列 $q_2$ 中,按照纯利润从大到小排序。取出当前利润最大的项目,将其纯利润加入到当前资金中,重复上述操作 $k$ 次。\n\n时间复杂度 $O(n\\log n)$,空间复杂度 $O(n)$。其中 $n$ 为项目数。" }, "is_english": false, "time_complexity": "O(n\\log n)", "space_complexity": "O(n)" }, { "problem_id": 503, "explanations": { "1": "The problem requires us to find the next greater element for each element. Therefore, we can traverse the array from back to front, which effectively turns the problem into finding the previous greater element. Additionally, since the array is circular, we can traverse the array twice.\n\nSpecifically, we start traversing the array from index $n \\times 2 - 1$, where $n$ is the length of the array. Then, we let $j = i \\bmod n$, where $\\bmod$ represents the modulo operation. If the stack is not empty and the top element of the stack is less than or equal to $nums[j]$, then we continuously pop the top element of the stack until the stack is empty or the top element of the stack is greater than $nums[j]$. At this point, the top element of the stack is the previous greater element for $nums[j]$, and we assign it to $ans[j]$. Finally, we push $nums[j]$ onto the stack. We continue to the next element.\n\nAfter the traversal is complete, we can obtain the array $ans$, which represents the next greater element for each element in the array $nums$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 504, "explanations": { "1": "我们不妨假设 `num` 大于等于 $0$,那么,如果 `num` 等于 $0$,只需要返回 $0$ 即可。否则,我们将 $num$ 模 $7$ 的结果保存起来,最后逆序拼接成字符串即可。\n\n时间复杂度 $O(\\log n)$,忽略答案的空间消耗,空间复杂度 $O(1)$。其中 $n$ 是 `num` 的绝对值大小。" }, "is_english": false, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 505, "explanations": { "1": "我们定义一个二维数组 $dist$,其中 $dist[i][j]$ 表示从起始位置到达 $(i,j)$ 的最短路径长度。初始时,$dist$ 中的所有元素都被初始化为一个很大的数,除了起始位置,因为起始位置到自身的距离是 $0$。\n\n然后,我们定义一个队列 $q$,将起始位置加入队列。随后不断进行以下操作:弹出队列中的首元素,将其四个方向上可以到达的位置加入队列中,并且在 $dist$ 中记录这些位置的距离,直到队列为空。\n\n最后,如果终点位置的距离仍然是一个很大的数,说明从起始位置无法到达终点位置,返回 $-1$,否则返回终点位置的距离。\n\n时间复杂度 $O(m \\times n \\times \\max(m, n))$,空间复杂度 $O(m \\times n)$。其中 $m$ 和 $n$ 分别是迷宫的行数和列数。" }, "is_english": false, "time_complexity": "O(m \\times n \\times \\max(m, n))", "space_complexity": "O(m \\times n)" }, { "problem_id": 506, "explanations": { "1": "We use an array $\\textit{idx}$ to store the indices from $0$ to $n-1$, then sort $\\textit{idx}$ based on the values in $\\textit{score}$ in descending order.\n\nNext, we define an array $\\textit{top3} = [\\text{Gold Medal}, \\text{Silver Medal}, \\text{Bronze Medal}]$. We traverse $\\textit{idx}$, and for each index $j$, if $j$ is less than $3$, then $\\textit{ans}[j]$ is $\\textit{top3}[j]$; otherwise, it is $j+1$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{score}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 507, "explanations": { "1": "First, we check if $\\textit{num}$ is 1. If it is, then $\\textit{num}$ is not a perfect number, and we return $\\text{false}$.\n\nNext, we enumerate all positive divisors of $\\textit{num}$ starting from 2. If $\\textit{num}$ is divisible by a positive divisor $i$, we add $i$ to the sum $\\textit{s}$. If the quotient of $\\textit{num}$ divided by $i$ is not equal to $i$, we also add the quotient to the sum $\\textit{s}$.\n\nFinally, we check if $\\textit{s}$ is equal to $\\textit{num}$.\n\nThe time complexity is $O(\\sqrt{n})$, where $n$ is the value of $\\textit{num}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\sqrt{n})", "space_complexity": "O(1)" }, { "problem_id": 508, "explanations": { "1": "We can use a hash table $\\textit{cnt}$ to record the frequency of each subtree sum. Then, we use depth-first search (DFS) to traverse the entire tree, calculate the sum of elements for each subtree, and update $\\textit{cnt}$.\n\nFinally, we traverse $\\textit{cnt}$ to find all subtree sums that appear most frequently.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 509, "explanations": { "1": "We define two variables $a$ and $b$, initially $a = 0$ and $b = 1$.\n\nNext, we perform $n$ iterations. In each iteration, we update the values of $a$ and $b$ to $b$ and $a + b$, respectively.\n\nFinally, we return $a$.\n\nThe time complexity is $O(n)$, where $n$ is the given integer. The space complexity is $O(1)$.", "2": "We define $\\textit{Fib}(n)$ as a $1 \\times 2$ matrix $\\begin{bmatrix} F_n & F_{n - 1} \\end{bmatrix}$, where $F_n$ and $F_{n - 1}$ are the $n$-th and $(n - 1)$-th Fibonacci numbers, respectively.\n\nWe want to derive $\\textit{Fib}(n)$ from $\\textit{Fib}(n - 1) = \\begin{bmatrix} F_{n - 1} & F_{n - 2} \\end{bmatrix}$. In other words, we need a matrix $\\textit{base}$ such that $\\textit{Fib}(n - 1) \\times \\textit{base} = \\textit{Fib}(n)$, i.e.:\n\n$$\n\\begin{bmatrix}\nF_{n - 1} & F_{n - 2}\n\\end{bmatrix} \\times \\textit{base} = \\begin{bmatrix} F_n & F_{n - 1} \\end{bmatrix}\n$$\n\nSince $F_n = F_{n - 1} + F_{n - 2}$, the first column of the matrix $\\textit{base}$ is:\n\n$$\n\\begin{bmatrix}\n1 \\\\\n1\n\\end{bmatrix}\n$$\n\nThe second column is:\n\n$$\n\\begin{bmatrix}\n1 \\\\\n0\n\\end{bmatrix}\n$$\n\nThus, we have:\n\n$$\n\\begin{bmatrix} F_{n - 1} & F_{n - 2} \\end{bmatrix} \\times \\begin{bmatrix}1 & 1 \\\\ 1 & 0\\end{bmatrix} = \\begin{bmatrix} F_n & F_{n - 1} \\end{bmatrix}\n$$\n\nWe define the initial matrix $res = \\begin{bmatrix} 1 & 0 \\end{bmatrix}$, then $F_n$ is equal to the second element of the first row of the result matrix obtained by multiplying $res$ with $\\textit{base}^{n}$. We can solve this using matrix exponentiation.\n\nThe time complexity is $O(\\log n)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 510, "explanations": { "1": "If the `node` has a right subtree, then the in-order successor of `node` is the leftmost node in the right subtree.\n\nIf the `node` does not have a right subtree, then if `node` is the right child of its parent, we continue to search upwards until the parent of the node is null, or the node is the left child of its parent. In this case, the parent node is the in-order successor.\n\nThe time complexity is $O(h)$, where $h$ is the height of the binary tree. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(h)", "space_complexity": "O(1)" }, { "problem_id": 511, "explanations": { "1": "We can use `GROUP BY` to group the `player_id` and then take the minimum `event_date` in each group as the date when the player first logged into the platform." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 512, "explanations": { "1": "We can use `GROUP BY` and `MIN` functions to find the first login date for each player, and then use a subquery with a composite key to find the first login device for each player.", "2": "We can use the window function `rank()`, which assigns a rank to each login date for each player, and then select the rows with a rank of $1$." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 513, "explanations": { "1": "BFS 找最后一层第一个节点。", "2": "DFS 先序遍历,找深度最大的,且第一次被遍历到的节点。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 514, "explanations": { "1": "First, we preprocess the positions of each character $c$ in the string $ring$, and record them in the array $pos[c]$. Suppose the lengths of the strings $key$ and $ring$ are $m$ and $n$, respectively.\n\nThen we define $f[i][j]$ as the minimum number of steps to spell the first $i+1$ characters of the string $key$, and the $j$-th character of $ring$ is aligned with the $12:00$ direction. Initially, $f[i][j]=+\\infty$. The answer is $\\min_{0 \\leq j < n} f[m - 1][j]$.\n\nWe can first initialize $f[0][j]$, where $j$ is the position where the character $key[0]$ appears in $ring$. Since the $j$-th character of $ring$ is aligned with the $12:00$ direction, we only need $1$ step to spell $key[0]$. In addition, we need $min(j, n - j)$ steps to rotate $ring$ to the $12:00$ direction. Therefore, $f[0][j]=min(j, n - j) + 1$.\n\nNext, we consider how the state transitions when $i \\geq 1$. We can enumerate the position list $pos[key[i]]$ where $key[i]$ appears in $ring$, and enumerate the position list $pos[key[i-1]]$ where $key[i-1]$ appears in $ring$, and then update $f[i][j]$, i.e., $f[i][j]=\\min_{k \\in pos[key[i-1]]} f[i-1][k] + \\min(\\textit{abs}(j - k), n - \\textit{abs}(j - k)) + 1$.\n\nFinally, we return $\\min_{0 \\leq j \\lt n} f[m - 1][j]$.\n\nThe time complexity is $O(m \\times n^2)$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the lengths of the strings $key$ and $ring$, respectively." }, "is_english": true, "time_complexity": "O(m \\times n^2)", "space_complexity": "O(m \\times n)" }, { "problem_id": 515, "explanations": { "1": "We define a queue $q$ and put the root node into the queue. Each time, we take out all the nodes of the current level from the queue, find the maximum value, and then put all the nodes of the next level into the queue until the queue is empty.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree.", "2": "DFS 先序遍历,找每个深度最大的节点值。" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 516, "explanations": { "1": "We define $f[i][j]$ as the length of the longest palindromic subsequence from the $i$-th character to the $j$-th character in string $s$. Initially, $f[i][i] = 1$, and the values of other positions are all $0$.\n\nIf $s[i] = s[j]$, then $f[i][j] = f[i + 1][j - 1] + 2$; otherwise, $f[i][j] = \\max(f[i + 1][j], f[i][j - 1])$.\n\nSince the value of $f[i][j]$ is related to $f[i + 1][j - 1]$, $f[i + 1][j]$, and $f[i][j - 1]$, we should enumerate $i$ from large to small, and enumerate $j$ from small to large.\n\nThe answer is $f[0][n - 1]$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Where $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 517, "explanations": { "1": "If the total number of clothes in the washing machines cannot be divided evenly by the number of washing machines, it is impossible to make the number of clothes in each washing machine equal, so we directly return $-1$.\n\nOtherwise, suppose the total number of clothes in the washing machines is $s$, then the number of clothes in each washing machine will eventually become $k = s / n$.\n\nWe define $a_i$ as the difference between the number of clothes in the $i$-th washing machine and $k$, that is, $a_i = \\textit{machines}[i] - k$. If $a_i > 0$, it means that the $i$-th washing machine has extra clothes and needs to pass them to the adjacent washing machine; if $a_i < 0$, it means that the $i$-th washing machine lacks clothes and needs to get them from the adjacent washing machine.\n\nWe define the sum of the differences in the number of clothes in the first $i$ washing machines as $s_i = \\sum_{j=0}^{i-1} a_j$. If we regard the first $i$ washing machines as one group and the remaining washing machines as another group. Then if $s_i$ is a positive number, it means that the first group of washing machines has extra clothes and needs to pass them to the second group of washing machines; if $s_i$ is a negative number, it means that the first group of washing machines lacks clothes and needs to get them from the second group of washing machines.\n\nThen there are the following two situations:\n\n1. The maximum number of times clothes need to be moved between the two groups is $\\max_{i=0}^{n-1} \\lvert s_i \\rvert$;\n1. A washing machine in the group has too many clothes and needs to move clothes to both sides, the maximum number of times clothes need to be moved is $\\max_{i=0}^{n-1} a_i$.\n\nWe take the maximum of the two.\n\nThe time complexity is $O(n)$, where $n$ is the number of washing machines. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 518, "explanations": { "1": "We define $f[i][j]$ as the number of coin combinations to make up the amount $j$ using the first $i$ types of coins. Initially, $f[0][0] = 1$, and the values of other positions are all $0$.\n\nWe can enumerate the quantity $k$ of the last coin used, then we have equation one:\n\n$$\nf[i][j] = f[i - 1][j] + f[i - 1][j - x] + f[i - 1][j - 2 \\times x] + \\cdots + f[i - 1][j - k \\times x]\n$$\n\nwhere $x$ represents the face value of the $i$-th type of coin.\n\nLet $j = j - x$, then we have equation two:\n\n$$\nf[i][j - x] = f[i - 1][j - x] + f[i - 1][j - 2 \\times x] + \\cdots + f[i - 1][j - k \\times x]\n$$\n\nSubstituting equation two into equation one, we can get the following state transition equation:\n\n$$\nf[i][j] = f[i - 1][j] + f[i][j - x]\n$$\n\nThe final answer is $f[m][n]$.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Where $m$ and $n$ are the number of types of coins and the total amount, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 519, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 520, "explanations": { "1": "We can count the number of uppercase letters in the string, and then determine whether it meets the requirements of the problem based on the number of uppercase letters.\n\n- If the number of uppercase letters is 0 or equal to the length of the string, then return `true`.\n- If the number of uppercase letters is 1 and the first letter is an uppercase letter, then return `true`.\n- Otherwise, return `false`.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string `word`. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 521, "explanations": { "1": "If strings `a` and `b` are equal, then they have no special sequences, return `-1`; otherwise, return the length of the longer string.\n\nThe time complexity is $O(n)$, where $n$ is the length of the longer string among `a` and `b`. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 522, "explanations": { "1": "We define a function $check(s, t)$ to determine whether string $s$ is a subsequence of string $t$. We can use a two-pointer approach, initializing two pointers $i$ and $j$ to point to the beginning of strings $s$ and $t$ respectively, then continuously move pointer $j$. If $s[i]$ equals $t[j]$, then move pointer $i$. Finally, check if $i$ equals the length of $s$. If $i$ equals the length of $s$, it means $s$ is a subsequence of $t$.\n\nTo determine if string $s$ is unique, we only need to take string $s$ itself and compare it with other strings in the list. If there exists a string for which $s$ is a subsequence, then $s$ is not unique. Otherwise, string $s$ is unique. We take the longest string among all unique strings.\n\nThe time complexity is $O(n^2 \\times m)$, where $n$ is the length of the list of strings, and $m$ is the average length of the strings. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n^2 \\times m)", "space_complexity": "O(1)" }, { "problem_id": 523, "explanations": { "1": "According to the problem description, if there exist two positions $i$ and $j$ ($j < i$) where the remainders of the prefix sums modulo $k$ are the same, then the sum of the subarray $\\textit{nums}[j+1..i]$ is a multiple of $k$.\n\nTherefore, we can use a hash table to store the first occurrence of each remainder of the prefix sum modulo $k$. Initially, we store a key-value pair $(0, -1)$ in the hash table, indicating that the remainder $0$ of the prefix sum $0$ appears at position $-1$.\n\nAs we iterate through the array, we calculate the current prefix sum's remainder modulo $k$. If the current prefix sum's remainder modulo $k$ has not appeared in the hash table, we store the current prefix sum's remainder modulo $k$ and its corresponding position in the hash table. Otherwise, if the current prefix sum's remainder modulo $k$ has already appeared in the hash table at position $j$, then we have found a subarray $\\textit{nums}[j+1..i]$ that meets the conditions, and thus return $\\textit{True}$.\n\nAfter completing the iteration, if no subarray meeting the conditions is found, we return $\\textit{False}$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 524, "explanations": { "1": "We define a function $check(s, t)$ to determine whether string $s$ is a subsequence of string $t$. We can use a two-pointer approach, initializing two pointers $i$ and $j$ to point to the beginning of strings $s$ and $t$ respectively, then continuously move pointer $j$. If $s[i]$ equals $t[j]$, then move pointer $i$. Finally, check if $i$ equals the length of $s$. If $i$ equals the length of $s$, it means $s$ is a subsequence of $t$.\n\nWe initialize the answer string $ans$ as an empty string. Then, we iterate through each string $t$ in the array $dictionary$. If $t$ is a subsequence of $s$, and the length of $t$ is greater than the length of $ans$, or the length of $t$ is equal to the length of $ans$ but $t$ is lexicographically smaller than $ans$, then we update $ans$ to $t$.\n\nThe time complexity is $O(d \\times (m + n))$, where $d$ is the length of the string list, and $m$ and $n$ are the lengths of string $s$ and the average length of strings in the list, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(d \\times (m + n))", "space_complexity": "O(1)" }, { "problem_id": 525, "explanations": { "1": "According to the problem description, we can treat $0$s in the array as $-1$. In this way, when encountering a $0$, the prefix sum $s$ will decrease by one, and when encountering a $1$, the prefix sum $s$ will increase by one. Therefore, suppose the prefix sum $s$ is equal at indices $j$ and $i$, where $j < i$, then the subarray from index $j + 1$ to $i$ has an equal number of $0$s and $1$s.\n\nWe use a hash table to store all prefix sums and their first occurrence indices. Initially, we map the prefix sum of $0$ to $-1$.\n\nAs we iterate through the array, we calculate the prefix sum $s$. If $s$ is already in the hash table, then we have found a subarray with a sum of $0$, and its length is $i - d[s]$, where $d[s]$ is the index where $s$ first appeared in the hash table. If $s$ is not in the hash table, we store $s$ and its index $i$ in the hash table.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 526, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 527, "explanations": { "1": "We notice that if two words have the same abbreviation, their first and last letters must be the same, and their lengths must be the same. Therefore, we can group all words by length and last letter, and use a trie to store the information of each group of words.\n\nThe structure of each node in the trie is as follows:\n\n- `children`: An array of length $26$, representing all child nodes of this node.\n- `cnt`: The number of words passing through this node.\n\nFor each word, we insert it into the trie and record the `cnt` value of each node.\n\nWhen querying, we start from the root node. For the current letter, if the `cnt` value of its corresponding child node is $1$, then we have found the unique abbreviation, and we return the length of the current prefix. Otherwise, we continue to traverse downwards. After the traversal, if we have not found a unique abbreviation, then we return the length of the original word. After getting the prefix lengths of all words, we check whether the abbreviation of the word is shorter than the original word. If it is, then we add it to the answer, otherwise we add the original word to the answer.\n\nThe time complexity is $O(L)$, and the space complexity is $O(L)$. Here, $L$ is the sum of the lengths of all words." }, "is_english": true, "time_complexity": "O(L)", "space_complexity": "O(L)" }, { "problem_id": 528, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 529, "explanations": { "1": "我们记 $click = (i, j)$,如果 $board[i][j]$ 等于 `'M'`,那么直接将 $board[i][j]$ 的值改为 `'X'` 即可。否则,我们需要统计 $board[i][j]$ 周围的地雷数量 $cnt$,如果 $cnt$ 不为 $0$,那么将 $board[i][j]$ 的值改为 $cnt$ 的字符串形式。否则,将 $board[i][j]$ 的值改为 `'B'`,并且递归地搜索处理 $board[i][j]$ 周围的未挖出的方块。\n\n时间复杂度 $O(m \\times n)$,空间复杂度 $O(m \\times n)$。其中 $m$ 和 $n$ 分别是二维数组 $board$ 的行数和列数。" }, "is_english": false, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 530, "explanations": { "1": "The problem requires us to find the minimum difference between the values of any two nodes. Since the inorder traversal of a binary search tree is an increasing sequence, we only need to find the minimum difference between the values of two adjacent nodes in the inorder traversal.\n\nWe can use a recursive method to implement the inorder traversal. During the process, we use a variable $\\textit{pre}$ to save the value of the previous node. This way, we can calculate the minimum difference between the values of two adjacent nodes during the traversal.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary search tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 531, "explanations": { "1": "According to the problem description, we need to count the number of black pixels in each row and column, which are recorded in the arrays `rows` and `cols` respectively. Then we traverse each black pixel, check whether there is only one black pixel in its row and column. If so, we increment the answer by one.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m + n)$, where $m$ and $n$ are the number of rows and columns in the matrix respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m + n)" }, { "problem_id": 532, "explanations": { "1": "Since $k$ is a fixed value, we can use a hash table $\\textit{ans}$ to record the smaller value of the pairs, which allows us to determine the larger value. Finally, we return the size of $\\textit{ans}$ as the answer.\n\nWe traverse the array $\\textit{nums}$. For the current number $x$, we use a hash table $\\textit{vis}$ to record all the numbers that have been traversed. If $x-k$ is in $\\textit{vis}$, we add $x-k$ to $\\textit{ans}$. If $x+k$ is in $\\textit{vis}$, we add $x$ to $\\textit{ans}$. Then, we add $x$ to $\\textit{vis}$. Continue traversing the array $\\textit{nums}$ until the end.\n\nFinally, we return the size of $\\textit{ans}$ as the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 533, "explanations": { "1": "The second condition in the problem is equivalent to requiring that for each column containing black pixels, these rows are exactly the same.\n\nTherefore, we can use an adjacency list $g$ to store all the rows containing black pixels in each column, i.e., $g[j]$ represents the set of all rows containing black pixels in the $j$-th column. In addition, we use an array $rows$ to store the number of black pixels in each row.\n\nNext, we traverse each column. For each column, we find the first row $i_1$ containing black pixels. If the number of black pixels in this row is not equal to $target$, then this column cannot contain lonely pixels, and we skip it directly. Otherwise, we check whether all the rows containing black pixels in this column are exactly the same as the $i_1$-th row. If so, all the black pixels in this column are lonely pixels, and we add $target$ to the answer.\n\nAfter the traversal, we return the answer.\n\nThe time complexity is $O(m \\times n^2)$, and the space complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns in the matrix respectively." }, "is_english": true, "time_complexity": "O(m \\times n^2)", "space_complexity": "O(m \\times n)" }, { "problem_id": 534, "explanations": { "1": "We can use the window function `SUM() OVER()` to group by `player_id`, sort by `event_date`, and calculate the total number of games played by each user up to the current date.", "2": "We can also use a self-join to join the `Activity` table with itself on the condition of `t1.player_id = t2.player_id AND t1.event_date >= t2.event_date`, and then group by `t1.player_id` and `t1.event_date`, and calculate the cumulative sum of `t2.games_played`. This will give us the total number of games played by each user up to the current date.", "3": "" }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 535, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 536, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 537, "explanations": { "1": "We can convert the complex number string into its real part $a$ and imaginary part $b$, and then use the formula for complex number multiplication $(a_1 + b_1i) \\times (a_2 + b_2i) = (a_1a_2 - b_1b_2) + (a_1b_2 + a_2b_1)i$ to calculate the result.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 538, "explanations": { "1": "按照“右根左”的顺序,递归遍历二叉搜索树,累加遍历到的所有节点值到 $s$ 中,然后每次赋值给对应的 `node` 节点。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉搜索树的节点数。", "2": "Morris 遍历无需使用栈,时间复杂度 $O(n)$,空间复杂度为 $O(1)$。核心思想是:\n\n定义 s 表示二叉搜索树节点值累加和。遍历二叉树节点:\n\n1. 若当前节点 root 的右子树为空,**将当前节点值添加至 s** 中,更新当前节点值为 s,并将当前节点更新为 `root.left`。\n2. 若当前节点 root 的右子树不为空,找到右子树的最左节点 next(也即是 root 节点在中序遍历下的后继节点):\n - 若后继节点 next 的左子树为空,将后继节点的左子树指向当前节点 root,并将当前节点更新为 `root.right`。\n - 若后继节点 next 的左子树不为空,**将当前节点值添加 s** 中,更新当前节点值为 s,然后将后继节点左子树指向空(即解除 next 与 root 的指向关系),并将当前节点更新为 `root.left`。\n3. 循环以上步骤,直至二叉树节点为空,遍历结束。\n4. 最后返回二叉搜索树根节点即可。\n\n> Morris 反序中序遍历跟 Morris 中序遍历思路一致,只是将中序遍历的“左根右”变为“右根左”。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 539, "explanations": { "1": "We notice that there can be at most $24 \\times 60 = 1440$ distinct time points. Therefore, if the length of $timePoints$ exceeds $1440$, it implies there are duplicate time points, and we can return $0$ early.\n\nNext, we iterate through the list of time points and convert it into a list of minutes $nums$. For example, for the time point `13:14`, we convert it into $13 \\times 60 + 14$.\n\nThen, we sort the list of minutes in ascending order and append the smallest time $nums[0]$ plus $1440$ to the end of the list. This step is to handle the special case of the difference between the maximum and minimum values.\n\nFinally, we iterate through the list of minutes to find the minimum difference between any two adjacent times.\n\nThe time complexity is $O(n \\log n)$, and the space complexity is $O(n)$, where $n$ is the number of time points." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(n)" }, { "problem_id": 540, "explanations": { "1": "The given array $\\textit{nums}$ is sorted, and we need to find the element that appears only once in $\\textit{O}(\\log n)$ time. Therefore, we consider using binary search to solve this problem.\n\nWe define the left boundary of the binary search as $\\textit{l} = 0$ and the right boundary as $\\textit{r} = n - 1$, where $n$ is the length of the array.\n\nIn each step, we take the middle position $\\textit{mid} = (l + r) / 2$. If the index $\\textit{mid}$ is even, we should compare $\\textit{nums}[\\textit{mid}]$ with $\\textit{nums}[\\textit{mid} + 1]$. If the index $\\textit{mid}$ is odd, we should compare $\\textit{nums}[\\textit{mid}]$ with $\\textit{nums}[\\textit{mid} - 1]$. Therefore, we can uniformly compare $\\textit{nums}[\\textit{mid}]$ with $\\textit{nums}[\\textit{mid} \\oplus 1]$, where $\\oplus$ denotes the XOR operation.\n\nIf $\\textit{nums}[\\textit{mid}] \\neq \\textit{nums}[\\textit{mid} \\oplus 1]$, then the answer is in $[\\textit{l}, \\textit{mid}]$, so we set $\\textit{r} = \\textit{mid}$. If $\\textit{nums}[\\textit{mid}] = \\textit{nums}[\\textit{mid} \\oplus 1]$, then the answer is in $[\\textit{mid} + 1, \\textit{r}]$, so we set $\\textit{l} = \\textit{mid} + 1$. We continue the binary search until $\\textit{l} = \\textit{r}$, at which point $\\textit{nums}[\\textit{l}]$ is the element that appears only once.\n\nThe time complexity is $\\textit{O}(\\log n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $\\textit{O}(1)$." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 541, "explanations": { "1": "We can traverse the string $\\textit{s}$, iterating over every $\\textit{2k}$ characters, and then use the two-pointer technique to reverse the first $\\textit{k}$ characters among these $\\textit{2k}$ characters.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $\\textit{s}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 542, "explanations": { "1": "We create a matrix $\\textit{ans}$ of the same size as $\\textit{mat}$ and initialize all elements to $-1$.\n\nThen, we traverse $\\textit{mat}$, adding the coordinates $(i, j)$ of all $0$ elements to the queue $\\textit{q}$, and setting $\\textit{ans}[i][j]$ to $0$.\n\nNext, we use Breadth-First Search (BFS), removing an element $(i, j)$ from the queue and traversing its four directions. If the element in that direction $(x, y)$ satisfies $0 \\leq x < m$, $0 \\leq y < n$ and $\\textit{ans}[x][y] = -1$, then we set $\\textit{ans}[x][y]$ to $\\textit{ans}[i][j] + 1$ and add $(x, y)$ to the queue $\\textit{q}$.\n\nFinally, we return $\\textit{ans}$.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the number of rows and columns in the matrix $\\textit{mat}$, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 543, "explanations": { "1": "We can enumerate each node of the binary tree, and for each node, calculate the maximum depth of its left and right subtrees, $\\textit{l}$ and $\\textit{r}$, respectively. The diameter of the node is $\\textit{l} + \\textit{r}$. The maximum diameter among all nodes is the diameter of the binary tree.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 544, "explanations": { "1": "We can use an array $s$ of length $n$ to store the ID of each team, and then simulate the process of the matches.\n\nIn each round of matches, we pair up the first $n$ elements in array $s$ two by two, and then store the ID of the winners in the first $n/2$ positions of array $s$. After that, we halve $n$ and continue to the next round of matches, until $n$ is reduced to $1$. At this point, the first element in array $s$ is the final match-up scheme.\n\nThe time complexity is $O(n \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the number of teams." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(n)" }, { "problem_id": 545, "explanations": { "1": "First, if the tree has only one node, we directly return a list with the value of that node.\n\nOtherwise, we can use depth-first search (DFS) to find the left boundary, leaf nodes, and right boundary of the binary tree.\n\nSpecifically, we can use a recursive function $\\textit{dfs}$ to find these three parts. In the $\\textit{dfs}$ function, we need to pass in a list $\\textit{nums}$, a node $\\textit{root}$, and an integer $\\textit{i}$, where $\\textit{nums}$ is used to store the current part's node values, and $\\textit{root}$ and $\\textit{i}$ represent the current node and the type of the current part (left boundary, leaf nodes, or right boundary), respectively.\n\nThe function implementation is as follows:\n\n- If $\\textit{root}$ is null, then directly return.\n- If $\\textit{i} = 0$, we need to find the left boundary. If $\\textit{root}$ is not a leaf node, we add the value of $\\textit{root}$ to $\\textit{nums}$. If $\\textit{root}$ has a left child, we recursively call the $\\textit{dfs}$ function, passing in $\\textit{nums}$, the left child of $\\textit{root}$, and $\\textit{i}$. Otherwise, we recursively call the $\\textit{dfs}$ function, passing in $\\textit{nums}$, the right child of $\\textit{root}$, and $\\textit{i}$.\n- If $\\textit{i} = 1$, we need to find the leaf nodes. If $\\textit{root}$ is a leaf node, we add the value of $\\textit{root}$ to $\\textit{nums}$. Otherwise, we recursively call the $\\textit{dfs}$ function, passing in $\\textit{nums}$, the left child of $\\textit{root}$ and $\\textit{i}$, as well as $\\textit{nums}$, the right child of $\\textit{root}$ and $\\textit{i}$.\n- If $\\textit{i} = 2$, we need to find the right boundary. If $\\textit{root}$ is not a leaf node, we add the value of $\\textit{root}$ to $\\textit{nums}$. If $\\textit{root}$ has a right child, we recursively call the $\\textit{dfs}$ function, passing in $\\textit{nums}$, the right child of $\\textit{root}$, and $\\textit{i}$. Otherwise, we recursively call the $\\textit{dfs}$ function, passing in $\\textit{nums}$, the left child of $\\textit{root}$, and $\\textit{i}$.\n\nWe call the $\\textit{dfs}$ function separately to find the left boundary, leaf nodes, and right boundary, and then concatenate these three parts to get the answer.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 546, "explanations": { "1": "设计递归函数 `dfs(i, j, k)` 表示当前处理的区间为 `[i, j]`,且该区间的右边有 `k` 个与 `boxes[j]` 相同的元素,返回该区间的最大积分。答案即为 `dfs(0, n - 1, 0)`。\n\n对于 `dfs(i, j, k)`,我们可以直接删除 `boxes[j]` 和其右边的 `k` 个元素,所得积分为 `dfs(i, j - 1, 0) + (k + 1) * (k + 1)`。\n\n我们还可以在区间 `[i, j-1]` 内枚举下标 `h`,找到满足 `boxes[h] == boxes[j]` 的下标,那么我们就将区间 `[i, j - 1]` 分成两部分,即 `[i, h]` 和 `[h + 1, j - 1]`。其中 `[i, h]` 的部分可以与 `boxes[j]` 合并,所以积分为 `dfs(i, h, k + 1) + dfs(h + 1, j - 1, 0)`。求不同 `h` 下的最大值即可。\n\n我们使用记忆化搜索来优化递归函数的时间复杂度。\n\n时间复杂度 $O(n^4)$,空间复杂度 $O(n^3)$。" }, "is_english": false, "time_complexity": "O(n^4)", "space_complexity": "O(n^3)" }, { "problem_id": 547, "explanations": { "1": "We create an array $\\textit{vis}$ to record whether each city has been visited.\n\nNext, we traverse each city $i$. If the city has not been visited, we start a depth-first search from that city. Using the matrix $\\textit{isConnected}$, we find the cities directly connected to this city. These cities and the current city belong to the same province. We continue the depth-first search for these cities until all cities in the same province have been visited. This counts as one province, so we increment the answer $\\textit{ans}$ by $1$. Then, we move to the next unvisited city and repeat the process until all cities have been traversed.\n\nFinally, return the answer.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ is the number of cities.", "2": "We can also use the union-find data structure to maintain each connected component. Initially, each city belongs to a different connected component, so the number of provinces is $n$.\n\nNext, we traverse the matrix $\\textit{isConnected}$. If there is a connection between two cities $(i, j)$ and they belong to two different connected components, they will be merged into one connected component, and the number of provinces is decremented by $1$.\n\nFinally, return the number of provinces.\n\nThe time complexity is $O(n^2 \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the number of cities, and $\\log n$ is the time complexity of path compression in the union-find data structure." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 548, "explanations": { "1": "先求出前缀和数组 s。\n\n然后遍历 j 所有可能的位置,对于每个 j,找出 i,使得前两个子数组的和相等。同时将和添加到哈希表中。\n\n接着对于每个 j,找出 k,使得后两个子数组的和相等,然后判断哈希表中是否存在该和,如果存在,则找到满足条件的三元组 `(i, j, k)`,返回 true。\n\n否则遍历结束返回 false。\n\n时间复杂度 $O(n^2)$。" }, "is_english": false, "time_complexity": "O(n^2)", "space_complexity": null }, { "problem_id": 549, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 550, "explanations": { "1": "We can first find the first login date of each player, and then perform a left join with the original table, with the join condition being that the player ID is the same and the date difference is $-1$, which means the player logged in on the second day. Then, we only need to calculate the ratio of non-null players among the players who logged in on the second day.", "2": "We can use the `LEAD` window function to get the next login date of each player. If the next login date is one day after the current login date, it means that the player logged in on the second day, and we use a field $st$ to record this information. Then, we use the `RANK` window function to rank the player IDs in ascending order by date, and get the login ranking of each player. Finally, we only need to calculate the ratio of non-null $st$ values among the players with a ranking of $1$." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 551, "explanations": { "1": "我们可以遍历字符串 $s$,记录字符 `'A'` 和字符串 `\"LLL\"` 的出现次数。如果字符 `'A'` 的出现次数小于 $2$,且字符串 `\"LLL\"` 没有出现过,则可以将该字符串视作记录合法,返回 `true`,否则返回 `false`。\n\n时间复杂度 $O(n)$,其中 $n$ 是字符串 $s$ 的长度。空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 552, "explanations": { "1": "我们设计一个函数 $dfs(i, j, k)$,表示从第 $i$ 个出勤记录开始,当前缺勤次数为 $j$,目前最后连续迟到次数为 $k$ 时,可获得出勤奖励的情况数量。那么答案就是 $dfs(0, 0, 0)$。\n\n函数 $dfs(i, j, k)$ 的执行过程如下:\n\n- 如果 $i \\ge n$,说明已经遍历完所有出勤记录,返回 $1$;\n- 如果 $j = 0$,说明当前缺勤次数为 $0$,那么可以选择缺勤,即 $dfs(i + 1, j + 1, 0)$;\n- 如果 $k \\lt 2$,说明当前连续迟到次数小于 $2$,那么可以选择迟到,即 $dfs(i + 1, j, k + 1)$;\n- 无论如何,都可以选择到场,即 $dfs(i + 1, j, 0)$。\n\n我们将上述三种情况的结果相加,即为 $dfs(i, j, k)$ 的结果。\n\n为了避免重复计算,我们可以使用记忆化搜索。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为出勤记录的长度。", "2": "动态规划,定义 `dp[i][j][k]` 表示前 `i` 天,缺勤 `j` 次,连续迟到 `k` 次时,可获得出勤奖励的情况数量\n\n状态转移需要对第 `i` 天的出勤情况分别讨论:\n\n- 缺勤:之前不能有任何缺勤记录,即 `j == 0`\n- 迟到:之前最多连续迟到 1 次,即 `k == 0 || k == 1`\n- 到场:无限制" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 553, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 554, "explanations": { "1": "We can use a hash table $\\textit{cnt}$ to record the prefix sum of each row except for the last brick. The key is the value of the prefix sum, and the value is the number of times the prefix sum appears.\n\nTraverse each row, and for each brick in the current row, add it to the current prefix sum and update $\\textit{cnt}$.\n\nFinally, we traverse $\\textit{cnt}$ to find the prefix sum that appears the most times, which represents the situation where the least number of bricks are crossed. The final answer is the number of rows in the brick wall minus the number of bricks crossed.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(n)$. Here, $m$ and $n$ are the number of rows and the number of bricks in the brick wall, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(n)" }, { "problem_id": 555, "explanations": { "1": "We first traverse the string array `strs`. For each string $s$, if the reversed string $t$ is greater than $s$, we replace $s$ with $t$.\n\nThen we enumerate each position $i$ in the string array `strs` as a split point, dividing the string array `strs` into two parts: $strs[i + 1:]$ and $strs[:i]$. We then concatenate these two parts to get a new string $t$. Next, we enumerate each position $j$ in the current string $strs[i]$. The suffix part is $a = strs[i][j:]$, and the prefix part is $b = strs[i][:j]$. We can concatenate $a$, $t$, and $b$ to get a new string $cur$. If $cur$ is greater than the current answer, we update the answer. This considers the case where $strs[i]$ is reversed. We also need to consider the case where $strs[i]$ is not reversed, i.e., concatenate $a$, $t$, and $b$ in reverse order to get a new string $cur$. If $cur$ is greater than the current answer, we update the answer.\n\nFinally, we return the answer.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string array `strs`." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 556, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 557, "explanations": { "1": "We can split the string $\\textit{s}$ into an array of words $\\textit{words}$ by spaces, then reverse each word and concatenate them back into a string.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $\\textit{s}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 558, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 559, "explanations": { "1": "First, we check if $\\textit{root}$ is null. If it is, we return 0. Otherwise, we initialize a variable $\\textit{mx}$ to record the maximum depth of the child nodes, then traverse all the child nodes of $\\textit{root}$, recursively call the $\\text{maxDepth}$ function, and update the value of $\\textit{mx}$. Finally, we return $\\textit{mx} + 1$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of nodes." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 560, "explanations": { "1": "We define a hash table `cnt` to store the number of times the prefix sum of the array `nums` appears. Initially, we set the value of `cnt[0]` to `1`, indicating that the prefix sum `0` appears once.\n\nWe traverse the array `nums`, calculate the prefix sum `s`, then add the value of `cnt[s - k]` to the answer, and increase the value of `cnt[s]` by `1`.\n\nAfter the traversal, we return the answer.\n\nThe time complexity is `O(n)`, and the space complexity is `O(n)`. Where `n` is the length of the array `nums`." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 561, "explanations": { "1": "For a pair of numbers $(a, b)$, we can assume $a \\leq b$, then $\\min(a, b) = a$. In order to make the sum as large as possible, the $b$ we choose should be as close to $a$ as possible, so as to retain a larger number.\n\nTherefore, we can sort the array $nums$, then divide every two adjacent numbers into a group, and add the first number of each group.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Where $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 562, "explanations": { "1": "We define $f[i][j][k]$ to represent the length of the longest consecutive $1$s ending at $(i, j)$ in direction $k$. The value range of $k$ is $0, 1, 2, 3$, representing horizontal, vertical, diagonal, and anti-diagonal directions, respectively.\n\n> We can also use four 2D arrays to represent the length of the longest consecutive $1$s in the four directions.\n\nWe traverse the matrix, and when we encounter $1$, we update the value of $f[i][j][k]$. For each position $(i, j)$, we only need to update the values in its four directions. Then we update the answer.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns in the matrix, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 563, "explanations": { "1": "We design a function $\\text{dfs}$ to calculate the sum of nodes in the subtree rooted at the current node. In the $\\text{dfs}$ function, we first check if the current node is null. If it is, we return 0. Then we recursively call the $\\text{dfs}$ function to calculate the sum of nodes in the left subtree $l$ and the sum of nodes in the right subtree $r$. Next, we calculate the tilt of the current node, which is $|l - r|$, and add it to the answer. Finally, we return the sum of nodes of the current node, which is $l + r + \\textit{root.val}$.\n\nIn the main function, we initialize the answer to 0, then call the $\\text{dfs}$ function to calculate the tilt of the entire tree and return the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of nodes." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 564, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 565, "explanations": { "1": "嵌套数组最终一定会形成一个环,在枚举 $nums[i]$ 的过程中,可以用 $vis$ 数组剪枝,避免重复枚举同一个环。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。", "2": "由于 $nums$ 元素均在 $[0..n-1]$ 之间,因此,对于访问过的元素,我们可以令 $nums[i]=n$,从而省略 $vis$ 数组。\n\n时间复杂度 $O(n)$,空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 566, "explanations": { "1": "First, we get the number of rows and columns of the original matrix, denoted as $m$ and $n$ respectively. If $m \\times n \\neq r \\times c$, then the matrix cannot be reshaped, and we return the original matrix directly.\n\nOtherwise, we create a new matrix with $r$ rows and $c$ columns. Starting from the first element of the original matrix, we traverse all elements in row-major order and place the traversed elements into the new matrix in order.\n\nAfter traversing all elements of the original matrix, we get the answer.\n\nThe time complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns of the original matrix, respectively. Ignoring the space consumption of the answer, the space complexity is $O(1)$.", "2": "" }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(1)" }, { "problem_id": 567, "explanations": { "1": "We use an array $\\textit{cnt}$ to record the characters and their counts that need to be matched, and a variable $\\textit{need}$ to record the number of different characters that still need to be matched. Initially, $\\textit{cnt}$ contains the character counts from the string $\\textit{s1}$, and $\\textit{need}$ is the number of different characters in $\\textit{s1}$.\n\nThen we traverse the string $\\textit{s2}$. For each character, we decrement its corresponding value in $\\textit{cnt}$. If the decremented value equals $0$, it means the current character's count in $\\textit{s1}$ is satisfied, and we decrement $\\textit{need}$. If the current index $i$ is greater than or equal to the length of $\\textit{s1}$, we need to increment the corresponding value in $\\textit{cnt}$ for $\\textit{s2}[i-\\textit{s1}]$. If the incremented value equals $1$, it means the current character's count in $\\textit{s1}$ is no longer satisfied, and we increment $\\textit{need}$. During the traversal, if the value of $\\textit{need}$ equals $0$, it means all character counts are satisfied, and we have found a valid substring, so we return $\\text{true}$.\n\nOtherwise, if the traversal ends without finding a valid substring, we return $\\text{false}$.\n\nThe time complexity is $O(m + n)$, where $m$ and $n$ are the lengths of strings $\\textit{s1}$ and $\\textit{s2}$, respectively. The space complexity is $O(|\\Sigma|)$, where $\\Sigma$ is the character set. In this problem, the character set is lowercase letters, so the space complexity is constant." }, "is_english": true, "time_complexity": "O(m + n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 568, "explanations": { "1": "我们定义 $f[k][j]$ 表示前 $k$ 周,且最后一周在城市 $j$ 休假的最长天数。初始时 $f[0][0]=0$,其它 $f[0][j]=-\\infty$。答案为 $\\max_{j=0}^{n-1} f[K][j]$。\n\n接下来,我们考虑如何计算 $f[k][j]$。对于当前这一周,我们可以枚举上一周所在的城市 $i$,城市 $i$ 可以和城市 $j$ 相等,那么 $f[k][j] = f[k-1][i]$;也可以和城市 $j$ 不相等,如果不相等,我们需要判断是否可以从城市 $i$ 飞到城市 $j$,如果可以,那么 $f[k][j] = \\max(f[k][j], f[k-1][i])$。最后,我们还需要加上这一周在城市 $j$ 休假的天数 $\\textit{days}[j][k-1]$。\n\n最终的答案即为 $\\max_{j=0}^{n-1} f[K][j]$。\n\n时间复杂度 $O(K \\times n^2)$,空间复杂度 $O(K \\times n)$。其中 $K$ 和 $n$ 分别为周数和城市数。" }, "is_english": false, "time_complexity": "O(K \\times n^2)", "space_complexity": "O(K \\times n)" }, { "problem_id": 569, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 570, "explanations": { "1": "We can first count the number of direct subordinates for each manager, and then join the `Employee` table to find the managers whose number of direct subordinates is greater than or equal to $5$." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 571, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 572, "explanations": { "1": "We define a helper function $\\textit{same}(p, q)$ to determine whether the tree rooted at $p$ and the tree rooted at $q$ are identical. If the root values of the two trees are equal, and their left and right subtrees are also respectively equal, then the two trees are identical.\n\nIn the $\\textit{isSubtree}(\\textit{root}, \\textit{subRoot})$ function, we first check if $\\textit{root}$ is null. If it is, we return $\\text{false}$. Otherwise, we check if $\\textit{root}$ and $\\textit{subRoot}$ are identical. If they are, we return $\\text{true}$. Otherwise, we recursively check if the left or right subtree of $\\textit{root}$ contains $\\textit{subRoot}$.\n\nThe time complexity is $O(n \\times m)$, and the space complexity is $O(n)$. Here, $n$ and $m$ are the number of nodes in the trees $root$ and $subRoot$, respectively." }, "is_english": true, "time_complexity": "O(n \\times m)", "space_complexity": "O(n)" }, { "problem_id": 573, "explanations": { "1": "Observing the squirrel's movement path, we can see that the squirrel will first move to the position of a nut, then move to the position of the tree. After that, the total movement path of the squirrel is equal to \"the sum of the distances from the remaining nuts to the tree\" multiplied by $2$.\n\nTherefore, we only need to select a nut as the squirrel's first target, such that the sum of its distance to the tree is minimized, to obtain the shortest path.\n\nThe time complexity is $O(n)$, where $n$ is the number of nuts. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 574, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 575, "explanations": { "1": "We use a hash table to store the types of candies. If the number of candy types is less than $n / 2$, then the maximum number of candy types that Alice can eat is the number of candy types. Otherwise, the maximum number of candy types that Alice can eat is $n / 2$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of candies." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 576, "explanations": { "1": "We define a function $\\textit{dfs}(i, j, k)$ to represent the number of paths that can move out of the boundary starting from coordinates $(i, j)$ with $k$ steps remaining.\n\nIn the function $\\textit{dfs}(i, j, k)$, we first handle the boundary cases. If the current coordinates $(i, j)$ are out of the grid range, return $1$ if $k \\geq 0$, otherwise return $0$. If $k \\leq 0$, it means we are still within the grid but have no remaining moves, so return $0$. Next, we iterate over the four directions, move to the next coordinates $(x, y)$, then recursively call $\\textit{dfs}(x, y, k - 1)$, and accumulate the results to the answer.\n\nIn the main function, we call $\\textit{dfs}(startRow, startColumn, maxMove)$, which represents the number of paths that can move out of the boundary starting from the initial coordinates $(\\textit{startRow}, \\textit{startColumn})$ with $\\textit{maxMove}$ steps remaining.\n\nTo avoid redundant calculations, we can use memoization.\n\nThe time complexity is $O(m \\times n \\times k)$, and the space complexity is $O(m \\times n \\times k)$. Here, $m$ and $n$ are the number of rows and columns of the grid, and $k$ is the number of steps that can be moved, with $k = \\textit{maxMove} \\leq 50$." }, "is_english": true, "time_complexity": "O(m \\times n \\times k)", "space_complexity": "O(m \\times n \\times k)" }, { "problem_id": 577, "explanations": { "1": "We can use a left join to join the `Employee` table and the `Bonus` table on `empId`, and then filter out the employees whose bonus is less than $1000$. Note that the employees with `NULL` bonus values after the join should also be filtered out, so we need to use the `IFNULL` function to convert `NULL` values to $0$." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 578, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 579, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 580, "explanations": { "1": "We can use a left join to join the `Department` table and the `Student` table on `dept_id`, and then group by `dept_id` to count the number of students in each department. Finally, we can sort the result by `student_number` in descending order and `dept_name` in ascending order." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 581, "explanations": { "1": "We can first sort the array, and then compare the sorted array with the original array to find the leftmost and rightmost positions where they differ. The length between them is the length of the shortest unsorted continuous subarray.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array.", "2": "We can traverse the array from left to right and maintain a maximum value $mx$. If the current value is less than $mx$, it means that the current value is not in the correct position, and we update the right boundary $r$ to the current position. Similarly, we can traverse the array from right to left and maintain a minimum value $mi$. If the current value is greater than $mi$, it means that the current value is not in the correct position, and we update the left boundary $l$ to the current position. At initialization, we set $l$ and $r$ to $-1$. If $l$ and $r$ are not updated, it means that the array is already sorted, and we return $0$. Otherwise, we return $r - l + 1$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 582, "explanations": { "1": "We first construct a graph $g$ based on $pid$ and $ppid$, where $g[i]$ represents all child processes of process $i$. Then, starting from the process $kill$, we perform depth-first search to obtain all killed processes.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of processes." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 583, "explanations": { "1": "We define $f[i][j]$ as the minimum number of deletions required to make the first $i$ characters of the string $\\textit{word1}$ and the first $j$ characters of the string $\\textit{word2}$ the same. The answer is $f[m][n]$, where $m$ and $n$ are the lengths of the strings $\\textit{word1}$ and $\\textit{word2}$, respectively.\n\nInitially, if $j = 0$, then $f[i][0] = i$; if $i = 0$, then $f[0][j] = j$.\n\nWhen $i, j > 0$, if $\\textit{word1}[i - 1] = \\textit{word2}[j - 1]$, then $f[i][j] = f[i - 1][j - 1]$; otherwise, $f[i][j] = \\min(f[i - 1][j], f[i][j - 1]) + 1$.\n\nFinally, return $f[m][n]$.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the lengths of the strings $\\textit{word1}$ and $\\textit{word2}$, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 584, "explanations": { "1": "We can directly filter out the customer names whose `referee_id` is not `2`. Note that the customers whose `referee_id` is `NULL` should also be filtered out." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 585, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 586, "explanations": { "1": "We can use `GROUP BY` to group the data by `customer_number`, and then sort the groups in descending order by `count(1)`. Finally, we can take the `customer_number` of the first record as the result.", "2": "" }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 587, "explanations": { "1": "原理:\n\n利用夹角,让整个图形保持左转。先将最左边的前两个点加入栈中,每次加入新点时判断是否左拐(叉积大于 0),如果是就将新点直接加入;如果不是,就弹出栈顶,直到左拐,将新点加入栈中。\n\n流程:\n\n1. 将所有点 `(x, y)` 进行排序,以 x 为第一关键字,y 为第二关键字升序排序;\n1. 先从左至右维护凸包的下半部分,然后再从右至左维护上半部分;\n1. 将第一个点放入栈中,这个点一定时凸包的最左边的点了,是不会清理掉的,然后再将第二个点放入栈中。当栈中元素大于等于 2 的时候,就要判断栈顶元素是否还要保留:\n - 如果新点在栈顶元素和次栈顶元素所组成的直线的逆时针方向上,那么直接将新点加入栈中;\n - 否则,将栈顶元素不断弹出,直至新点的位置出现在栈顶元素与次栈顶元素所在直线的逆时针方向。\n\n这个过程,是从左往右走的,并且得到的凸包是凸壳的下半部分。求上半部分的时候,从右往左遍历。\n\n时间复杂度 O(nlogn)。" }, "is_english": false, "time_complexity": "O(nlogn)", "space_complexity": null }, { "problem_id": 588, "explanations": { "1": "哈希表实现前缀树。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 589, "explanations": { "1": "We can recursively traverse the entire tree. For each node, we first add the node's value to the answer, then recursively call the function for each of the node's children.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes.", "2": "We can also solve this problem iteratively.\n\nWe use a stack to help us get the pre-order traversal. We first push the root node into the stack. Since the pre-order traversal is root, left subtree, right subtree, and the characteristic of the stack is first in last out, we first add the node's value to the answer, then push each of the node's children into the stack in the order from right to left. We continue this process until the stack is empty.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 590, "explanations": { "1": "We can recursively traverse the entire tree. For each node, we first recursively call the function for each of the node's children, then add the node's value to the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes.", "2": "We can also solve this problem iteratively.\n\nWe use a stack to help us get the post-order traversal. We first push the root node into the stack. Since the post-order traversal is left subtree, right subtree, root, and the characteristic of the stack is first in last out, we first add the node's value to the answer, then push each of the node's children into the stack in the order from left to right. This way, we can get the traversal result of root, right subtree, left subtree. Finally, we reverse the answer to get the post-order traversal result.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 591, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 592, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 593, "explanations": { "1": "若任选三个点,都能构成等腰直角三角形,说明是有效的正方形。\n\n时间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(1)", "space_complexity": null }, { "problem_id": 594, "explanations": { "1": "We can use a hash table $\\textit{cnt}$ to record the occurrence count of each element in the array $\\textit{nums}$. Then, we iterate through each key-value pair $(x, c)$ in the hash table. If the key $x + 1$ exists in the hash table, then the sum of occurrences of elements $x$ and $x + 1$, $c + \\textit{cnt}[x + 1]$, forms a harmonious subsequence. We just need to find the maximum length among all harmonious subsequences.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 595, "explanations": { "1": "我们可以使用 `WHERE` + `OR` 查询出所有符合条件的国家。", "2": "我们可以查询出所有面积大于等于 300 万平方公里的国家,然后再查询出所有人口大于等于 2500 万的国家,最后使用 `UNION` 将两个结果集合并起来。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 596, "explanations": { "1": "We can use the `GROUP BY` statement to group by class and then use the `HAVING` statement to filter out the classes with a student count greater than or equal to $5$." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 597, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 598, "explanations": { "1": "We notice that the intersection of all operation submatrices is the submatrix where the final maximum integer is located, and each operation submatrix starts from the top-left corner $(0, 0)$. Therefore, we traverse all operation submatrices to find the minimum number of rows and columns. Finally, we return the product of these two values.\n\nNote that if the operation array is empty, the number of maximum integers in the matrix is $m \\times n$.\n\nThe time complexity is $O(k)$, where $k$ is the length of the operation array $\\textit{ops}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(k)", "space_complexity": "O(1)" }, { "problem_id": 599, "explanations": { "1": "We use a hash table $\\textit{d}$ to record the strings in $\\textit{list2}$ and their indices, and a variable $\\textit{mi}$ to record the minimum index sum.\n\nThen, we traverse $\\textit{list1}$. For each string $\\textit{s}$, if $\\textit{s}$ appears in $\\textit{list2}$, we calculate the index $\\textit{i}$ of $\\textit{s}$ in $\\textit{list1}$ and the index $\\textit{j}$ in $\\textit{list2}$. If $\\textit{i} + \\textit{j} < \\textit{mi}$, we update the answer array $\\textit{ans}$ to $\\textit{s}$ and update $\\textit{mi}$ to $\\textit{i} + \\textit{j}$. If $\\textit{i} + \\textit{j} = \\textit{mi}$, we add $\\textit{s}$ to the answer array $\\textit{ans}$.\n\nAfter traversing, return the answer array $\\textit{ans}$." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 600, "explanations": { "1": "This problem essentially asks for the number of numbers in the given range $[l, ..r]$ whose binary representation does not contain consecutive $1$s. The count is related to the number of digits and the value of each binary digit. We can use the concept of Digit DP to solve this problem. In Digit DP, the size of the number has little impact on the complexity.\n\nFor the range $[l, ..r]$ problem, we generally convert it to the problem of $[0, ..r]$ and then subtract the result of $[0, ..l - 1]$, i.e.:\n\n$$\nans = \\sum_{i=0}^{r} ans_i - \\sum_{i=0}^{l-1} ans_i\n$$\n\nHowever, for this problem, we only need to find the value for the range $[0, ..r]$.\n\nHere, we use memoized search to implement Digit DP. The basic steps are as follows:\n\nFirst, we get the binary length of the number $n$, denoted as $m$. Then, based on the problem information, we design a function $\\textit{dfs}(i, \\textit{pre}, \\textit{limit})$, where:\n\n- The digit $i$ represents the current position being searched, starting from the highest digit, i.e., the first character of the binary string.\n- The digit $\\textit{pre}$ represents the digit at the previous binary position. For this problem, the initial value of $\\textit{pre}$ is $0$.\n- The boolean $\\textit{limit}$ indicates whether the digits that can be filled are restricted. If there is no restriction, then we can choose $[0,1]$. Otherwise, we can only choose $[0, \\textit{up}]$.\n\nThe function executes as follows:\n\nIf $i$ exceeds the length of the number $n$, i.e., $i < 0$, it means the search is over, directly return $1$. Otherwise, we enumerate the digits $j$ from $0$ to $\\textit{up}$ for the position $i$. For each $j$:\n\n- If both $\\textit{pre}$ and $j$ are $1$, it means there are consecutive $1$, so we skip it.\n- Otherwise, we recurse to the next level, update $\\textit{pre}$ to $j$, and update $\\textit{limit}$ to the logical AND of $\\textit{limit}$ and whether $j$ equals $\\textit{up}$.\n\nFinally, we sum all the results from the recursive calls to the next level, which is the answer.\n\nThe time complexity is $O(\\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the given positive integer.\n\nSimilar problems:\n\n- [233. Number of Digit One](https://github.com/doocs/leetcode/blob/main/solution/0200-0299/0233.Number%20of%20Digit%20One/README_EN.md)\n- [357. Count Numbers with Unique Digits](https://github.com/doocs/leetcode/blob/main/solution/0300-0399/0357.Count%20Numbers%20with%20Unique%20Digits/README_EN.md)\n- [788. Rotated Digits](https://github.com/doocs/leetcode/blob/main/solution/0700-0799/0788.Rotated%20Digits/README_EN.md)\n- [902. Numbers At Most N Given Digit Set](https://github.com/doocs/leetcode/blob/main/solution/0900-0999/0902.Numbers%20At%20Most%20N%20Given%20Digit%20Set/README_EN.md)\n- [1012. Numbers With Repeated Digits](https://github.com/doocs/leetcode/blob/main/solution/1000-1099/1012.Numbers%20With%20Repeated%20Digits/README_EN.md)\n- [2376. Count Special Integers](https://github.com/doocs/leetcode/blob/main/solution/2300-2399/2376.Count%20Special%20Integers/README_EN.md)" }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 601, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 602, "explanations": { "1": "We can merge the `requester_id` and `accepter_id` columns into a single column, representing each person's friend relationships. Then we group the merged result and count, finding the person with the most friends and the number of friends." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 603, "explanations": { "1": "We can use a self-join to join the `Seat` table with itself, and then filter out the records where the `id` of the left seat is equal to the `id` of the right seat minus $1$, and where both seats are empty.", "2": "We can use the `LAG` and `LEAD` functions (or `SUM() OVER(ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)`) to obtain the information of adjacent seats, and then filter out the consecutive empty seats and sort them in a unique way.", "3": "" }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 604, "explanations": { "1": "Parse the `compressedString` into characters $c$ and their corresponding repetition counts $x$, and store them in an array or list $d$. Use $p$ to point to the current character.\n\nThen perform operations in `next` and `hasNext`.\n\nThe initialization time complexity is $O(n)$, and the time complexity of the other operations is $O(1)$. Here, $n$ is the length of `compressedString`." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": null }, { "problem_id": 605, "explanations": { "1": "We directly traverse the array $flowerbed$. For each position $i$, if $flowerbed[i]=0$ and its adjacent positions on the left and right are also $0$, then we can plant a flower at this position. Otherwise, we cannot. Finally, we count the number of flowers that can be planted. If it is not less than $n$, we return $true$, otherwise we return $false$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $flowerbed$. We only need to traverse the array once. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 606, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 607, "explanations": { "1": "We can use a left join to join the `SalesPerson` table with the `Orders` table on the condition of sales id, and then join the result with the `Company` table on the condition of company id. After that, we can group by `sales_id` and count the number of orders with the company name `RED`. Finally, we can filter out the salespersons who do not have any orders with the company name `RED`." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 608, "explanations": { "1": "We can use the `CASE WHEN` conditional statement to determine the type of each node as follows:\n\n- If a node's `p_id` is `NULL`, then it is a root node.\n- Otherwise, if a node is the parent node of another node (we use a subquery to determine this), then it is an internal node.\n- Otherwise, it is a leaf node." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 609, "explanations": { "1": "We create a hash table $d$, where the key is the file content and the value is a list of file paths with the same content.\n\nNext, we iterate over $\\textit{paths}$. For each path, we split it into the directory path and file information. For each file entry, we extract the file name and file content, and append the file path to the corresponding list in hash table $d$.\n\nFinally, we return all values in hash table $d$ that have more than one file path.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of $\\textit{paths}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 610, "explanations": { "1": "The condition for whether three sides can form a triangle is that the sum of any two sides is greater than the third side. Therefore, we can use an `IF` statement to determine whether this condition is satisfied. If it is satisfied, we return `Yes`, otherwise we return `No`." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 611, "explanations": { "1": "A valid triangle must satisfy: **the sum of any two sides is greater than the third side**. That is:\n\n$$a + b \\gt c \\tag{1}$$\n\n$$a + c \\gt b \\tag{2}$$\n\n$$b + c \\gt a \\tag{3}$$\n\nIf we arrange the sides in ascending order, i.e., $a \\leq b \\leq c$, then obviously conditions (2) and (3) are satisfied. We only need to ensure that condition (1) is also satisfied to form a valid triangle.\n\nWe enumerate $i$ in the range $[0, n - 3]$, enumerate $j$ in the range $[i + 1, n - 2]$, and perform binary search in the range $[j + 1, n - 1]$ to find the first index $left$ that is greater than or equal to $nums[i] + nums[j]$. Then, the values of $k$ in the range $[j + 1, left - 1]$ satisfy the condition, and we add them to the result $\\textit{ans}$.\n\nThe time complexity is $O(n^2\\log n)$, and the space complexity is $O(\\log n)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n^2\\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 612, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 613, "explanations": { "1": "We can use a self-join to join each point in the table with the larger points, and then calculate the distance between the two points. Finally, we can take the minimum distance.", "2": "We can use a window function to sort the points in the table by their $x$ values, and then calculate the distance between adjacent points. Finally, we can take the minimum distance." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 614, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 615, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 616, "explanations": { "1": "相似题目:\n\n- [1065. 字符串的索引对](https://github.com/doocs/leetcode/blob/main/solution/1000-1099/1065.Index%20Pairs%20of%20a%20String/README.md)\n- [758. 字符串中的加粗单词](https://github.com/doocs/leetcode/blob/main/solution/0700-0799/0758.Bold%20Words%20in%20String/README.md)" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 617, "explanations": { "1": "递归合并两棵树的节点。\n\n- 如果其中一棵树的当前节点为空,则返回另一棵树的当前节点作为合并后节点。\n- 如果两棵树的当前节点都不为空,则将它们的值相加作为合并后节点的新值,然后递归合并它们的左右子节点。\n\n时间复杂度 $O(m)$,空间复杂度 $O(m)$。其中 $m$ 是两棵树的节点数的最小值。" }, "is_english": false, "time_complexity": "O(m)", "space_complexity": "O(m)" }, { "problem_id": 618, "explanations": { "1": "我们可以使用窗口函数 `row_number()` 来为每个大洲的学生编号,然后使用 `GROUP BY` 来将同一编号的学生聚合到一行中。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 619, "explanations": { "1": "We can first group the `MyNumbers` table by `num` and count the number of occurrences of each number. Then, we can use a subquery to find the maximum number among the numbers that appear only once.", "2": "Similar to Solution 1, we can first group the `MyNumbers` table by `num` and count the number of occurrences of each number. Then, we can use a `CASE` expression to find the numbers that appear only once, sort them in descending order by number, and take the first one." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 620, "explanations": { "1": "We can use the `WHERE` clause to filter out the records where `description` is not `boring` and `id` is odd, and then use the `ORDER BY` clause to sort the result in descending order by `rating`." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 621, "explanations": { "1": "不妨设 $m$ 是任务的个数,统计每种任务出现的次数,记录在数组 `cnt` 中。\n\n假设出现次数最多的任务为 `A`,出现次数为 $x$,则至少需要 $(x-1)\\times(n+1) + 1$ 个时间单位才能安排完所有任务。如果出现次数最多的任务有 $s$ 个,则需要再加上出现次数最多的任务的个数。\n\n答案是 $\\max ((x-1) \\times(n+1)+s, m)$。\n\n时间复杂度 $O(m+|\\Sigma|)$。其中 $|\\Sigma|$ 是任务的种类数。" }, "is_english": false, "time_complexity": "O(m+|\\Sigma|)", "space_complexity": null }, { "problem_id": 622, "explanations": { "1": "We can use an array $q$ of length $k$ to simulate a circular queue, with a pointer $\\textit{front}$ to record the position of the front element. Initially, the queue is empty, and $\\textit{front}$ is $0$. Additionally, we use a variable $\\textit{size}$ to record the number of elements in the queue, initially $\\textit{size}$ is $0$.\n\nWhen calling the `enQueue` method, we first check if the queue is full, i.e., $\\textit{size} = k$. If it is full, we return $\\textit{false}$. Otherwise, we insert the element at position $(\\textit{front} + \\textit{size}) \\bmod k$, then $\\textit{size} = \\textit{size} + 1$, indicating that the number of elements in the queue has increased by $1$. Finally, we return $\\textit{true}$.\n\nWhen calling the `deQueue` method, we first check if the queue is empty, i.e., $\\textit{size} = 0$. If it is empty, we return $\\textit{false}$. Otherwise, we set $\\textit{front} = (\\textit{front} + 1) \\bmod k$, indicating that the front element has been dequeued, then $\\textit{size} = \\textit{size} - 1$.\n\nWhen calling the `Front` method, we first check if the queue is empty, i.e., $\\textit{size} = 0$. If it is empty, we return $-1$. Otherwise, we return $q[\\textit{front}]$.\n\nWhen calling the `Rear` method, we first check if the queue is empty, i.e., $\\textit{size} = 0$. If it is empty, we return $-1$. Otherwise, we return $q[(\\textit{front} + \\textit{size} - 1) \\bmod k]$.\n\nWhen calling the `isEmpty` method, we simply check if $\\textit{size} = 0$.\n\nWhen calling the `isFull` method, we simply check if $\\textit{size} = k$.\n\nIn terms of time complexity, the above operations all have a time complexity of $O(1)$. The space complexity is $O(k)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(k)" }, { "problem_id": 623, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 624, "explanations": { "1": "We notice that the maximum distance must be the distance between the maximum value in one array and the minimum value in another array. Therefore, we can maintain two variables $\\textit{mi}$ and $\\textit{mx}$, representing the minimum and maximum values of the arrays we have traversed. Initially, $\\textit{mi}$ and $\\textit{mx}$ are the first and last elements of the first array, respectively.\n\nNext, we traverse from the second array. For each array, we first calculate the distance between the first element of the current array and $\\textit{mx}$, and the distance between the last element of the current array and $\\textit{mi}$. Then, we update the maximum distance. At the same time, we update $\\textit{mi} = \\min(\\textit{mi}, \\textit{arr}[0])$ and $\\textit{mx} = \\max(\\textit{mx}, \\textit{arr}[\\textit{size} - 1])$.\n\nAfter traversing all arrays, we get the maximum distance.\n\nThe time complexity is $O(m)$, where $m$ is the number of arrays. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m)", "space_complexity": "O(1)" }, { "problem_id": 625, "explanations": { "1": "我们先判断 $num$ 是否小于 $2$,如果是,直接返回 $num$。然后从 $9$ 开始,尽可能多地将数字分解为 $9$,然后分解为 $8$,以此类推,直到分解为 $2$。如果最后剩下的数字不是 $1$,或者结果超过了 $2^{31} - 1$,则返回 $0$。否则,我们返回结果。\n\n> 注意,分解后的数字,应该依次填充到结果的个位、十位、百位、千位……上,因此我们需要维护一个变量 $mul$,表示当前的位数。\n\n时间复杂度 $O(\\log n)$,空间复杂度 $O(1)$。其中 $n$ 为 $num$ 的值。" }, "is_english": false, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 626, "explanations": { "1": "", "2": "", "3": "", "4": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 627, "explanations": { "1": "According to the problem requirements, we only need to use a single UPDATE statement to swap the sex of all employees. We can achieve this using conditional expressions in SQL." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 628, "explanations": { "1": "First, we sort the array $\\textit{nums}$, and then discuss two cases:\n\n- If $\\textit{nums}$ contains all non-negative or all non-positive numbers, the answer is the product of the last three numbers, i.e., $\\textit{nums}[n-1] \\times \\textit{nums}[n-2] \\times \\textit{nums}[n-3]$;\n- If $\\textit{nums}$ contains both positive and negative numbers, the answer could be the product of the two smallest negative numbers and the largest positive number, i.e., $\\textit{nums}[n-1] \\times \\textit{nums}[0] \\times \\textit{nums}[1]$, or the product of the last three numbers, i.e., $\\textit{nums}[n-1] \\times \\textit{nums}[n-2] \\times \\textit{nums}[n-3]$.\n\nFinally, return the maximum of the two cases.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array $\\textit{nums}$.", "2": "We can avoid sorting the array by maintaining five variables: $\\textit{mi1}$ and $\\textit{mi2}$ represent the two smallest numbers in the array, while $\\textit{mx1}$, $\\textit{mx2}$, and $\\textit{mx3}$ represent the three largest numbers in the array.\n\nFinally, return $\\max(\\textit{mi1} \\times \\textit{mi2} \\times \\textit{mx1}, \\textit{mx1} \\times \\textit{mx2} \\times \\textit{mx3})$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 629, "explanations": { "1": "We define $f[i][j]$ as the number of arrays of length $i$ with $j$ inverse pairs. Initially, $f[0][0] = 1$, and the rest $f[i][j] = 0$.\n\nNext, we consider how to obtain $f[i][j]$.\n\nAssume the first $i-1$ numbers are already determined, and now we need to insert the number $i$. We discuss the cases of inserting $i$ into each position:\n\n- If $i$ is inserted into the 1st position, the number of inverse pairs increases by $i-1$, so $f[i][j] += f[i-1][j-(i-1)]$.\n- If $i$ is inserted into the 2nd position, the number of inverse pairs increases by $i-2$, so $f[i][j] += f[i-1][j-(i-2)]$.\n- ...\n- If $i$ is inserted into the $(i-1)$th position, the number of inverse pairs increases by 1, so $f[i][j] += f[i-1][j-1]$.\n- If $i$ is inserted into the $i$th position, the number of inverse pairs does not change, so $f[i][j] += f[i-1][j]$.\n\nTherefore, $f[i][j] = \\sum_{k=1}^{i} f[i-1][j-(i-k)]$.\n\nWe notice that the calculation of $f[i][j]$ actually involves prefix sums, so we can use prefix sums to optimize the calculation process. Moreover, since $f[i][j]$ only depends on $f[i-1][j]$, we can use a one-dimensional array to optimize the space complexity.\n\nThe time complexity is $O(n \\times k)$, and the space complexity is $O(k)$. Here, $n$ and $k$ are the array length and the number of inverse pairs, respectively." }, "is_english": true, "time_complexity": "O(n \\times k)", "space_complexity": "O(k)" }, { "problem_id": 630, "explanations": { "1": "We can sort the courses in ascending order by their end time, and each time select the course with the earliest deadline to take.\n\nIf the total time $s$ of the selected courses exceeds the end time $last$ of the current course, we remove the course with the longest duration from the previously selected courses, until the constraint of the current course's end time is satisfied. Here we use a priority queue (max-heap) $pq$ to maintain the durations of the currently selected courses, and each time we pop the course with the longest duration from the priority queue to remove it.\n\nFinally, the number of elements in the priority queue is the maximum number of courses we can take.\n\nThe time complexity is $O(n \\times \\log n)$ and the space complexity is $O(n)$, where $n$ is the number of courses." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 631, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 632, "explanations": { "1": "We construct a data item $(x, i)$ for each number $x$ and its group $i$, and store these items in a new array $t$. Then, we sort $t$ by the value of the numbers (similar to merging multiple sorted arrays into a new sorted array).\n\nNext, we traverse each data item in $t$, focusing on the group to which each number belongs. We use a hash table to record the groups of numbers within the sliding window. If the number of groups is $k$, it means the current window meets the problem's requirements. At this point, we calculate the start and end positions of the window and update the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the total number of numbers in all arrays.", "2": "" }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 633, "explanations": { "1": "We can use the two-pointer method to solve this problem. Define two pointers $a$ and $b$, pointing to $0$ and $\\sqrt{c}$ respectively. In each step, we calculate the value of $s = a^2 + b^2$, and then compare the size of $s$ and $c$. If $s = c$, we have found two integers $a$ and $b$ such that $a^2 + b^2 = c$. If $s < c$, we increase the value of $a$ by $1$. If $s > c$, we decrease the value of $b$ by $1$. We continue this process until we find the answer, or the value of $a$ is greater than the value of $b$, and return `false`.\n\nThe time complexity is $O(\\sqrt{c})$, where $c$ is the given non-negative integer. The space complexity is $O(1)$.", "2": "This problem is essentially about the conditions under which a number can be expressed as the sum of two squares. This theorem dates back to Fermat and Euler and is a classic result in number theory.\n\nSpecifically, the theorem can be stated as follows:\n\n> A positive integer $n$ can be expressed as the sum of two squares if and only if all prime factors of $n$ of the form $4k + 3$ have even powers.\n\nThis means that if we decompose $n$ into the product of its prime factors, $n = p_1^{e_1} p_2^{e_2} \\cdots p_k^{e_k}$, where $p_i$ are primes and $e_i$ are their corresponding exponents, then $n$ can be expressed as the sum of two squares if and only if all prime factors $p_i$ of the form $4k + 3$ have even exponents $e_i$.\n\nMore formally, if $p_i$ is a prime of the form $4k + 3$, then for each such $p_i$, $e_i$ must be even.\n\nFor example:\n\n- The number $13$ is a prime and $13 \\equiv 1 \\pmod{4}$, so it can be expressed as the sum of two squares, i.e., $13 = 2^2 + 3^2$.\n- The number $21$ can be decomposed into $3 \\times 7$, where both $3$ and $7$ are prime factors of the form $4k + 3$ and their exponents are $1$ (odd), so $21$ cannot be expressed as the sum of two squares.\n\nIn summary, this theorem is very important in number theory for determining whether a number can be expressed as the sum of two squares.\n\nThe time complexity is $O(\\sqrt{c})$, where $c$ is the given non-negative integer. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\sqrt{c})", "space_complexity": "O(1)" }, { "problem_id": 634, "explanations": { "1": "We define $f[i]$ as the number of derangement of an array of length $i$. Initially, $f[0] = 1$, $f[1] = 0$. The answer is $f[n]$.\n\nFor an array of length $i$, we consider where to place the number $1$. Suppose it is placed in the $j$-th position, where there are $i-1$ choices. Then, the number $j$ has two choices:\n\n- Placed in the first position, then the remaining $i - 2$ positions have $f[i - 2]$ derangements, so there are a total of $(i - 1) \\times f[i - 2]$ derangements;\n- Not placed in the first position, which is equivalent to the derangement of an array of length $i - 1$, so there are a total of $(i - 1) \\times f[i - 1]$ derangements.\n\nIn summary, we have the following state transition equation:\n\n$$\nf[i] = (i - 1) \\times (f[i - 1] + f[i - 2])\n$$\n\nThe final answer is $f[n]$. Note the modulo operation in the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$.", "2": "We notice that the state transition equation only relates to $f[i - 1]$ and $f[i - 2]$. Therefore, we can use two variables $a$ and $b$ to represent $f[i - 1]$ and $f[i - 2]$ respectively, thereby reducing the space complexity to $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 635, "explanations": { "1": "Store the `id` and `timestamp` of the logs as tuples in an array. Then in the `retrieve()` method, truncate the corresponding parts of `start` and `end` based on `granularity`, and traverse the array, adding the `id` that meets the conditions to the result array.\n\nIn terms of time complexity, the time complexity of the `put()` method is $O(1)$, and the time complexity of the `retrieve()` method is $O(n)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": null }, { "problem_id": 636, "explanations": { "1": "We define a stack $\\textit{stk}$ to store the identifiers of the currently executing functions. We also define an array $\\textit{ans}$ to store the exclusive time of each function, initially setting the exclusive time of each function to $0$. We use a variable $\\textit{pre}$ to record the previous timestamp.\n\nWe traverse the log array. For each log entry, we first split it by colons to get the function identifier $\\textit{i}$, the operation type $\\textit{op}$, and the timestamp $\\textit{t}$.\n\nIf $\\textit{op}$ is $\\text{start}$, it means function $\\textit{i}$ starts executing. We need to check if the stack is empty. If it is not empty, we add $\\textit{cur} - \\textit{pre}$ to the exclusive time of the function at the top of the stack, then push $\\textit{i}$ onto the stack and update $\\textit{pre}$ to $\\textit{cur}$. If $\\textit{op}$ is $\\text{end}$, it means function $\\textit{i}$ finishes executing. We add $\\textit{cur} - \\textit{pre} + 1$ to the exclusive time of the function at the top of the stack, then pop the top element from the stack and update $\\textit{pre}$ to $\\textit{cur} + 1$.\n\nFinally, we return the array $\\textit{ans}$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the log array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 637, "explanations": { "1": "We can use the Breadth-First Search (BFS) method to traverse the nodes of each level and calculate the average value of each level.\n\nSpecifically, we define a queue $q$, initially adding the root node to the queue. Each time, we take out all the nodes in the queue, calculate their average value, add it to the answer array, and then add their child nodes to the queue. Repeat this process until the queue is empty.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree.", "2": "We can also use the Depth-First Search (DFS) method to calculate the average value of each level.\n\nSpecifically, we define an array $s$, where $s[i]$ is a tuple representing the sum of node values and the number of nodes at the $i$-th level. We perform a depth-first search on the tree. For each node, we add the node's value to the corresponding $s[i]$ and increment the node count by one. Finally, for each $s[i]$, we calculate the average value and add it to the answer array.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 638, "explanations": { "1": "We notice that the number of types of items $n \\leq 6$ in the problem, and the quantity of each item needed does not exceed $10$. We can use $4$ binary bits to represent the quantity of each item needed. Thus, we only need at most $6 \\times 4 = 24$ binary bits to represent the entire shopping list.\n\nFirst, we convert the shopping list $\\textit{needs}$ into an integer $\\textit{mask}$, where the quantity of the $i$-th item needed is stored in the $i \\times 4$ to $(i + 1) \\times 4 - 1$ bits of $\\textit{mask}$. For example, when $\\textit{needs} = [1, 2, 1]$, we have $\\textit{mask} = 0b0001 0010 0001$.\n\nThen, we design a function $\\textit{dfs}(cur)$, representing the minimum amount of money we need to spend when the current state of the shopping list is $\\textit{cur}$. Therefore, the answer is $\\textit{dfs}(\\textit{mask})$.\n\nThe calculation method of the function $\\textit{dfs}(cur)$ is as follows:\n\n- First, we calculate the cost of the current shopping list $\\textit{cur}$ without using any bundles, denoted as $\\textit{ans}$.\n- Then, we iterate through each bundle $\\textit{offer}$. If the current shopping list $\\textit{cur}$ can use the bundle $\\textit{offer}$, i.e., the quantity of each item in $\\textit{cur}$ is not less than that in the bundle $\\textit{offer}$, then we can try to use this bundle. We subtract the quantity of each item in the bundle $\\textit{offer}$ from $\\textit{cur}$, obtaining a new shopping list $\\textit{nxt}$, then recursively calculate the minimum cost of $\\textit{nxt}$ and add the price of the bundle $\\textit{offer}[n]$, updating $\\textit{ans}$, i.e., $\\textit{ans} = \\min(\\textit{ans}, \\textit{offer}[n] + \\textit{dfs}(\\textit{nxt}))$.\n- Finally, return $\\textit{ans}$.\n\nTo avoid repeated calculations, we use a hash table $\\textit{f}$ to record the minimum cost corresponding to each state $\\textit{cur}$.\n\nThe time complexity is $O(n \\times k \\times m^n)$, where $n$ represents the types of items, and $k$ and $m$ respectively represent the number of bundles and the maximum demand for each type of item. The space complexity is $O(n \\times m^n)$." }, "is_english": true, "time_complexity": "O(n \\times k \\times m^n)", "space_complexity": "O(n \\times m^n)" }, { "problem_id": 639, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 640, "explanations": { "1": "We split the $equation$ by the equal sign `\"=\"` into left and right expressions, and compute the coefficient of `\"x\"` (denoted $x_i$) and the constant value (denoted $y_i$) for each side.\n\nThe equation is then transformed into: $x_1 \\times x + y_1 = x_2 \\times x + y_2$.\n\n- When $x_1 = x_2$: if $y_1 \\neq y_2$, there is no solution; if $y_1 = y_2$, there are infinite solutions.\n- When $x_1 \\neq x_2$: there is a unique solution $x = \\frac{y_2 - y_1}{x_1 - x_2}$.\n\nSimilar problems:\n\n- [592. Fraction Addition and Subtraction](https://github.com/doocs/leetcode/blob/main/solution/0500-0599/0592.Fraction%20Addition%20and%20Subtraction/README_EN.md)" }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 641, "explanations": { "1": "We can use an array to implement the circular deque. We maintain a pointer $\\textit{front}$ pointing to the front of the queue, a variable $\\textit{size}$ representing the number of elements in the queue, and a variable $\\textit{capacity}$ representing the queue's capacity. We use an array $\\textit{q}$ to store the elements.\n\nWhen $\\textit{insertFront}$ is called, we first check if the queue is full; if so, return $\\text{false}$. Otherwise, we move $\\textit{front}$ one position forward (using modular arithmetic for circular wrapping), insert the new element at $\\textit{front}$, and increment $\\textit{size}$ by 1.\n\nWhen $\\textit{insertLast}$ is called, we first check if the queue is full; if so, return $\\text{false}$. Otherwise, we compute the insertion position (using $\\textit{front}$ and $\\textit{size}$), insert the new element there, and increment $\\textit{size}$ by 1.\n\nWhen $\\textit{deleteFront}$ is called, we first check if the queue is empty; if so, return $\\text{false}$. Otherwise, we move $\\textit{front}$ one position backward (using modular arithmetic for circular wrapping) and decrement $\\textit{size}$ by 1.\n\nWhen $\\textit{deleteLast}$ is called, we first check if the queue is empty; if so, return $\\text{false}$. Otherwise, we decrement $\\textit{size}$ by 1.\n\nWhen $\\textit{getFront}$ is called, we first check if the queue is empty; if so, return $-1$. Otherwise, we return $\\textit{q}[\\textit{front}]$.\n\nWhen $\\textit{getRear}$ is called, we first check if the queue is empty; if so, return $-1$. Otherwise, we compute the position of the rear element (using $\\textit{front}$ and $\\textit{size}$) and return the element at that position.\n\nWhen $\\textit{isEmpty}$ is called, we check whether $\\textit{size}$ equals $0$.\n\nWhen $\\textit{isFull}$ is called, we check whether $\\textit{size}$ equals $\\textit{capacity}$.\n\nAll operations above have a time complexity of $O(1)$ and a space complexity of $O(k)$, where $k$ is the capacity of the deque." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(k)" }, { "problem_id": 642, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 643, "explanations": { "1": "We maintain a sliding window of length $k$, and for each window, we calculate the sum $s$ of the numbers within the window. We take the maximum sum $s$ as the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 644, "explanations": { "1": "We note that if the average value of a subarray with length greater than or equal to $k$ is $v$, then the maximum average number must be greater than or equal to $v$, otherwise the maximum average number must be less than $v$. Therefore, we can use binary search to find the maximum average number.\n\nWhat are the left and right boundaries of binary search? The left boundary $l$ must be the minimum value in the array, and the right boundary $r$ is the maximum value in the array. Next, we binary search the midpoint $mid$, and judge whether there exists a subarray with length greater than or equal to $k$ whose average value is greater than or equal to $mid$. If it exists, then we update the left boundary $l$ to $mid$, otherwise we update the right boundary $r$ to $mid$. When the difference between the left and right boundaries is less than a very small non-negative number, i.e., $r - l < \\epsilon$, we can get the maximum average number, where $\\epsilon$ represents a very small positive number, which can be $10^{-5}$.\n\nThe key to the problem is how to judge whether the average value of a subarray with length greater than or equal to $k$ is greater than or equal to $v$.\n\nWe assume that in the array $nums$, there is a subarray with length $j$, the elements are $a_1, a_2, \\cdots, a_j$, and its average value is greater than or equal to $v$, i.e.,\n\n$$\n\\frac{a_1 + a_2 + \\cdots + a_j}{j} \\geq v\n$$\n\nThen,\n\n$$\na_1 + a_2 + \\cdots + a_j \\geq v \\times j\n$$\n\nThat is,\n\n$$\n(a_1 - v) + (a_2 - v) + \\cdots + (a_j - v) \\geq 0\n$$\n\nWe can find that if we subtract $v$ from each element in the array $nums$, the original problem is transformed into a problem of whether the sum of the elements of a subarray with length greater than or equal to $k$ is greater than or equal to $0$. We can use a sliding window to solve this problem.\n\nFirst, we calculate the sum $s$ of the differences between the first $k$ elements and $v$. If $s \\geq 0$, it means that there exists a subarray with length greater than or equal to $k$ whose element sum is greater than or equal to $0$.\n\nOtherwise, we continue to traverse the element $nums[j]$. Suppose the current sum of the differences between the first $j$ elements and $v$ is $s_j$. Then we can maintain the minimum value $mi$ of the sum of the differences between the prefix sum and $v$ in the range $[0,..j-k]$. If $s_j \\geq mi$ exists, it means that there exists a subarray with length greater than or equal to $k$ whose element sum is greater than or equal to $0$, and we return $true$.\n\nOtherwise, we continue to traverse the element $nums[j]$ until the entire array is traversed.\n\nThe time complexity is $O(n \\times \\log M)$, where $n$ and $M$ are the length of the array $nums$ and the difference between the maximum and minimum values in the array, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(1)" }, { "problem_id": 645, "explanations": { "1": "We denote $s_1$ as the sum of all numbers from $[1,..n]$, $s_2$ as the sum of the numbers in the array $nums$ after removing duplicates, and $s$ as the sum of the numbers in the array $nums$.\n\nThen $s - s_2$ is the duplicate number, and $s_1 - s_2$ is the missing number.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $nums$. Extra space is needed to store the array after de-duplication.", "2": "We can also use a more intuitive method, using a hash table $cnt$ to count the occurrence of each number in the array $nums$.\n\nNext, iterate through $x \\in [1, n]$, if $cnt[x] = 2$, then $x$ is the duplicate number, if $cnt[x] = 0$, then $x$ is the missing number.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $nums$.", "3": "According to the properties of the XOR operation, for integer $x$, we have $x \\oplus x = 0$ and $x \\oplus 0 = x$. Therefore, if we perform the XOR operation on all elements in the array $nums$ and all numbers $i \\in [1, n]$, we can eliminate the numbers that appear twice, leaving only the XOR result of the missing number and the duplicate number, i.e., $xs = a \\oplus b$.\n\nSince these two numbers are not equal, there must be at least one bit in the XOR result that is $1$. We find the lowest bit of $1$ in the XOR result through the $lowbit$ operation, and then divide all numbers in the array $nums$ and all numbers $i \\in [1, n]$ into two groups according to whether this bit is $1$. In this way, the two numbers are divided into different groups. The XOR result of one group of numbers is $a$, and the XOR result of the other group is $b$. These two numbers are the answers we are looking for.\n\nNext, we only need to determine which of $a$ and $b$ is the duplicate number and which is the missing number. Therefore, iterate through the array $nums$, for the traversed number $x$, if $x=a$, then $a$ is the duplicate number, return $[a, b]$, otherwise, at the end of the iteration, return $[b, a]$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$, only using a constant size of extra space." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 646, "explanations": { "1": "We sort all pairs in ascending order by the second number, and use a variable $\\textit{pre}$ to maintain the maximum value of the second number of the selected pairs.\n\nWe traverse the sorted pairs. If the first number of the current pair is greater than $\\textit{pre}$, we can greedily select the current pair, increment the answer by one, and update $\\textit{pre}$ to the second number of the current pair.\n\nAfter the traversal, we return the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the number of pairs." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 647, "explanations": { "1": "We can enumerate the center position of each palindrome and expand outward to count the number of palindromic substrings. For a string of length $n$, there are $2n-1$ possible center positions (covering both odd-length and even-length palindromes). For each center, we expand outward until the palindrome condition is no longer satisfied, and count the number of palindromic substrings.\n\nThe time complexity is $O(n^2)$, where $n$ is the length of string $s$. The space complexity is $O(1)$.", "2": "In Manacher's algorithm, $p[i] - 1$ represents the maximum palindrome length centered at position $i$, and the number of palindromic substrings centered at position $i$ is $\\left \\lceil \\frac{p[i]-1}{2} \\right \\rceil$.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of string $s$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(1)" }, { "problem_id": 648, "explanations": { "1": "We can use a trie to store all the roots in the dictionary. Define the trie node class $\\text{Trie}$, which contains an array $\\text{children}$ of length $26$ to store child nodes, and a boolean variable $\\text{is\\_end}$ to mark whether it is a complete root.\n\nFor each root, we insert it into the trie. For each word in the sentence, we search for its shortest root in the trie. If found, we replace the word; otherwise, we keep it unchanged.\n\nThe time complexity is $O(n \\times |w| + L)$, and the space complexity is $O(n \\times |w|)$, where $n$ and $|w|$ are the number of roots in the dictionary and the average length, respectively, and $L$ is the total length of words in the sentence." }, "is_english": true, "time_complexity": "O(n \\times |w| + L)", "space_complexity": "O(n \\times |w|)" }, { "problem_id": 649, "explanations": { "1": "We create two queues $qr$ and $qd$ to record the indices of the Radiant and Dire senators, respectively. Then we start the simulation, where in each round we dequeue one senator from each queue and perform different operations based on their factions:\n\n- If the Radiant senator's index is less than the Dire senator's index, the Radiant senator can permanently ban the voting rights of the Dire senator. We add $n$ to the Radiant senator's index and enqueue it back to the end of the queue, indicating that this senator will participate in the next round of voting.\n- If the Dire senator's index is less than the Radiant senator's index, the Dire senator can permanently ban the voting rights of the Radiant senator. We add $n$ to the Dire senator's index and enqueue it back to the end of the queue, indicating that this senator will participate in the next round of voting.\n\nFinally, when there are only senators from one faction left in the queues, the senators from that faction win.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of senators." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 650, "explanations": { "1": "定义 $dfs(i)$ 为输出 $i$ 个字符的最少操作次数。初始化 `dfs(1)=0`。\n\n当 $i\\gt 1$ 时,有:\n\n$$\ndfs(i)=\\min _{j \\mid i} (dfs(\\frac{i}{j})+j, i), 2\\leq j\\lt i\n$$\n\n时间复杂度 $O(n\\sqrt{n})$。", "2": "记忆化搜索也可以改成动态规划。\n\n$$\ndp[i]=\\min _{j \\mid i} (dp[\\frac{i}{j}]+j, i), 2\\leq j\\lt i\n$$\n\n时间复杂度 $O(n\\sqrt{n})$。", "3": "" }, "is_english": false, "time_complexity": "O(n\\sqrt{n})", "space_complexity": null }, { "problem_id": 651, "explanations": { "1": "定义 $dp[i]$ 表示前 $i$ 个按键可以显示的最大个数。\n\n我们可以发现,要显示最多的 `A`,要么一直按 `A`,要么以 `Ctrl-V` 结束。\n\n- 一直按 `A` 的情况,满足 $dp[i] = i$。\n- 以 `Ctrl-V` 结束的情况,我们枚举对应的 `Ctrl-A` 的位置 $j$,可以得到 $dp[i]=max(dp[i], dp[j-1] \\times (i - j))$。\n\n时间复杂度 $O(n^2)$,空间复杂度 $O(n)$。" }, "is_english": false, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 652, "explanations": { "1": "后序遍历,序列化每个子树,用哈希表判断序列化的字符串出现次数是否等于 `2`,若是,说明这棵子树重复。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 653, "explanations": { "1": "DFS 遍历二叉搜索树,对于每个节点,判断 `k - node.val` 是否在哈希表中,如果在,则返回 `true`,否则将 `node.val` 加入哈希表中。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉搜索树的节点个数。", "2": "与方法一类似,只是使用 BFS 遍历二叉搜索树。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉搜索树的节点个数。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 654, "explanations": { "1": "先找到数组 $nums$ 的最大元素所在的位置 $i$,将 $nums[i]$ 作为根节点,然后递归左右两侧的子数组,构建左右子树。\n\n时间复杂度 $O(n^2)$,空间复杂度 $O(n)$,其中 $n$ 是数组的长度。", "2": "方法一中,每次查找区间最大值,需要 $O(n)$ 的时间,我们可以借助线段树,将每次查询区间最大值的时间降至 $O(\\log n)$。\n\n最多需要查询 $n$ 次,因此,总的时间复杂度为 $O(n \\times \\log n)$,空间复杂度 $O(n)$,其中 $n$ 是数组的长度。", "3": "题目表达了一个意思:如果 $nums$ 中间有一个数字 $v$,找出它左右两侧最大的数,这两个最大的数应该比 $v$ 小。\n\n了解单调栈的朋友,或许会注意到:\n\n当我们尝试向栈中压入一个数字 $v$ 时,如果栈顶元素比 $v$ 小,则循环弹出栈顶元素,并记录最后一个弹出的元素 $last$。那么循环结束,$last$ 必须位于 $v$ 的左侧,因为 $last$ 是 $v$ 的左侧最大的数。令 $node(val=v).left$ 指向 $last$。\n\n如果此时存在栈顶元素,栈顶元素一定大于 $v$。$v$ 成为栈顶元素的候选右子树节点。令 $stk.top().right$ 指向 $v$。然后 $v$ 入栈。\n\n遍历结束,栈底元素成为树的根节点。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。" }, "is_english": false, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 655, "explanations": { "1": "先通过 `DFS` 求二叉树的高度 $h$(高度从 `0` 开始),然后根据 $h$ 求得结果列表的行数 $m$ 和列数 $n$。\n\n根据 $m$, $n$ 初始化结果列表 `ans`,然后 `DFS` 遍历二叉树,依次在每个位置填入二叉树节点值(字符串形式)即可。\n\n时间复杂度 $O(h\\times 2^h)$,空间复杂度 $O(h)$。其中 $h$ 是二叉树的高度。忽略结果返回值的空间消耗。", "2": "方法一中,我们是通过 `DFS` 来求二叉树的高度,我们也可以改成 `BFS` 的方式,逐层往下扩展,那么扩展的层数就是二叉树的高度。\n\n同样,我们初始化结果列表 `ans`,然后 `BFS` 遍历二叉树,依次在每个位置填入二叉树节点值(字符串形式)即可。\n\n时间复杂度 $O(h\\times 2^h)$,空间复杂度 $O(h)$。其中 $h$ 是二叉树的高度。忽略结果返回值的空间消耗。" }, "is_english": false, "time_complexity": "O(h\\times 2^h)", "space_complexity": "O(h)" }, { "problem_id": 656, "explanations": { "1": "题目需要我们找到从下标 1 到下标 n 的最小花费路径,且字典序最小,我们可以使用动态规划求解。\n\n我们定义 $f[i]$ 表示从下标 $i$ 到下标 $n-1$ 的最小花费。如果 $coins[n - 1] = -1$,则不存在从下标 $n-1$ 到下标 $n-1$ 的路径,直接返回空数组即可。否则 $f[n - 1] = coins[n - 1]$。\n\n接下来,我们从下标 $n-2$ 开始,逆向遍历数组,对于下标 $i$,如果 $coins[i] = -1$,则 $f[i] = \\infty$,否则 $f[i] = \\min_{j = i + 1}^{min(n - 1, i + maxJump)} f[j] + coins[i]$。\n\n然后我们判断 $f[0]$ 是否为 $\\infty$,如果是,则不存在一条满足条件的路径,返回空数组即可。否则,我们的总花费为 $s = f[0]$,我们从下标 0 开始,向后遍历数组,如果 $f[i] = s$,则说明从下标 $i$ 到下标 $n-1$ 的花费为 $s$,我们将 $s$ 减去 $coins[i]$,并将下标 $i+1$ 加入到结果数组中,直到遍历到下标 $n-1$,返回结果数组即可。\n\n时间复杂度 $O(n \\times m)$,空间复杂度 $O(n)$。其中 $n$ 和 $m$ 分别为数组的长度和最大跳跃长度。" }, "is_english": false, "time_complexity": "O(n \\times m)", "space_complexity": "O(n)" }, { "problem_id": 657, "explanations": { "1": "We can maintain a coordinate $(x, y)$ to represent the robot's movement in the horizontal and vertical directions.\n\nTraverse the string $\\textit{moves}$ and update the coordinate $(x, y)$ based on the current character:\n\n- If the current character is `'U'`, then $y$ increases by $1$;\n- If the current character is `'D'$, then $y$ decreases by $1$;\n- If the current character is `'L'$, then $x$ decreases by $1$;\n- If the current character is `'R'$, then $x$ increases by $1$.\n\nFinally, check if both $x$ and $y$ are $0$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $\\textit{moves}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 658, "explanations": { "1": "将 $arr$ 中的所有元素按照与 $x$ 的距离从小到大进行排列。取前 $k$ 个元素排序后返回。\n\n时间复杂度 $O(nlogn)$。", "2": "直觉上,有序数组 $arr$ 最靠近 $x$ 的 $k$ 个数必然是一段连续的子数组。\n\n我们可以声明头尾指针,记为 $l$ 和 $r$,然后根据 $x-arr[l]$ 与 $arr[r-1] - x$ 的大小比较结果缩小范围,直到 $r - l = k$。\n\n时间复杂度 $O(n)$。", "3": "在方法二的基础上,我们更进一步,查找大小为 $k$ 的窗口的左边界。\n\n时间复杂度 $O(logn)$。" }, "is_english": false, "time_complexity": "O(nlogn)", "space_complexity": null }, { "problem_id": 659, "explanations": { "1": "由于题目中的子序列是由连续整数组成的,因此,只要知道子序列的最后一个数以及子序列的长度,就能够确定子序列。\n\n我们可以使用哈希表存储每个子序列的最后一个数,使用优先队列存储当前数作为子序列的末尾时,子序列的长度。我们要优先选择长度较短的子序列,因此使用小根堆。\n\n遍历数组 `nums`,对于当前遍历到的数 `num`,如果 `num` 不能加入到任何子序列中,那么我们就创建一个新的子序列,长度为 1;否则,我们就将 `num` 加入到某个子序列中,具体的子序列是哪个呢?我们可以从 `num - 1` 对应的子序列中取出一个长度最短的子序列,将 `num` 加入到该子序列中,然后将该子序列的最后一个数更新为 `num`,同时将该子序列的长度加 1。\n\n如果我们遍历完数组 `nums`,优先队列中所有的子序列的长度都不小于 3,那么我们就可以将数组 `nums` 分割成若干个子序列,否则,我们就无法将数组 `nums` 分割成若干个子序列。\n\n时间复杂度 $O(n\\log n)$,其中 $n$ 是数组 `nums` 的长度。空间复杂度 $O(n)$。" }, "is_english": false, "time_complexity": "O(n\\log n)", "space_complexity": "O(n)" }, { "problem_id": 660, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 661, "explanations": { "1": "We create a 2D array $\\textit{ans}$ of size $m \\times n$, where $\\textit{ans}[i][j]$ represents the smoothed value of the cell in the $i$-th row and $j$-th column of the image.\n\nFor $\\textit{ans}[i][j]$, we traverse the cell in the $i$-th row and $j$-th column of $\\textit{img}$ and its surrounding 8 cells, calculate their sum $s$ and count $cnt$, then compute the average value $s / cnt$ and store it in $\\textit{ans}[i][j]$.\n\nAfter the traversal, we return $\\textit{ans}$.\n\nThe time complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns of $\\textit{img}$, respectively. Ignoring the space consumption of the answer array, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(1)" }, { "problem_id": 662, "explanations": { "1": "对节点进行编号,初始根节点编号为 $1$。\n\n对于一个编号为 `i` 的节点,它的左节点编号为 `i<<1`,右节点编号为 `i<<1|1`。\n\n采用 BFS 进行层序遍历,求每层的宽度时,用该层的最大节点编号减去最小节点编号再加一即可。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点数。", "2": "定义 `dfs(root, depth, i)` 表示从深度为 `depth`,且编号为 `i` 的节点 `root` 开始往下搜索。记录每一层最先访问到的节点的编号。访问到当前层其它节点时,求当前节点编号与当前层最小编号的差再加一,更新当前层的最大宽度。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点数。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 663, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 664, "explanations": { "1": "We define $f[i][j]$ as the minimum operations to print $s[i..j]$, with the initial value $f[i][j]=\\infty$, and the answer is $f[0][n-1]$, where $n$ is the length of string $s$.\n\nConsider $f[i][j]$, if $s[i] = s[j]$, we can print $s[j]$ when print $s[i]$, so we can ignore $s[j]$ and continue to print $s[i+1..j-1]$. If $s[i] \\neq s[j]$, we need to print the substring separately, i.e. $s[i..k]$ and $s[k+1..j]$, where $k \\in [i,j)$. So we can have the following transition equation:\n\n$$\nf[i][j]=\n\\begin{cases}\n1, & \\textit{if } i=j \\\\\nf[i][j-1], & \\textit{if } s[i]=s[j] \\\\\n\\min_{i \\leq k < j} \\{f[i][k]+f[k+1][j]\\}, & \\textit{otherwise}\n\\end{cases}\n$$\n\nWe can enumerate $i$ from large to small and $j$ from small to large, so that we can ensure that $f[i][j-1]$, $f[i][k]$ and $f[k+1][j]$ have been calculated when we calculate $f[i][j]$.\n\nThe time complexity is $O(n^3)$ and the space complexity is $O(n^2)$. Where $n$ is the length of string $s$." }, "is_english": true, "time_complexity": "O(n^3)", "space_complexity": "O(n^2)" }, { "problem_id": 665, "explanations": { "1": "在最多改变一个元素的情况下,若要将数组变成非递减数列,那么数组最多只能有一个位置,其左右两侧的元素不满足非递减数列的要求。也即数组中只会存在一个位置 $i$,使得 $nums[i] \\gt nums[i+1]$。\n\n因此,我们可以从左到右遍历数组,找到第一个不满足非递减数列要求的位置 $i$,然后将 $nums[i]$ 修改为 $nums[i+1]$ 或者将 $nums[i+1]$ 修改为 $nums[i]$,再判断修改后的数组是否满足非递减数列的要求。如果满足,则返回 `true`,否则返回 `false`。\n\n遍历结束后,如果没有找到不满足非递减数列要求的位置,说明数组本身就是非递减数列,返回 `true`。\n\n时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组的长度。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 666, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 667, "explanations": { "1": "先按照 `1, n, 2, n-1, 3,...` 构造答案数据 `ans` 的前 $k$ 个数,共产生 $k-1$ 个不同的整数。然后根据 $k$ 的奇偶性确定从哪个数开始构造下一个数。\n\n时间复杂度 $O(n)$,忽略答案数组的空间消耗,空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 668, "explanations": { "1": "题目可以转换为,求有多少个数不超过 x。对于每一行 i,所有数都是 i 的倍数,不超过 x 的个数有 `x / i` 个。\n\n二分枚举 x,累加每一行不超过 x 的个数,得到 cnt。找到 `cnt >= k` 的最小 x。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 669, "explanations": { "1": "判断 `root.val` 与 `low` 和 `high` 的大小关系:\n\n- 若 `root.val` 大于 `high`,说明当前 `root` 节点与其右子树所有节点的值均大于 `high`,那么递归修剪 `root.left` 即可;\n- 若 `root.val` 小于 `low`,说明当前 `root` 节点与其左子树所有节点的值均小于 `low`,那么递归修剪 `root.right` 即可;\n- 若 `root.val` 在 `[low, high]` 之间,说明当前 `root` 应该保留,递归修剪 `root.left`, `root.right`,并且返回 `root`。\n\n递归的终止条件是 `root` 节点为空。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉搜索树的节点个数。", "2": "我们先循环判断 `root`,若 `root.val` 不在 `[low, high]` 之间,那么直接将 `root` 置为对应的左孩子或右孩子,循环直至 `root` 为空或者 `root.val` 在 `[low, high]` 之间。\n\n若此时 `root` 为空,直接返回。否则,说明 `root` 是一个需要保留的节点。接下来只需要分别迭代修剪 `root` 的左右子树。\n\n以左子树 `node = root.left` 为例:\n\n- 若 `node.left.val` 小于 `low`,那么 `node.left` 及其左孩子均不满足条件,我们直接将 `node.left` 置为 `node.left.right`;\n- 否则,我们将 `node` 置为 `node.left`;\n- 循环判断,直至 `node.left` 为空。\n\n右子树的修剪过程与之类似。\n\n时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 是二叉搜索树的节点个数。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 670, "explanations": { "1": "First, we convert the number into a string $s$. Then, we traverse the string $s$ from right to left, using an array or hash table $d$ to record the position of the maximum number to the right of each number (it can be the position of the number itself).\n\nNext, we traverse $d$ from left to right. If $s[i] < s[d[i]]$, we swap them and exit the traversal process.\n\nFinally, we convert the string $s$ back into a number, which is the answer.\n\nThe time complexity is $O(\\log M)$, and the space complexity is $O(\\log M)$. Here, $M$ is the range of the number $num$.", "2": "" }, "is_english": true, "time_complexity": "O(\\log M)", "space_complexity": "O(\\log M)" }, { "problem_id": 671, "explanations": { "1": "直接 DFS 遍历二叉树,找到大于 `root.val` 的最小值。若不存在,则返回 -1。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点数。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 672, "explanations": { "1": "观察灯泡开关随按钮操作的变化规律,我们可以发现,位置 $i$ 与 $i+6$ 的灯泡,开关状态始终保持一致,因此,我们只需要考虑最多前 $n=6$ 个灯泡的开关状态。\n\n另外,对于每个按钮,若操作偶数次,相当于没执行操作;若操作奇数次,相当于操作了 $1$ 次。同时,不同按钮操作的先后顺序,也不影响结果。\n\n题目有 $4$ 个按钮,每个按钮有“操作偶数次”和“操作奇数次”两种状态,因此总共有 $2^4$ 种按钮状态。\n\n二进制枚举按钮的状态 `mask`,若当前状态满足题目 `presses` 的限制,我们可以通过位运算,模拟操作对应按钮,最终得到灯泡的状态 $t$,去重后的 $t$ 的数量就是答案。\n\n时空复杂度均为常数级别。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 673, "explanations": { "1": "We define $f[i]$ as the length of the longest increasing subsequence ending with $nums[i]$, and $cnt[i]$ as the number of longest increasing subsequences ending with $nums[i]$. Initially, $f[i]=1$, $cnt[i]=1$. Also, we define $mx$ as the length of the longest increasing subsequence, and $ans$ as the number of longest increasing subsequences.\n\nFor each $nums[i]$, we enumerate all elements $nums[j]$ in $nums[0:i-1]$. If $nums[j] < nums[i]$, then $nums[i]$ can be appended after $nums[j]$ to form a longer increasing subsequence. If $f[i] < f[j] + 1$, it means the length of the longest increasing subsequence ending with $nums[i]$ has increased, so we need to update $f[i]=f[j]+1$ and $cnt[i]=cnt[j]$. If $f[i]=f[j]+1$, it means we have found a longest increasing subsequence with the same length as before, so we need to increase $cnt[i]$ by $cnt[j]$. Then, if $mx < f[i]$, it means the length of the longest increasing subsequence has increased, so we need to update $mx=f[i]$ and $ans=cnt[i]$. If $mx=f[i]$, it means we have found a longest increasing subsequence with the same length as before, so we need to increase $ans$ by $cnt[i]$.\n\nFinally, we return $ans$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$.", "2": "We can use a binary indexed tree to maintain the length and count of the longest increasing subsequence in the prefix interval. We remove duplicates from the array $nums$ and sort it to get the array $arr$. Then we enumerate each element $x$ in $nums$, find the position $i$ of $x$ in the array $arr$ by binary search, then query the length and count of the longest increasing subsequence in $[1,i-1]$, denoted as $v$ and $cnt$, then update the length and count of the longest increasing subsequence in $[i]$ to $v+1$ and $\\max(cnt,1)$. Finally, we query the length and count of the longest increasing subsequence in $[1,m]$, where $m$ is the length of the array $arr$, which is the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 674, "explanations": { "1": "We can traverse the array $nums$, using a variable $cnt$ to record the length of the current consecutive increasing sequence. Initially, $cnt = 1$.\n\nThen, we start from index $i = 1$ and traverse the array $nums$ to the right. Each time we traverse, if $nums[i - 1] < nums[i]$, it means that the current element can be added to the consecutive increasing sequence, so we set $cnt = cnt + 1$, and then update the answer to $ans = \\max(ans, cnt)$. Otherwise, it means that the current element cannot be added to the consecutive increasing sequence, so we set $cnt = 1$.\n\nAfter the traversal ends, we return the answer $ans$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$.", "2": "We can also use two pointers $i$ and $j$ to find each consecutive increasing sequence, and find the length of the longest consecutive increasing sequence as the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 675, "explanations": { "1": "题目的一个关键信息是“所有树的高度都不同”,要按照从小到大的顺序依次砍树,因此,我们先遍历树林,找出所有树及对应的坐标点。然后将树按照高度升序排列。\n\n接下来就是找相邻两个点之间的最短距离。可以用 BFS,A\\* 算法优化搜索。\n\nA\\* 算法主要思想如下:\n\n1. 将 BFS 队列转换为优先队列(小根堆);\n1. 队列中的每个元素为 `(dist[state] + f(state), state)`,`dist[state]` 表示从起点到当前 state 的距离,`f(state)` 表示从当前 state 到终点的估计距离,这两个距离之和作为堆排序的依据;\n1. 当终点第一次出队时,说明找到了从起点到终点的最短路径,直接返回对应的 step;\n1. `f(state)` 是估价函数,并且估价函数要满足 `f(state) <= g(state)`,其中 `g(state)` 表示 state 到终点的真实距离;\n1. A\\* 算法只能保证终点第一次出队时,即找到了一条从起点到终点的最小路径,不能保证其他点出队时也是从起点到当前点的最短路径。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 676, "explanations": { "1": "We can use a trie to store all the words in the dictionary. For each word we search, we use depth-first search. Specifically, we start from the root of the trie. For the current letter we are traversing, we first check whether there is a child node that is the same as it. If there is, we continue to traverse downwards. Otherwise, we need to check whether there are remaining modification times. If not, it means that it cannot be matched, so we return false. If there are remaining modification times, we can try to modify the current letter and continue to traverse downwards. If the child node corresponding to the modified letter exists, it means that it can be matched, otherwise it means that it cannot be matched, so we return false. If we traverse to the end of the word and the number of modifications is exactly 1, it means that it can be matched, so we return true.\n\nThe time complexity is $O(n \\times l + q \\times l \\times |\\Sigma|)$, and the space complexity is $O(n \\times l)$, where $n$ and $l$ are the number of words in the dictionary and the average length of the words, respectively, and $q$ is the number of words searched. In addition, $|\\Sigma|$ represents the size of the character set. Here, the character set is lowercase English letters, so $|\\Sigma|=26$." }, "is_english": true, "time_complexity": "O(n \\times l + q \\times l \\times |\\Sigma|)", "space_complexity": "O(n \\times l)" }, { "problem_id": 677, "explanations": { "1": "We use a hash table $d$ to store key-value pairs and a trie $t$ to store the prefix sums of the key-value pairs. Each node in the trie contains two pieces of information:\n\n- `val`: the total sum of the values of the key-value pairs with this node as the prefix\n- `children`: an array of length $26$ that stores the child nodes of this node\n\nWhen inserting a key-value pair $(key, val)$, we first check if the key exists in the hash table. If it does, the `val` of each node in the trie needs to subtract the original value of the key and then add the new value. If it does not exist, the `val` of each node in the trie needs to add the new value.\n\nWhen querying the prefix sum, we start from the root node of the trie and traverse the prefix string. If the current node's child nodes do not contain the character, it means the prefix does not exist in the trie, and we return $0$. Otherwise, we continue to traverse the next character until we finish traversing the prefix string and return the `val` of the current node.\n\nIn terms of time complexity, the time complexity of inserting a key-value pair is $O(n)$, where $n$ is the length of the key. The time complexity of querying the prefix sum is $O(m)$, where $m$ is the length of the prefix.\n\nThe space complexity is $O(n \\times m \\times C)$, where $n$ and $m$ are the number of keys and the maximum length of the keys, respectively; and $C$ is the size of the character set, which is $26$ in this problem." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n \\times m \\times C)" }, { "problem_id": 678, "explanations": { "1": "Let `dp[i][j]` be true if and only if the interval `s[i], s[i+1], ..., s[j]` can be made valid. Then `dp[i][j]` is true only if:\n\n- `s[i]` is `'*'`, and the interval `s[i+1], s[i+2], ..., s[j]` can be made valid;\n- or, `s[i]` can be made to be `'('`, and there is some `k` in `[i+1, j]` such that `s[k]` can be made to be `')'`, plus the two intervals cut by `s[k]` (`s[i+1: k] and s[k+1: j+1]`) can be made valid;\n\n- Time Complexity: $O(n^3)$, where $n$ is the length of the string. There are $O(n^2)$ states corresponding to entries of dp, and we do an average of $O(n)$ work on each state.\n- Space Complexity: $O(n^2)$.", "2": "Scan twice, first from left to right to make sure that each of the closing brackets is matched successfully, and second from right to left to make sure that each of the opening brackets is matched successfully.\n\n- Time Complexity: $O(n)$, where $n$ is the length of the string.\n- Space Complexity: $O(1)$." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 679, "explanations": { "1": "We design a function $dfs(nums)$, where $nums$ represents the current number sequence. The function returns a boolean value indicating whether there exists a permutation that makes this number sequence equal to $24$.\n\nIf the length of $nums$ is $1$, we return $true$ only when this number is $24$, otherwise we return $false$.\n\nOtherwise, we can enumerate any two numbers $a$ and $b$ in $nums$ as the left and right operands, and enumerate the operator $op$ between $a$ and $b$. The result of $a\\ op\\ b$ can be used as an element of the new number sequence. We add it to the new number sequence and remove $a$ and $b$ from $nums$, then recursively call the $dfs$ function. If it returns $true$, it means we have found a permutation that makes this number sequence equal to $24$, and we return $true$.\n\nIf none of the enumerated cases return $true$, we return $false$." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 680, "explanations": { "1": "We use two pointers to point to the left and right ends of the string, respectively. Each time, we check whether the characters pointed to by the two pointers are the same. If they are not the same, we check whether the string is a palindrome after deleting the character corresponding to the left pointer, or we check whether the string is a palindrome after deleting the character corresponding to the right pointer. If the characters pointed to by the two pointers are the same, we move both pointers towards the middle by one position, until the two pointers meet.\n\nIf we have not encountered a situation where the characters pointed to by the pointers are different by the end of the traversal, then the string itself is a palindrome, and we return `true`.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 681, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 682, "explanations": { "1": "We can use a stack to simulate this process.\n\nTraverse $\\textit{operations}$, for each operation:\n\n- If it is `+`, add the top two elements of the stack and push the result onto the stack;\n- If it is `D`, multiply the top element of the stack by 2 and push the result onto the stack;\n- If it is `C`, pop the top element of the stack;\n- If it is a number, push the number onto the stack.\n\nFinally, sum all the elements in the stack to get the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of $\\textit{operations}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 683, "explanations": { "1": "We can use a Binary Indexed Tree to maintain the prefix sum of the bulbs. Every time we turn on a bulb, we update the corresponding position in the Binary Indexed Tree. Then we check if the $k$ bulbs to the left or right of the current bulb are all turned off and the $(k+1)$-th bulb is already turned on. If either of these conditions is met, we return the current day.\n\nThe time complexity is $O(n \\times \\log n)$ and the space complexity is $O(n)$, where $n$ is the number of bulbs." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 684, "explanations": { "1": "According to the problem description, we need to find an edge that can be removed so that the remaining part is a tree with $n$ nodes. We can traverse each edge and determine whether the two nodes of this edge are in the same connected component. If they are in the same connected component, it means this edge is redundant and can be removed, so we directly return this edge. Otherwise, we merge the two nodes connected by this edge into the same connected component.\n\nThe time complexity is $O(n \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the number of edges.", "2": "Here is a template approach using Union-Find for your reference.\n\nThe time complexity is $O(n \\alpha(n))$, and the space complexity is $O(n)$. Here, $n$ is the number of edges, and $\\alpha(n)$ is the inverse Ackermann function, which can be considered a very small constant." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(n)" }, { "problem_id": 685, "explanations": { "1": "According to the problem description, for a rooted tree, the in-degree of the root node is $0$, and the in-degree of other nodes is $1$. After adding an edge to the tree, there can be the following three scenarios:\n\n1. The added edge points to a non-root node, and the in-degree of that node becomes $2$. In this case, there is no directed cycle in the graph:\n\n ```plaintext\n 1\n / \\\n v v\n 2-->3\n ```\n\n2. The added edge points to a non-root node, and the in-degree of that node becomes $2$. In this case, there is a directed cycle in the graph:\n\n ```plaintext\n 1\n |\n v\n 2 <--> 3\n ```\n\n3. The added edge points to the root node, and the in-degree of the root node becomes $1$. In this case, there is a directed cycle in the graph, but there are no nodes with an in-degree of $2$.\n\n ```plaintext\n 1\n /^\n v \\\n 2-->3\n ```\n\nTherefore, we first calculate the in-degree of each node. If there exists a node with an in-degree of $2$, we identify the two edges corresponding to that node, denoted as $\\textit{dup}[0]$ and $\\textit{dup}[1]$. If deleting $\\textit{dup}[1]$ results in the remaining edges not forming a tree, then $\\textit{dup}[0]$ is the edge that needs to be deleted; otherwise, $\\textit{dup}[1]$ is the edge that needs to be deleted.\n\nIf there are no nodes with an in-degree of $2$, we traverse the array $\\textit{edges}$. For each edge $(u, v)$, we use the union-find data structure to maintain connectivity between nodes. If $u$ and $v$ are already connected, it indicates that there is a directed cycle in the graph, and the current edge is the one that needs to be deleted.\n\nThe time complexity is $O(n \\log n)$, and the space complexity is $O(n)$, where $n$ is the number of edges.", "2": "Here is a template approach using Union-Find for your reference.\n\nThe time complexity is $O(n \\alpha(n))$, and the space complexity is $O(n)$. Here, $n$ is the number of edges, and $\\alpha(n)$ is the inverse Ackermann function, which can be considered a very small constant." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(n)" }, { "problem_id": 686, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 687, "explanations": { "1": "We design a function $\\textit{dfs}(root)$, which represents the longest univalue path length extending downward with the $\\textit{root}$ node as one endpoint of the path.\n\nIn $\\textit{dfs}(root)$, we first recursively call $\\textit{dfs}(root.\\textit{left})$ and $\\textit{dfs}(root.\\textit{right})$ to get two return values $\\textit{l}$ and $\\textit{r}$. These two return values represent the longest univalue path lengths extending downward with the left and right children of the $\\textit{root}$ node as one endpoint of the path, respectively.\n\nIf the $\\textit{root}$ has a left child and $\\textit{root}.\\textit{val} = \\textit{root}.\\textit{left}.\\textit{val}$, then the longest univalue path length extending downward with the left child of the $\\textit{root}$ as one endpoint of the path should be $\\textit{l} + 1$; otherwise, this length is $0$. If the $\\textit{root}$ has a right child and $\\textit{root}.\\textit{val} = \\textit{root}.\\textit{right}.\\textit{val}$, then the longest univalue path length extending downward with the right child of the $\\textit{root}$ as one endpoint of the path should be $\\textit{r} + 1$; otherwise, this length is $0$.\n\nAfter recursively calling the left and right children, we update the answer to $\\max(\\textit{ans}, \\textit{l} + \\textit{r})$, which is the longest univalue path length passing through the $\\textit{root}$ with the $\\textit{root}$ as one endpoint of the path.\n\nFinally, the $\\textit{dfs}(root)$ function returns the longest univalue path length extending downward with the $\\textit{root}$ as one endpoint of the path, which is $\\max(\\textit{l}, \\textit{r})$.\n\nIn the main function, we call $\\textit{dfs}(root)$ to get the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 688, "explanations": { "1": "We define $f[h][i][j]$ to represent the probability that the knight remains on the board after taking $h$ steps starting from position $(i, j)$. The final answer is $f[k][\\textit{row}][\\textit{column}]$.\n\nWhen $h=0$, the knight is definitely on the board, so the probability is $1$, i.e., $f[0][i][j]=1$.\n\nWhen $h \\gt 0$, the probability that the knight is at position $(i, j)$ can be derived from the probabilities of the $8$ possible positions it could have come from in the previous step, i.e.,\n\n$$\nf[h][i][j] = \\sum_{x, y} f[h - 1][x][y] \\times \\frac{1}{8}\n$$\n\nwhere $(x, y)$ is one of the $8$ positions the knight can move to from $(i, j)$.\n\nThe final answer is $f[k][\\textit{row}][\\textit{column}]$.\n\nThe time complexity is $O(k \\times n^2)$, and the space complexity is $O(k \\times n^2)$. Here, $k$ and $n$ are the given number of steps and the size of the board, respectively." }, "is_english": true, "time_complexity": "O(k \\times n^2)", "space_complexity": "O(k \\times n^2)" }, { "problem_id": 689, "explanations": { "1": "We use a sliding window to enumerate the position of the third subarray, while maintaining the maximum sum and its position of the first two non-overlapping subarrays.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$.", "2": "We can preprocess to get the prefix sum array $s$ of the array $nums$, where $s[i] = \\sum_{j=0}^{i-1} nums[j]$. Then for any $i$, $j$, $s[j] - s[i]$ is the sum of the subarray $[i, j)$.\n\nNext, we use dynamic programming to maintain two arrays $pre$ and $suf$ of length $n$, where $pre[i]$ represents the maximum sum and its starting position of the subarray of length $k$ within the range $[0, i]$, and $suf[i]$ represents the maximum sum and its starting position of the subarray of length $k$ within the range $[i, n)$.\n\nThen, we enumerate the starting position $i$ of the middle subarray. The sum of the three subarrays is $pre[i-1][0] + suf[i+k][0] + (s[i+k] - s[i])$, where $pre[i-1][0]$ represents the maximum sum of the subarray of length $k$ within the range $[0, i-1]$, $suf[i+k][0]$ represents the maximum sum of the subarray of length $k$ within the range $[i+k, n)$, and $(s[i+k] - s[i])$ represents the sum of the subarray of length $k$ within the range $[i, i+k)$. We find the starting positions of the three subarrays corresponding to the maximum sum.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 690, "explanations": { "1": "We use a hash table $d$ to store all employee information, where the key is the employee's ID, and the value is the employee object. Then we start a depth-first search from the given employee ID. Each time we traverse to an employee, we add the employee's importance to the answer, and recursively traverse all the subordinates of the employee, adding the importance of the subordinates to the answer as well.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of employees." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 691, "explanations": { "1": "We notice that the length of the string `target` does not exceed 15. We can use a binary number of length 15 to represent whether each character of `target` has been spelled out. If the $i$th bit is 1, it means that the $i$th character of `target` has been spelled out; otherwise, it has not been spelled out.\n\nWe define an initial state 0, which means that all characters have not been spelled out. Then we use the Breadth-First Search (BFS) method, starting from the initial state. Each time we search, we enumerate all the stickers. For each sticker, we try to spell out each character of `target`. If we spell out a character, we set the $i$th bit of the corresponding binary number to 1, indicating that the character has been spelled out. Then we continue to search until we spell out all the characters of `target`.\n\nThe time complexity is $O(2^n \\times m \\times (l + n))$, and the space complexity is $O(2^n)$. Where $n$ is the length of the string `target`, and $m$ and $l$ are the number of stickers and the average length of the stickers, respectively." }, "is_english": true, "time_complexity": "O(2^n \\times m \\times (l + n))", "space_complexity": "O(2^n)" }, { "problem_id": 692, "explanations": { "1": "We can use a hash table $\\textit{cnt}$ to record the frequency of each word. Then, we sort the key-value pairs in the hash table by value, and if the values are the same, we sort by key.\n\nFinally, we take the first $k$ keys.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the number of words." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 693, "explanations": { "1": "We cyclically right-shift $n$ until it becomes $0$, checking whether the binary bits of $n$ appear alternately. If during the loop we find that $0$ and $1$ do not appear alternately, we directly return $\\textit{false}$. Otherwise, when the loop ends, we return $\\textit{true}$.\n\nThe time complexity is $O(\\log n)$, and the space complexity is $O(1)$.", "2": "Assuming $\\text{01}$ appears alternately, we can convert all trailing bits to $\\text{1}$ through misaligned XOR. Adding $\\text{1}$ gives us a power of $2$, which is a number $n$ (where $n$ has only one bit that is $\\text{1}$). Then, using $\\text{n} \\& (\\text{n} + 1)$ can eliminate the last $\\text{1}$ bit.\n\nAt this point, check if it equals $\\text{0}$. If so, the assumption holds, and it is an alternating $\\text{01}$ sequence.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 694, "explanations": { "1": "我们遍历网格中的每个位置 $(i, j)$,如果该位置为 $1$,则以其为起始节点开始进行深度优先搜索,过程中将 $1$ 修改为 $0$,并且将搜索的方向记录下来,等搜索结束后将方向序列加入哈希表中,最后返回哈希表中不同方向序列的数量即可。\n\n时间复杂度 $O(m \\times n)$,空间复杂度 $O(m \\times n)$。其中 $m$ 和 $n$ 分别为网格的行数和列数。" }, "is_english": false, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 695, "explanations": { "1": "我们可以遍历每一个格子 $(i, j)$,从每个格子开始进行深度优先搜索,如果搜索到的格子是陆地,就将当前格子标记为已访问,并且继续搜索上、下、左、右四个方向的格子。搜索结束后,计算标记的陆地的数量,即为岛屿的面积。我们找出最大的岛屿面积即为答案。\n\n时间复杂度 $O(m \\times n)$,空间复杂度 $O(m \\times n)$。其中 $m$ 和 $n$ 分别是二维数组的行数和列数。" }, "is_english": false, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 696, "explanations": { "1": "We can iterate through the string $s$, using a variable $\\textit{pre}$ to record the count of the previous consecutive characters, and another variable $\\textit{cur}$ to record the count of the current consecutive characters. The number of valid substrings ending with the current character is $\\min(\\textit{pre}, \\textit{cur})$. We accumulate $\\min(\\textit{pre}, \\textit{cur})$ to the answer, assign the value of $\\textit{cur}$ to $\\textit{pre}$, and continue iterating through string $s$ until the end.\n\nThe time complexity is $O(n)$, where $n$ is the length of string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 697, "explanations": { "1": "遍历数组,用哈希表记录数组每个元素出现的次数,以及首次、末次出现的位置。然后遍历哈希表,获取元素出现次数最多(可能有多个)且首末位置差最小的数。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组长度。", "2": "" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 698, "explanations": { "1": "According to the problem description, we need to partition the array $\\textit{nums}$ into $k$ subsets such that the sum of each subset is equal. Therefore, we first sum all the elements in $\\textit{nums}$. If the total sum cannot be divided by $k$, it means we cannot partition the array into $k$ subsets, and we return $\\textit{false}$ early.\n\nIf the total sum can be divided by $k$, let's denote the expected sum of each subset as $s$. Then, we create an array $\\textit{cur}$ of length $k$ to represent the current sum of each subset.\n\nWe sort the array $\\textit{nums}$ in descending order (to reduce the number of searches), and then start from the first element, trying to add it to each subset in $\\textit{cur}$ one by one. If adding $\\textit{nums}[i]$ to a subset $\\textit{cur}[j]$ makes the subset's sum exceed $s$, it means it cannot be placed in that subset, and we can skip it. Additionally, if $\\textit{cur}[j]$ is equal to $\\textit{cur}[j - 1]$, it means we have already completed the search for $\\textit{cur}[j - 1]$, and we can skip the current search.\n\nIf we can add all elements to $\\textit{cur}$, it means we can partition the array into $k$ subsets, and we return $\\textit{true}$.", "2": "Similar to Solution 1, we first check whether the array $\\textit{nums}$ can be partitioned into $k$ subsets. If it cannot be divided by $k$, we directly return $\\textit{false}$.\n\nLet $s$ be the expected sum of each subset, and let $\\textit{state}$ represent the current partitioning state of the elements. For the $i$-th number, if the $i$-th bit of $\\textit{state}$ is $0$, it means the $i$-th element has not been partitioned.\n\nOur goal is to form $k$ subsets with a sum of $s$ from all elements. Let $t$ be the current sum of the subset. When the $i$-th element is not partitioned:\n\n- If $t + \\textit{nums}[i] \\gt s$, it means the $i$-th element cannot be added to the current subset. Since we sort the array $\\textit{nums}$ in ascending order, all elements from position $i$ onwards cannot be added to the current subset, and we directly return $\\textit{false}$.\n- Otherwise, add the $i$-th element to the current subset, change the state to $\\textit{state} | 2^i$, and continue searching for unpartitioned elements. Note that if $t + \\textit{nums}[i] = s$, it means we can form a subset with a sum of $s$. The next step is to reset $t$ to zero (which can be achieved by $(t + \\textit{nums}[i]) \\bmod s$) and continue partitioning the next subset.\n\nTo avoid repeated searches, we use an array $\\textit{f}$ of length $2^n$ to record the search results for each state. The array $\\textit{f}$ has three possible values:\n\n- `0` indicates that the current state has not been searched yet;\n- `-1`: indicates that the current state cannot be partitioned into $k$ subsets;\n- `1`: indicates that the current state can be partitioned into $k$ subsets.\n\nThe time complexity is $O(n \\times 2^n)$, and the space complexity is $O(2^n)$. Here, $n$ represents the length of the array $\\textit{nums}$. For each state, we need to traverse the array $\\textit{nums}$, which has a time complexity of $O(n)$. The total number of states is $2^n$, so the overall time complexity is $O(n \\times 2^n)$.", "3": "We can use dynamic programming to solve this problem.\n\nWe define $f[i]$ to represent whether there exists $k$ subsets that meet the requirements when the current selected numbers' state is $i$. Initially, $f[0] = \\text{true}$, and the answer is $f[2^n - 1]$, where $n$ is the length of the array $\\textit{nums}$. Additionally, we define $cur[i]$ to represent the sum of the last subset when the current selected numbers' state is $i$.\n\nWe enumerate the states $i$ in the range $[0, 2^n]$. For each state $i$, if $f[i]$ is $\\text{false}$, we skip it. Otherwise, we enumerate any number $\\textit{nums}[j]$ in the array $\\textit{nums}$. If $cur[i] + \\textit{nums}[j] > s$, we break the enumeration loop because the subsequent numbers are larger and cannot be placed in the current subset. Otherwise, if the $j$-th bit of the binary representation of $i$ is $0$, it means the current $\\textit{nums}[j]$ has not been selected. We can place it in the current subset, change the state to $i | 2^j$, update $cur[i | 2^j] = (cur[i] + \\textit{nums}[j]) \\bmod s$, and set $f[i | 2^j] = \\text{true}$.\n\nFinally, we return $f[2^n - 1]$.\n\nThe time complexity is $O(n \\times 2^n)$, and the space complexity is $O(2^n)$. Here, $n$ represents the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times 2^n)", "space_complexity": "O(2^n)" }, { "problem_id": 699, "explanations": { "1": "According to the problem description, we need to maintain a set of intervals that support modification and query operations. In this case, we can use a segment tree to solve the problem.\n\nA segment tree divides the entire interval into multiple non-contiguous sub-intervals, with the number of sub-intervals not exceeding $\\log(width)$, where $width$ is the length of the interval. To update the value of an element, we only need to update $\\log(width)$ intervals, and these intervals are all contained within a larger interval that includes the element. When modifying intervals, we need to use **lazy propagation** to ensure efficiency.\n\n- Each node of the segment tree represents an interval;\n- The segment tree has a unique root node representing the entire statistical range, such as $[1, n]$;\n- Each leaf node of the segment tree represents a primitive interval of length 1, $[x, x]$;\n- For each internal node $[l, r]$, its left child is $[l, \\textit{mid}]$, and its right child is $[\\textit{mid} + 1, r]$, where $\\textit{mid} = \\frac{l + r}{2}$;\n\nFor this problem, the information maintained by the segment tree nodes includes:\n\n1. The maximum height $v$ of the blocks in the interval\n2. Lazy propagation marker $add$\n\nAdditionally, since the range of the number line is very large, up to $10^8$, we use dynamic node creation.\n\nIn terms of time complexity, each query and modification has a time complexity of $O(\\log n)$, and the total time complexity is $O(n \\log n)$. The space complexity is $O(n)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(n)" }, { "problem_id": 700, "explanations": { "1": "We check if the current node is null or if the current node's value equals the target value. If so, we return the current node.\n\nOtherwise, if the current node's value is greater than the target value, we recursively search the left subtree; otherwise, we recursively search the right subtree.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 701, "explanations": { "1": "If the root node is null, we directly create a new node with the value $\\textit{val}$ and return it.\n\nIf the root node's value is greater than $\\textit{val}$, we recursively insert $\\textit{val}$ into the left subtree and update the root of the left subtree with the returned root node.\n\nIf the root node's value is less than $\\textit{val}$, we recursively insert $\\textit{val}$ into the right subtree and update the root of the right subtree with the returned root node.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 702, "explanations": { "1": "First, we define a pointer $r = 1$. Each time, we check if the value at position $r$ is less than the target value. If it is, we multiply $r$ by $2$, i.e., shift it left by one bit, until the value at position $r$ is greater than or equal to the target value. At this point, we can determine that the target value is within the interval $[r / 2, r]$.\n\nNext, we define a pointer $l = r / 2$, and then we can use the binary search method to find the position of the target value within the interval $[l, r]$.\n\nThe time complexity is $O(\\log M)$, where $M$ is the position of the target value. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log M)", "space_complexity": "O(1)" }, { "problem_id": 703, "explanations": { "1": "We maintain a priority queue (min heap) $\\textit{minQ}$.\n\nInitially, we add the elements of the array $\\textit{nums}$ to $\\textit{minQ}$ one by one, ensuring that the size of $\\textit{minQ}$ does not exceed $k$. The time complexity is $O(n \\times \\log k)$.\n\nEach time a new element is added, if the size of $\\textit{minQ}$ exceeds $k$, we pop the top element of the heap to ensure that the size of $\\textit{minQ}$ is $k$. The time complexity is $O(\\log k)$.\n\nIn this way, the elements in $\\textit{minQ}$ are the largest $k$ elements in the array $\\textit{nums}$, and the top element of the heap is the $k^{th}$ largest element.\n\nThe space complexity is $O(k)$." }, "is_english": true, "time_complexity": "O(n \\times \\log k)", "space_complexity": "O(k)" }, { "problem_id": 704, "explanations": { "1": "We define the left boundary $l=0$ and the right boundary $r=n-1$ for binary search.\n\nIn each iteration, we calculate the middle position $\\textit{mid}=(l+r)/2$, then compare the size of $\\textit{nums}[\\textit{mid}]$ and $\\textit{target}$.\n\n- If $\\textit{nums}[\\textit{mid}] \\geq \\textit{target}$, it means $\\textit{target}$ is in the left half, so we move the right boundary $r$ to $\\textit{mid}$;\n- Otherwise, it means $\\textit{target}$ is in the right half, so we move the left boundary $l$ to $\\textit{mid}+1$.\n\nThe loop ends when $l 1 \\textit{ and } s1[i-1] = s2[j-1] \\\\\nf[i - 1][j], & s1[i-1] \\ne s2[j-1]\n\\end{cases}\n$$\n\nNext, we only need to traverse $\\textit{s1}$. If $f[i][n] \\gt 0$, update the starting position and length of the shortest substring. Finally, return the shortest substring.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the lengths of strings $\\textit{s1}$ and $\\textit{s2}$, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 728, "explanations": { "1": "We define a function $\\textit{check}(x)$ to determine whether $x$ is a self-dividing number. The implementation idea of the function is as follows:\n\nWe use $y$ to record the value of $x$, and then continuously divide $y$ by $10$ until $y$ is $0$. During this process, we check whether the last digit of $y$ is $0$, or whether $x$ cannot be divided by the last digit of $y$. If either of these conditions is met, then $x$ is not a self-dividing number, and we return $\\text{false}$. Otherwise, after traversing all the digits, we return $\\text{true}$.\n\nFinally, we traverse all the numbers in the interval $[\\textit{left}, \\textit{right}]$, and for each number, we call $\\textit{check}(x)$. If it returns $\\text{true}$, we add this number to the answer array.\n\nThe time complexity is $O(n \\times \\log_{10} M)$, where $n$ is the number of elements in the interval $[\\textit{left}, \\textit{right}]$, and $M = \\textit{right}$, which is the maximum value in the interval." }, "is_english": true, "time_complexity": "O(n \\times \\log_{10} M)", "space_complexity": null }, { "problem_id": 729, "explanations": { "1": "We can use an ordered set to store the schedule. An ordered set can perform insert, delete, and search operations in $O(\\log n)$ time. The elements in the ordered set are sorted by the $\\textit{endTime}$ of the schedule in ascending order.\n\nWhen calling the $\\text{book}(start, end)$ method, we search for the first schedule in the ordered set with an end time greater than $\\textit{start}$. If it exists and its start time is less than $\\textit{end}$, it means there is a double booking, and we return $\\text{false}$. Otherwise, we insert $\\textit{end}$ as the key and $\\textit{start}$ as the value into the ordered set and return $\\text{true}$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the number of schedules." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 730, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 731, "explanations": { "1": "We can use the concept of a difference array to record the booking status at each time point. Then, we traverse all the time points and count the booking status at the current time point. If the number of bookings exceeds $2$, we return $\\textit{false}$. Otherwise, we return $\\textit{true}$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$, where $n$ is the number of bookings.", "2": "A segment tree divides the entire interval into multiple non-contiguous subintervals, with the number of subintervals not exceeding $\\log(\\textit{width})$. To update the value of an element, only $\\log(\\textit{width})$ intervals need to be updated, and these intervals are all contained within a larger interval that includes the element. When modifying intervals, a **lazy mark** is used to ensure efficiency.\n\n- Each node of the segment tree represents an interval;\n- The segment tree has a unique root node representing the entire statistical range, such as $[1, N]$;\n- Each leaf node of the segment tree represents a unit interval of length 1, $[x, x]$;\n- For each internal node $[l, r]$, its left child is $[l, \\textit{mid}]$ and its right child is $[\\textit{mid} + 1, r]$, where $\\textit{mid} = \\lfloor(l + r) / 2\\rfloor$ (i.e., floor division).\n\nFor this problem, the segment tree nodes maintain the following information:\n\n1. The maximum number of bookings within the interval $v$\n2. Lazy mark $\\textit{add}$\n\nSince the time range is $10^9$, which is very large, we use dynamic node creation.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the number of bookings." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 732, "explanations": { "1": "A segment tree divides the entire interval into multiple non-contiguous subintervals, with the number of subintervals not exceeding $\\log(\\text{width})$. To update the value of an element, we only need to update $\\log(\\text{width})$ intervals, and these intervals are all contained within a larger interval that includes the element. When modifying intervals, we use **lazy propagation** to ensure efficiency.\n\n- Each node of the segment tree represents an interval.\n- The segment tree has a unique root node representing the entire range, such as $[1, N]$.\n- Each leaf node of the segment tree represents a unit interval of length $1$, $[x, x]$.\n- For each internal node $[l, r]$, its left child is $[l, \\text{mid}]$ and its right child is $[\\text{mid} + 1, r]$, where $\\text{mid} = \\lfloor(l + r) / 2\\rfloor$ (i.e., floor division).\n\nFor this problem, the segment tree nodes maintain the following information:\n\n1. The maximum number of times the interval has been booked, $v$.\n2. Lazy propagation marker, $\\text{add}$.\n\nSince the time range is $10^9$, which is very large, we use dynamic node creation.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$, where $n$ is the number of bookings." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 733, "explanations": { "1": "We denote the initial pixel's color as $\\textit{oc}$. If $\\textit{oc}$ is not equal to the target color $\\textit{color}$, we start a depth-first search from $(\\textit{sr}, \\textit{sc})$ to change the color of all eligible pixels to the target color.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the number of rows and columns of the 2D array $\\textit{image}$, respectively.", "2": "We first check if the initial pixel's color is equal to the target color. If it is, we return the original image directly. Otherwise, we can use the breadth-first search method, starting from $(\\textit{sr}, \\textit{sc})$, to change the color of all eligible pixels to the target color.\n\nSpecifically, we define a queue $\\textit{q}$ and add the initial pixel $(\\textit{sr}, \\textit{sc})$ to the queue. Then, we continuously take pixels $(i, j)$ from the queue, change their color to the target color, and add the pixels in the four directions (up, down, left, right) that have the same original color as the initial pixel to the queue. When the queue is empty, we have completed the flood fill.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the number of rows and columns of the 2D array $\\textit{image}$, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 734, "explanations": { "1": "First, we check if the lengths of $\\textit{sentence1}$ and $\\textit{sentence2}$ are equal. If they are not equal, return $\\text{false}$.\n\nThen we use a hash table $\\textit{s}$ to store all similar word pairs. For each word pair $[x, y]$ in $\\textit{similarPairs}$, we add $x$ and $y$ to the hash table $\\textit{s}$.\n\nNext, we traverse $\\textit{sentence1}$ and $\\textit{sentence2}$. For each position $i$, if $\\textit{sentence1}[i]$ is not equal to $\\textit{sentence2}[i]$, and $(\\textit{sentence1}[i], \\textit{sentence2}[i])$ and $(\\textit{sentence2}[i], \\textit{sentence1}[i])$ are not in the hash table $\\textit{s}$, then return $\\text{false}$.\n\nIf the traversal ends without returning $\\text{false}$, it means $\\textit{sentence1}$ and $\\textit{sentence2}$ are similar, so return $\\text{true}$.\n\nThe time complexity is $O(L)$, and the space complexity is $O(L)$, where $L$ is the sum of the lengths of all strings in the problem." }, "is_english": true, "time_complexity": "O(L)", "space_complexity": "O(L)" }, { "problem_id": 735, "explanations": { "1": "We traverse each asteroid $x$ from left to right. Since each asteroid may collide with multiple asteroids before it, we consider using a stack to store.\n\n- For the current asteroid, if $x>0$, it will definitely not collide with the previous asteroid, and we can directly push $x$ into the stack.\n- Otherwise, if the stack is not empty and the top element of the stack is greater than $0$, and the top element of the stack is less than $-x$, then the top element of the stack corresponds to the asteroid will explode, we loop to the top element of the stack Pop out until the condition is not satisfied. At this time, if the top element of the stack is equal to $-x$, then the two asteroids will explode, and we only need to pop the top element of the stack; if the stack is empty, or the top element of the stack is less than $0$, then the current asteroid will not collide, we will push $x$ into the stack.\n\nFinally, we return the elements in the stack as the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $asteroids$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 736, "explanations": { "1": "时间复杂度 $O(n)$。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": null }, { "problem_id": 737, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 738, "explanations": { "1": "从数字 `n` 的高位开始,找到第一个不满足 $n_{i-1} \\le n_i$ 的位置 $i$。\n\n然后,从后往前,只要发现 $n_{i-1} \\gt n_i$,就将 $n_{i-1}$ 减 1。\n\n最后将位置 $i$ 之后的所有数字都置为 9 即可。\n\n时间复杂度 $O(\\log n)$,空间复杂度 $O(\\log n)$。" }, "is_english": false, "time_complexity": "O(\\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 739, "explanations": { "1": "This problem requires us to find the position of the first element greater than each element to its right, which is a typical application scenario for a monotonic stack.\n\nWe traverse the array $\\textit{temperatures}$ from right to left, maintaining a stack $\\textit{stk}$ that is monotonically increasing from top to bottom in terms of temperature. The stack stores the indices of the array elements. For each element $\\textit{temperatures}[i]$, we continuously compare it with the top element of the stack. If the temperature corresponding to the top element of the stack is less than or equal to $\\textit{temperatures}[i]$, we pop the top element of the stack in a loop until the stack is empty or the temperature corresponding to the top element of the stack is greater than $\\textit{temperatures}[i]$. At this point, the top element of the stack is the first element greater than $\\textit{temperatures}[i]$ to its right, and the distance is $\\textit{stk.top()} - i$. We update the answer array accordingly. Then we push $\\textit{temperatures}[i]$ onto the stack and continue traversing.\n\nAfter the traversal, we return the answer array.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{temperatures}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 740, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 741, "explanations": { "1": "According to the problem description, the player starts from $(0, 0)$, reaches $(n-1, n-1)$, and then returns to the starting point $(0, 0)$. We can consider the player as starting from $(0, 0)$ to $(n-1, n-1)$ twice.\n\nTherefore, we define $f[k][i_1][i_2]$ as the maximum number of cherries that can be picked when both have walked $k$ steps and reached $(i_1, k-i_1)$ and $(i_2, k-i_2)$ respectively. Initially, $f[0][0][0] = grid[0][0]$. The initial values of other $f[k][i_1][i_2]$ are negative infinity. The answer is $\\max(0, f[2n-2][n-1][n-1])$.\n\nAccording to the problem description, we can get the state transition equation:\n\n$$\nf[k][i_1][i_2] = \\max(f[k-1][x_1][x_2] + t, f[k][i_1][i_2])\n$$\n\nWhere $t$ represents the number of cherries at positions $(i_1, k-i_1)$ and $(i_2, k-i_2)$, and $x_1, x_2$ represent the previous step positions of $(i_1, k-i_1)$ and $(i_2, k-i_2)$ respectively.\n\nThe time complexity is $O(n^3)$, and the space complexity is $O(n^3)$. Where $n$ is the side length of the grid." }, "is_english": true, "time_complexity": "O(n^3)", "space_complexity": "O(n^3)" }, { "problem_id": 742, "explanations": { "1": "First, we use depth-first search to construct an undirected graph $g$, where $g[node]$ represents the set of nodes adjacent to the node $node$. Then we start a breadth-first search from node $k$ until we find a leaf node, which is the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 743, "explanations": { "1": "We define $\\textit{g}[u][v]$ to represent the edge weight from node $u$ to node $v$. If there is no edge between node $u$ and node $v$, then $\\textit{g}[u][v] = +\\infty$.\n\nWe maintain an array $\\textit{dist}$, where $\\textit{dist}[i]$ represents the shortest path length from node $k$ to node $i$. Initially, we set all $\\textit{dist}[i]$ to $+\\infty$, except for $\\textit{dist}[k - 1] = 0$. We define an array $\\textit{vis}$, where $\\textit{vis}[i]$ indicates whether node $i$ has been visited. Initially, we set all $\\textit{vis}[i]$ to $\\text{false}$.\n\nEach time, we find the unvisited node $t$ with the smallest distance, and then perform relaxation operations centered on node $t$. For each node $j$, if $\\textit{dist}[j] > \\textit{dist}[t] + \\textit{g}[t][j]$, we update $\\textit{dist}[j] = \\textit{dist}[t] + \\textit{g}[t][j]$.\n\nFinally, we return the maximum value in $\\textit{dist}$ as the answer. If the answer is $+\\infty$, it means there are unreachable nodes, and we return $-1$.\n\nThe time complexity is $O(n^2 + m)$, and the space complexity is $O(n^2)$. Here, $n$ and $m$ are the number of nodes and edges, respectively.", "2": "We can use a priority queue (heap) to optimize the naive Dijkstra algorithm.\n\nWe define $\\textit{g}[u]$ to represent all adjacent edges of node $u$, and $\\textit{dist}[u]$ to represent the shortest path length from node $k$ to node $u$. Initially, we set all $\\textit{dist}[u]$ to $+\\infty$, except for $\\textit{dist}[k - 1] = 0$.\n\nWe define a priority queue $\\textit{pq}$, where each element is $(\\textit{d}, u)$, representing the distance $\\textit{d}$ from node $u$ to node $k$. Each time, we take out the node $(\\textit{d}, u)$ with the smallest distance from $\\textit{pq}$. If $\\textit{d} > $\\textit{dist}[u]$, we skip this node. Otherwise, we traverse all adjacent edges of node $u$. For each adjacent edge $(v, w)$, if $\\textit{dist}[v] > \\textit{dist}[u] + w$, we update $\\textit{dist}[v] = \\textit{dist}[u] + w$ and add $(\\textit{dist}[v], v)$ to $\\textit{pq}$.\n\nFinally, we return the maximum value in $\\textit{dist}$ as the answer. If the answer is $+\\infty$, it means there are unreachable nodes, and we return $-1$.\n\nThe time complexity is $O(m \\times \\log m + n)$, and the space complexity is $O(n + m)$. Here, $n$ and $m$ are the number of nodes and edges, respectively." }, "is_english": true, "time_complexity": "O(n^2 + m)", "space_complexity": "O(n^2)" }, { "problem_id": 744, "explanations": { "1": "Since `letters` is sorted in non-decreasing order, we can use binary search to find the smallest character that is larger than `target`.\n\nWe define the left boundary of the binary search as $l = 0$, and the right boundary as $r = n$. For each binary search, we calculate the middle position $mid = (l + r) / 2$. If $letters[mid] > \\textit{target}$, it means we need to continue searching in the left half, so we set $r = mid$. Otherwise, we need to continue searching in the right half, so we set $l = mid + 1$.\n\nFinally, we return $letters[l \\mod n]$.\n\nThe time complexity is $O(\\log n)$, where $n$ is the length of `letters`. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 745, "explanations": { "1": "遍历 $words$ 的每个单词 $w$,将 $w$ 的所有前缀、后缀对存放到哈希表中。", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 746, "explanations": { "1": "We design a function $\\textit{dfs}(i)$, which represents the minimum cost required to climb the stairs starting from the $i$-th step. Therefore, the answer is $\\min(\\textit{dfs}(0), \\textit{dfs}(1))$.\n\nThe execution process of the function $\\textit{dfs}(i)$ is as follows:\n\n- If $i \\ge \\textit{len(cost)}$, it means the current position has exceeded the top of the stairs, and there is no need to climb further, so return $0$;\n- Otherwise, we can choose to climb $1$ step with a cost of $\\textit{cost}[i]$, then recursively call $\\textit{dfs}(i + 1)$; or we can choose to climb $2$ steps with a cost of $\\textit{cost}[i]$, then recursively call $\\textit{dfs}(i + 2)$;\n- Return the minimum cost between these two options.\n\nTo avoid repeated calculations, we use memoization search, saving the results that have already been calculated in an array or hash table.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{cost}$.", "2": "We define $f[i]$ as the minimum cost needed to reach the $i$-th stair. Initially, $f[0] = f[1] = 0$, and the answer is $f[n]$.\n\nWhen $i \\ge 2$, we can reach the $i$-th stair directly from the $(i - 1)$-th stair with one step, or from the $(i - 2)$-th stair with two steps. Therefore, we have the state transition equation:\n\n$$\nf[i] = \\min(f[i - 1] + \\textit{cost}[i - 1], f[i - 2] + \\textit{cost}[i - 2])\n$$\n\nThe final answer is $f[n]$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{cost}$.", "3": "We notice that the state transition equation for $f[i]$ only depends on $f[i - 1]$ and $f[i - 2]$. Therefore, we can use two variables $f$ and $g$ to alternately record the values of $f[i - 2]$ and $f[i - 1]$, thus optimizing the space complexity to $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 747, "explanations": { "1": "We can traverse the array $nums$ to find the maximum value $x$ and the second largest value $y$ in the array. If $x \\ge 2y$, then return the index of $x$, otherwise return $-1$.\n\nWe can also first find the maximum value $x$ in the array and find the index $k$ of the maximum value $x$ at the same time. Then traverse the array again. If we find an element $y$ outside of $k$ that satisfies $x < 2y$, then return $-1$. Otherwise, return $k$ after the traversal ends.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 748, "explanations": { "1": "First, we use a hash table or an array $cnt$ of length $26$ to count the frequency of each letter in the string `licensePlate`. Note that we convert all letters to lowercase for counting.\n\nThen, we traverse each word $w$ in the array `words`. If the length of the word $w$ is longer than the length of the answer $ans$, we directly skip this word. Otherwise, we use another hash table or an array $t$ of length $26$ to count the frequency of each letter in the word $w$. If for any letter, the frequency of this letter in $t$ is less than the frequency of this letter in $cnt$, we can also directly skip this word. Otherwise, we have found a word that meets the conditions, and we update the answer $ans$ to the current word $w$.\n\nThe time complexity is $O(n \\times |\\Sigma|)$, and the space complexity is $O(|\\Sigma|)$. Here, $n$ is the length of the array `words`, and $\\Sigma$ is the character set. In this case, the character set is all lowercase letters, so $|\\Sigma| = 26$." }, "is_english": true, "time_complexity": "O(n \\times |\\Sigma|)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 749, "explanations": { "1": "DFS 找到每个病毒区域 `areas[i]`,同时记录每个区域边界节点 `boundaries[i]` 以及周长 `c[i]`。\n\n接着对威胁最大的病毒区域进行隔离,累加所需的防火墙数量。\n\n剩余的病毒区域向外感染一个区域。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 750, "explanations": { "1": "We enumerate each row as the bottom of the rectangle. For the current row, if both column $i$ and column $j$ are $1$, then we use a hash table to find out how many of the previous rows have both columns $i$ and $j$ as $1$. This is the number of rectangles with $(i, j)$ as the bottom right corner, and we add this number to the answer. Then we add $(i, j)$ to the hash table and continue to enumerate the next pair $(i, j)$.\n\nThe time complexity is $O(m \\times n^2)$, and the space complexity is $O(n^2)$. Here, $m$ and $n$ are the number of rows and columns of the matrix, respectively." }, "is_english": true, "time_complexity": "O(m \\times n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 751, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 752, "explanations": { "1": "直接用朴素 BFS。", "2": "本题也可以用双向 BFS 优化搜索空间,从而提升效率。\n\n双向 BFS 是 BFS 常见的一个优化方法,主要实现思路如下:\n\n1. 创建两个队列 q1, q2 分别用于“起点 -> 终点”、“终点 -> 起点”两个方向的搜索;\n2. 创建两个哈希表 m1, m2 分别记录访问过的节点以及对应的扩展次数(步数);\n3. 每次搜索时,优先选择元素数量较少的队列进行搜索扩展,如果在扩展过程中,搜索到另一个方向已经访问过的节点,说明找到了最短路径;\n4. 只要其中一个队列为空,说明当前方向的搜索已经进行不下去了,说明起点到终点不连通,无需继续搜索。\n\n```python\nwhile q1 and q2:\n if len(q1) <= len(q2):\n # 优先选择较少元素的队列进行扩展\n extend(m1, m2, q1)\n else:\n extend(m2, m1, q2)\n\n\ndef extend(m1, m2, q):\n # 新一轮扩展\n for _ in range(len(q)):\n p = q.popleft()\n step = m1[p]\n for t in next(p):\n if t in m1:\n # 此前已经访问过\n continue\n if t in m2:\n # 另一个方向已经搜索过,说明找到了一条最短的连通路径\n return step + 1 + m2[t]\n q.append(t)\n m1[t] = step + 1\n```", "3": "A\\* 算法主要思想如下:\n\n1. 将 BFS 队列转换为优先队列(小根堆);\n1. 队列中的每个元素为 `(dist[state] + f(state), state)`,`dist[state]` 表示从起点到当前 state 的距离,`f(state)` 表示从当前 state 到终点的估计距离,这两个距离之和作为堆排序的依据;\n1. 当终点第一次出队时,说明找到了从起点到终点的最短路径,直接返回对应的 step;\n1. `f(state)` 是估价函数,并且估价函数要满足 `f(state) <= g(state)`,其中 `g(state)` 表示 state 到终点的真实距离;\n1. A\\* 算法只能保证终点第一次出队时,即找到了一条从起点到终点的最小路径,不能保证其他点出队时也是从起点到当前点的最短路径。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 753, "explanations": { "1": "We can construct a directed graph based on the description in the problem: each point is considered as a length $n-1$ $k$-string, and each edge carries a character from $0$ to $k-1$. If there is a directed edge $e$ from point $u$ to point $v$, and the character carried by $e$ is $c$, then the last $k-1$ characters of $u+c$ form the string $v$. At this point, the edge $u+c$ represents a password of length $n$.\n\nIn this directed graph, there are $k^{n-1}$ points, each point has $k$ outgoing edges and $k$ incoming edges. Therefore, this directed graph has an Eulerian circuit, and the path traversed by the Eulerian circuit is the answer to the problem.\n\nThe time complexity is $O(k^n)$, and the space complexity is $O(k^n)$." }, "is_english": true, "time_complexity": "O(k^n)", "space_complexity": "O(k^n)" }, { "problem_id": 754, "explanations": { "1": "Due to symmetry, each time we can choose to move left or right, so we can take the absolute value of $\\textit{target}$.\n\nDefine $s$ as the current position, and use the variable $k$ to record the number of moves. Initially, both $s$ and $k$ are $0$.\n\nWe keep adding to $s$ in a loop until $s \\ge \\textit{target}$ and $(s - \\textit{target}) \\bmod 2 = 0$. At this point, the number of moves $k$ is the answer, and we return it directly.\n\nWhy? Because if $s \\ge \\textit{target}$ and $(s - \\textit{target}) \\bmod 2 = 0$, we only need to change the sign of the positive integer $\\frac{s - \\textit{target}}{2}$ to negative, so that $s$ equals $\\textit{target}$. Changing the sign of a positive integer essentially means changing the direction of the move, but the actual number of moves remains the same.\n\nThe time complexity is $O(\\sqrt{\\left | \\textit{target} \\right | })$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\sqrt{\\left | \\textit{target} \\right | })", "space_complexity": "O(1)" }, { "problem_id": 755, "explanations": { "1": "We can simulate the process of each unit of water dropping. Each time a drop falls, we first try to move left. If it can move to a lower height, it moves to the lowest height; if it cannot move to a lower height, we try to move right. If it can move to a lower height, it moves to the lowest height; if it cannot move to a lower height, it rises at the current position.\n\nThe time complexity is $O(v \\times n)$, and the space complexity is $O(1)$, where $v$ and $n$ are the number of water drops and the length of the height array, respectively." }, "is_english": true, "time_complexity": "O(v \\times n)", "space_complexity": "O(1)" }, { "problem_id": 756, "explanations": { "1": "We define a hash table $d$ to store the allowed triangular patterns, where the key is a pair of two characters and the value is the corresponding list of characters, indicating that the two characters can form a triangular pattern with each item in the value list being the top of the triangle.\n\nStarting from the bottom layer, for every two adjacent characters in each layer, if they can form a triangular pattern, we add the top character of the triangular pattern to the character list at the corresponding position in the next layer, then recursively process the next layer.\n\nWhen the recursion reaches a single character, it means we have successfully built to the top of the pyramid, and we return $\\textit{true}$. If at some layer, two adjacent characters cannot form a triangular pattern, we return $\\textit{false}$." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 757, "explanations": { "1": "We want to select as few integer points as possible on the number line such that each interval contains at least two points. A classic and effective strategy is to sort intervals by their right endpoints and try to place selected points towards the right side of intervals, so that these points can cover more subsequent intervals.\n\nFirst, sort all intervals by the following rules:\n\n1. Sort by right endpoint in ascending order;\n2. If right endpoints are equal, sort by left endpoint in descending order.\n\nThe reason for this sorting is: intervals with smaller right endpoints have less \"operational space\" and should be satisfied first; when right endpoints are equal, intervals with larger left endpoints are narrower and should be prioritized.\n\nNext, we use two variables $s$ and $e$ to record the **second-to-last point** and **last point** that are common to all currently processed intervals. Initially, $s = e = -1$, indicating that no points have been placed yet.\n\nThen we process the sorted intervals $[a, b]$ one by one, and discuss three cases based on their relationship with $\\{s, e\\}$:\n\n1. **If $a \\leq s$**:\n The current interval already contains both points $s$ and $e$, so no additional points are needed.\n\n2. **If $s < a \\leq e$**:\n The current interval only contains one point (i.e., $e$), and needs one more point. To make the new point most helpful for subsequent intervals, we choose the rightmost point $b$ in the interval. Update $\\textit{ans} = \\textit{ans} + 1$, and set the new two points to $\\{e, b\\}$.\n\n3. **If $a > e$**:\n The current interval does not contain either of the existing two points, so two points need to be added. The optimal choice is to place $\\{b - 1, b\\}$ at the rightmost side of the interval. Update $\\textit{ans} = \\textit{ans} + 2$, and set the new two points to $\\{b - 1, b\\}$.\n\nFinally, return the total number of points placed, $\\textit{ans}$.\n\nThe time complexity is $O(n \\times \\log n)$ and the space complexity is $O(\\log n)$, where $n$ is the number of intervals." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 758, "explanations": { "1": "相似题目:\n\n- [1065. 字符串的索引对](https://github.com/doocs/leetcode/blob/main/solution/1000-1099/1065.Index%20Pairs%20of%20a%20String/README.md)\n- [616. 给字符串添加加粗标签](https://github.com/doocs/leetcode/blob/main/solution/0600-0699/0616.Add%20Bold%20Tag%20in%20String/README.md)" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 759, "explanations": { "1": "We can merge all employees' working time intervals into a single list, then sort and merge the overlapping intervals. Finally, we traverse the merged interval list to find the free time periods between adjacent intervals.\n\nThe time complexity is $O(mn \\log(mn))$ and the space complexity is $O(mn)$, where $m$ is the number of employees and $n$ is the number of working intervals per employee." }, "is_english": true, "time_complexity": "O(mn \\log(mn))", "space_complexity": "O(mn)" }, { "problem_id": 760, "explanations": { "1": "We use a hash table $\\textit{d}$ to store each element of the array $\\textit{nums2}$ and its corresponding index. Then we iterate through the array $\\textit{nums1}$, and for each element $\\textit{nums1}[i]$, we retrieve its corresponding index from the hash table $\\textit{d}$ and store it in the result array.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 761, "explanations": { "1": "We can treat the special binary sequence as \"valid parentheses\", where $1$ represents an opening parenthesis and $0$ represents a closing parenthesis. For example, \"11011000\" can be viewed as \"(()(()))\".\n\nSwapping two consecutive non-empty special substrings is equivalent to swapping two adjacent valid parentheses. We can use recursion to solve this problem.\n\nWe treat each \"valid parenthesis\" in string $s$ as a part, process it recursively, and finally sort them to get the final answer.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$, where $n$ is the length of string $s$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 762, "explanations": { "1": "In the problem, both $\\textit{left}$ and $\\textit{right}$ are within the range of $10^6$, and since $2^{20} = 1048576$, the number of $1$s in binary representation can be at most $20$. The prime numbers within $20$ are $[2, 3, 5, 7, 11, 13, 17, 19]$.\n\nWe enumerate each number in the range $[\\textit{left},.. \\textit{right}]$, count the number of $1$s in its binary representation, and then check if this count is a prime number. If it is, we increment the answer by one.\n\nThe time complexity is $O(n\\times \\log m)$, where $n = \\textit{right} - \\textit{left} + 1$ and $m$ is the maximum number in the range $[\\textit{left},.. \\textit{right}]$." }, "is_english": true, "time_complexity": "O(n\\times \\log m)", "space_complexity": null }, { "problem_id": 763, "explanations": { "1": "We first use an array or hash table $\\textit{last}$ to record the last occurrence of each letter in the string $s$.\n\nNext, we use a greedy approach to partition the string into as many segments as possible.\n\nTraverse the string $s$ from left to right, while maintaining the start index $j$ and end index $i$ of the current segment, both initially set to $0$.\n\nFor each letter $c$ visited, get the last occurrence position $\\textit{last}[c]$. Since the end index of the current segment must not be less than $\\textit{last}[c]$, let $\\textit{mx} = \\max(\\textit{mx}, \\textit{last}[c])$.\n\nWhen visiting the index $\\textit{mx}$, it means the current segment ends. The index range of the current segment is $[j,.. i]$, and the length is $i - j + 1$. We add this length to the result array. Then set $j = i + 1$ and continue to find the next segment.\n\nRepeat the above process until the string traversal is complete to get the lengths of all segments.\n\nTime complexity is $O(n)$, and space complexity is $O(|\\Sigma|)$. Where $n$ is the length of the string $s$, and $|\\Sigma|$ is the size of the character set. In this problem, $|\\Sigma| = 26$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 764, "explanations": { "1": "我们定义 $dp[i][j]$ 表示以 $(i, j)$ 为中心的最大加号标志的阶数,答案即为所有 $dp[i][j]$ 的最大值。\n\n我们可以发现,对于每个 $(i, j)$,其最大加号标志的阶数不会超过其上下左右四个方向上连续的 $1$ 的个数的最小值。因此,我们可以预处理出每个位置上下左右四个方向上连续的 $1$ 的个数,然后遍历所有的 $(i, j)$,求出 $dp[i][j]$ 的最大值即可。\n\n时间复杂度 $O(n^2)$,空间复杂度 $O(n^2)$。其中 $n$ 为网格的边长。" }, "is_english": false, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 765, "explanations": { "1": "We can assign a number to each pair of couples. Person with number $0$ and $1$ corresponds to couple $0$, person with number $2$ and $3$ corresponds to couple $1$, and so on. In other words, the person corresponding to $row[i]$ has a couple number of $\\lfloor \\frac{row[i]}{2} \\rfloor$.\n\nIf there are $k$ pairs of couples who are seated incorrectly with respect to each other, i.e., if $k$ pairs of couples are in the same permutation cycle, it will take $k-1$ swaps for all of them to be seated correctly.\n\nWhy? Consider the following: we first adjust the positions of a couple to their correct seats. After this, the problem reduces from $k$ couples to $k-1$ couples. This process continues, and when $k = 1$, the number of swaps required is $0$. Therefore, if $k$ pairs of couples are in the wrong positions, we need $k-1$ swaps.\n\nThus, we only need to traverse the array once, use union-find to determine how many permutation cycles there are. Suppose there are $x$ cycles, and the size of each cycle (in terms of couple pairs) is $y_1, y_2, \\cdots, y_x$. The number of swaps required is $y_1-1 + y_2-1 + \\cdots + y_x-1 = y_1 + y_2 + \\cdots + y_x - x = n - x$.\n\nThe time complexity is $O(n \\times \\alpha(n))$, and the space complexity is $O(n)$, where $\\alpha(n)$ is the inverse Ackermann function, which can be considered a very small constant." }, "is_english": true, "time_complexity": "O(n \\times \\alpha(n))", "space_complexity": "O(n)" }, { "problem_id": 766, "explanations": { "1": "According to the problem description, the characteristic of a Toeplitz matrix is that each element is equal to the element in its upper left corner. Therefore, we only need to iterate through each element in the matrix and check if it is equal to the element in its upper left corner.\n\nThe time complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns of the matrix, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(1)" }, { "problem_id": 767, "explanations": { "1": "利用哈希表 cnt 统计字符串 s 中每个字符出现的次数。\n\n若最大的出现次数 mx 大于 `(n + 1) / 2`,说明一定会存在两个相同字符相邻,直接返回 ''。\n\n否则,按字符出现频率从大到小遍历,依次间隔 1 个位置填充字符。若位置大于等于 n,则重置为 1 继续填充。", "2": "先用哈希表 `cnt` 统计每个字母出现的次数,然后构建一个大根堆 `pq`,其中每个元素是一个 `(v, c)` 的元组,其中 `c` 是字母,`v` 是字母出现的次数。\n\n重排字符串时,我们每次从堆顶弹出一个元素 `(v, c)`,将 `c` 添加到结果字符串中,并将 `(v-1, c)` 放入队列 `q` 中。当队列 `q` 的长度达到 $k$ (本题中 $k$ 为 2)及以上时,弹出队首元素,若此时 `v` 大于 0,则将队首元素放入堆中。循环,直至堆为空。\n\n最后判断结果字符串的长度,若与 `s` 长度相等,则返回结果字符串,否则返回空串。\n\n时间复杂度 $O(n\\log n)$,其中 $n$ 是字符串 `s` 的长度。\n\n相似题目:\n\n- [358. K 距离间隔重排字符串](https://github.com/doocs/leetcode/blob/main/solution/0300-0399/0358.Rearrange%20String%20k%20Distance%20Apart/README.md)\n- [1054. 距离相等的条形码](https://github.com/doocs/leetcode/blob/main/solution/1000-1099/1054.Distant%20Barcodes/README.md)" }, "is_english": false, "time_complexity": "O(n\\log n)", "space_complexity": null }, { "problem_id": 768, "explanations": { "1": "According to the problem, we can find that from left to right, each chunk has a maximum value, and these maximum values are monotonically increasing (non-strictly increasing). We can use a stack to store these maximum values of the chunks. The size of the final stack is the maximum number of chunks that can be sorted.\n\nTime complexity is $O(n)$, where $n$ represents the length of $\\textit{arr}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": null }, { "problem_id": 769, "explanations": { "1": "Since $\\textit{arr}$ is a permutation of $[0,..,n-1]$, if the maximum value $\\textit{mx}$ among the numbers traversed so far is equal to the current index $i$, it means a split can be made, and the answer is incremented.\n\nTime complexity is $O(n)$, and space complexity is $O(1)$. Where $n$ is the length of the array $\\textit{arr}$.", "2": "The solution of method one has certain limitations. If there are duplicate elements in the array, the correct answer cannot be obtained.\n\nAccording to the problem, we can find that from left to right, each chunk has a maximum value, and these maximum values are monotonically increasing. We can use a stack to store these maximum values of the chunks. The size of the final stack is the maximum number of chunks that can be sorted.\n\nThis solution can not only solve this problem but also solve the problem 768. Max Chunks To Make Sorted II. You can try it yourself.\n\nTime complexity is $O(n)$, and space complexity is $O(n)$. Where $n$ is the length of the array $\\textit{arr}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 770, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 771, "explanations": { "1": "We can first use a hash table or array $s$ to record all types of jewels. Then traverse all the stones, and if the current stone is a jewel, increment the answer by one.\n\nTime complexity is $O(m+n)$, and space complexity is $O(|\\Sigma|)$, where $m$ and $n$ are the lengths of the strings $jewels$ and $stones$ respectively, and $\\Sigma$ is the character set, which in this problem is the set of all uppercase and lowercase English letters." }, "is_english": true, "time_complexity": "O(m+n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 772, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 773, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 774, "explanations": { "1": "我们二分枚举相邻两个加油站间的距离,找到最小的距离,使得加油站的数量不超过 $k$。\n\n时间复杂度 $O(n\\log M)$。其中 $n$ 为加油站的数量;而 $M$ 为答案的范围,即 $10^8$ 除以答案的精度 $10^{-6}$。" }, "is_english": false, "time_complexity": "O(n\\log M)", "space_complexity": null }, { "problem_id": 775, "explanations": { "1": "根据题意,我们可以发现,一个数组中的局部倒置一定是全局倒置,但是全局倒置不一定是局部倒置。也就是说,全局倒置的数量一定大于等于局部倒置的数量。\n\n因此,我们枚举每个数 $nums[i]$,其中 $2 \\leq i \\leq n - 1$,维护前缀数组 $nums[0,..i-2]$ 中的最大值,记为 $mx$。如果存在 $mx$ 大于 $nums[i]$,则说明全局倒置的数量大于局部倒置的数量,返回 `false` 即可。\n\n遍历结束后,返回 `true`。\n\n时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 `nums` 的长度。", "2": "这道题目实际上是一个“逆序对”问题。\n\n局部倒置的数量等于相邻元素之间逆序对的个数,可以在遍历数组 `nums` 的过程中直接求出;而全局倒置的数量等于逆序对的个数,求解逆序对个数的一个常用做法是使用树状数组。\n\n树状数组,也称作“二叉索引树”(Binary Indexed Tree)或 Fenwick 树。 它可以高效地实现如下两个操作:\n\n1. 单点更新:即函数 `update(x, delta)`,把序列 $x$ 位置的数加上一个值 $delta$。时间复杂度 $O(\\log n)$。\n1. 前缀和查询:即函数 `query(x)`,查询序列 `[1,...x]` 区间的区间和,即位置 $x$ 的前缀和。时间复杂度 $O(\\log n)$。\n\n对于本题,我们定义一个变量 $cnt$ 记录局部倒置的数量与全局倒置的数量之差。如果遍历过程中,$cnt$ 的值小于 $0$,则说明全局倒置的数量大于局部倒置的数量,返回 `false` 即可。\n\n时间复杂度 $O(n\\times \\log n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 `nums` 的长度。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 776, "explanations": { "1": "判断 `root` 节点的情况:\n\n- 若 `root` 为空,直接返回 `[null, null]`;\n- 若 `root.val <= target`,说明 `root` 及其左孩子所有节点的值均小于等于 `target`,那么我们递归 `root.right`,得到 `ans`。然后将 `root.right` 指向 `ans[0]`,最后返回 `[root, ans[1]]`;\n- 若 `root.val > target`,说明 `root` 及其右孩子所有节点的值均大于 `target`,那么我们递归 `root.left`,得到 `ans`。然后将 `root.left` 指向 `ans[1]`,最后返回 `[ans[0], root]`。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉搜索树的节点个数。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 777, "explanations": { "1": "替换操作实际上是将 `L` 往左移动(`L` 左边为 `X` 时才能移动),`R` 往右移动(`R` 右边是 `X` 时才能移动),但 `L` 无法穿过 `R`。所以,如果去掉 `start` 和 `end` 中的所有 `X`,剩下的字符应该是相同的,否则返回 `false`。\n\n双指针遍历 `start` 和 `end`:\n\n- 如果当前字符为 `L` 且 $i\\lt j$,那么这个 `L` 无法向右移动,返回 `false`;\n- 如果当前字符为 `R` 且 $i\\gt j$,那么这个 `R` 无法向左移动,返回 `false`。\n\n如果双指针均遍历到末尾,返回 `true`。\n\n时间复杂度 $O(n)$,其中 $n$ 表示字符串 `start` 或 `end` 的长度。\n\n相似题目:\n\n- [2337. 移动片段得到字符串](https://github.com/doocs/leetcode/blob/main/solution/2300-2399/2337.Move%20Pieces%20to%20Obtain%20a%20String/README.md)" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": null }, { "problem_id": 778, "explanations": { "1": "We can map each position $(i, j)$ to an ID $id = i \\times n + j$, and use a union-find data structure to maintain connected components.\n\nFirst, we use a one-dimensional array $hi$ to record the position ID corresponding to each height, i.e., $hi[h]$ represents the position ID with height $h$.\n\nThen we traverse from height $0$ to height $n^2 - 1$. For each height $t$, we merge position $hi[t]$ with its four adjacent positions that have heights not exceeding $t$. If after merging, position $0$ and position $n^2 - 1$ are connected, then we have found the minimum time $t$, and we return $t$.\n\nThe time complexity is $O(n^2 \\times \\log n)$ and the space complexity is $O(n^2)$, where $n$ is the side length of the matrix." }, "is_english": true, "time_complexity": "O(n^2 \\times \\log n)", "space_complexity": "O(n^2)" }, { "problem_id": 779, "explanations": { "1": "Let's first observe the pattern of the first few rows:\n\n```\nn = 1: 0\nn = 2: 0 1\nn = 3: 0 1 1 0\nn = 4: 0 1 1 0 1 0 0 1\nn = 5: 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0\n...\n```\n\nWe can see that the first half of each row is exactly the same as the previous row, and the second half is the inversion of the previous row. Note that \"inversion\" here means changing $0$ to $1$ and $1$ to $0$.\n\nIf $k$ is in the first half, then the $k$-th character is the same as the $k$-th character of the previous row, so we can directly recurse with $kthGrammar(n - 1, k)$.\n\nIf $k$ is in the second half, then the $k$-th character is the inversion of the $(k - 2^{n - 2})$-th character of the previous row, i.e., $kthGrammar(n - 1, k - 2^{n - 2}) \\oplus 1$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$.", "2": "In the problem, the index starts from $1$. We will change $k$ to $k-1$, converting the index to start from $0$. In the following discussion, all indices start from $0$.\n\nUpon closer observation, the $i$-th character in a row generates two characters at positions $2i$ and $2i+1$ in the next row.\n\n```\n0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0\n```\n\nIf the $i$-th character is $0$, then the characters generated at positions $2i$ and $2i+1$ are $0$ and $1$, respectively. If the $i$-th character is $1$, the generated characters are $1$ and $0$.\n\n```\n0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0\n ^ * *\n```\n\n```\n0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0\n ^ * *\n```\n\nWe can see that the character at position $2i$ (even index) is always the same as the character at position $i$, while the character at position $2i+1$ (odd index) is the inversion of the character at position $i$. In other words, characters at odd indices are always the result of one inversion. If the number of inversions is even, the character remains unchanged; if the number of inversions is odd, it is equivalent to one inversion.\n\nTherefore, we only need to check whether $k$ is odd. If it is, we accumulate one inversion. Then, we divide $k$ by $2$ and continue to check, accumulating the number of inversions until $k$ becomes $0$.\n\nFinally, we determine whether the number of inversions is odd. If it is, the answer is $1$; otherwise, it is $0$.\n\nThe process of accumulating the number of inversions is essentially equivalent to counting the number of $1$s in the binary representation of $k$.\n\nThe time complexity is $O(\\log k)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 780, "explanations": { "1": "从 `(tx, ty)` 开始逆向计算,判断是否可以到达状态 `(sx, sy)`。由于逆向计算是将 tx, ty 中的较大值减少,因此当 `tx > ty` 时可以直接将 tx 的值更新为 `tx % ty`,当 `tx < ty` 时可以将 ty 的值更新为 `ty % tx`。逆向计算需要满足 `tx > sx && ty > sy && tx != ty`。\n\n当条件不成立时,根据此时 tx 和 ty 判断是否可以从起点转换到终点。\n\n- 如果 `tx == sx && ty == sy`,说明此时已经到达起点状态,返回 true;\n- 如果 `tx == sx`,若 `ty > sy && (ty - sy) % tx == 0`,返回 true,否则返回 false;\n- 如果 `ty == sy`,若 `tx > sx && (tx - sx) % ty == 0`,返回 true,否则返回 false;\n- 如果 `tx ≠ sx && ty ≠ sy`,则不可以从起点转换到终点。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 781, "explanations": { "1": "According to the problem description, rabbits that give the same answer may belong to the same color, while rabbits that give different answers cannot belong to the same color.\n\nTherefore, we use a hash map $\\textit{cnt}$ to record the number of occurrences of each answer. For each answer $x$ and its occurrence $v$, we calculate the minimum number of rabbits based on the principle that each color has $x + 1$ rabbits, and add it to the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $\\textit{answers}$.", "2": "" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 782, "explanations": { "1": "In a valid chessboard, there are exactly two types of \"rows\".\n\nFor example, if one row on the chessboard is \"01010011\", then any other row can only be \"01010011\" or \"10101100\". Columns also satisfy this property.\n\nAdditionally, each row and each column has half $0$s and half $1$s. Suppose the chessboard is $n \\times n$:\n\n- If $n = 2 \\times k$, then each row and each column has $k$ $1$s and $k$ $0$s.\n- If $n = 2 \\times k + 1$, then each row has $k$ $1$s and $k + 1$ $0$s, or $k + 1$ $1$s and $k$ $0$s.\n\nBased on the above conclusions, we can determine whether a chessboard is valid. If valid, we can calculate the minimum number of moves required.\n\nIf $n$ is even, there are two possible valid chessboards, where the first row is either \"010101...\" or \"101010...\". We calculate the minimum number of swaps required for these two possibilities and take the smaller value as the answer.\n\nIf $n$ is odd, there is only one possible valid chessboard. If the number of $0$s in the first row is greater than the number of $1$s, then the first row of the final chessboard must be \"01010...\"; otherwise, it must be \"10101...\". We calculate the number of swaps required and use it as the answer.\n\nThe time complexity is $O(n^2)$, where $n$ is the size of the chessboard. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(1)" }, { "problem_id": 783, "explanations": { "1": "The problem requires us to find the minimum difference between the values of any two nodes. Since the inorder traversal of a binary search tree is an increasing sequence, we only need to find the minimum difference between the values of two adjacent nodes in the inorder traversal.\n\nWe can use a recursive method to implement the inorder traversal. During the process, we use a variable $\\textit{pre}$ to save the value of the previous node. This way, we can calculate the minimum difference between the values of two adjacent nodes during the traversal.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary search tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 784, "explanations": { "1": "Since each letter in $s$ can be converted to uppercase or lowercase, we can use the DFS (Depth-First Search) method to enumerate all possible cases.\n\nSpecifically, traverse the string $s$ from left to right. For each letter encountered, you can choose to convert it to uppercase or lowercase, and then continue to traverse the subsequent letters. When you reach the end of the string, you get a conversion scheme and add it to the answer.\n\nThe method of converting case can be implemented using bitwise operations. For a letter, the difference between the ASCII codes of its lowercase and uppercase forms is $32$, so we can achieve case conversion by XORing the ASCII code of the letter with $32$.\n\nThe time complexity is $O(n \\times 2^n)$, where $n$ is the length of the string $s$. For each letter, we can choose to convert it to uppercase or lowercase, so there are $2^n$ conversion schemes in total. For each conversion scheme, we need $O(n)$ time to generate a new string.", "2": "For a letter, we can convert it to uppercase or lowercase. Therefore, for each letter, we can use a binary bit to represent its conversion scheme, where $1$ represents lowercase and $0$ represents uppercase.\n\nFirst, we count the number of letters in the string $s$, denoted as $n$. Then, there are $2^n$ conversion schemes in total. We can use each bit of a binary number to represent the conversion scheme of each letter, enumerating from $0$ to $2^n-1$.\n\nSpecifically, we can use a variable $i$ to represent the current binary number being enumerated, where the $j$-th bit of $i$ represents the conversion scheme of the $j$-th letter. That is, the $j$-th bit of $i$ being $1$ means the $j$-th letter is converted to lowercase, and $0$ means the $j$-th letter is converted to uppercase.\n\nThe time complexity is $O(n \\times 2^n)$, where $n$ is the length of the string $s$. For each letter, we can choose to convert it to uppercase or lowercase, so there are $2^n$ conversion schemes in total. For each conversion scheme, we need $O(n)$ time to generate a new string." }, "is_english": true, "time_complexity": "O(n \\times 2^n)", "space_complexity": null }, { "problem_id": 785, "explanations": { "1": "Traverse all nodes for coloring. For example, initially color them white, and use DFS to color the adjacent nodes with another color. If the target color to be colored is different from the color that the node has already been colored, it means that it cannot form a bipartite graph.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes.", "2": "For this problem, if it is a bipartite graph, then all adjacent nodes of each vertex in the graph should belong to the same set and not be in the same set as the vertex. Therefore, we can use the union-find method. Traverse each vertex in the graph, and if it is found that the current vertex and its corresponding adjacent nodes are in the same set, it means that it is not a bipartite graph. Otherwise, merge the adjacent nodes of the current node.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 786, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 787, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 788, "explanations": { "1": "An intuitive and effective approach is to directly enumerate each number in $[1,2,..n]$ and determine whether it is a good number. If it is a good number, increment the answer by one.\n\nThe key to the problem is how to determine whether a number $x$ is a good number. The logic is as follows:\n\nWe first use an array $d$ of length 10 to record the rotated digits corresponding to each valid digit. In this problem, the valid digits are $[0, 1, 8, 2, 5, 6, 9]$, which correspond to the rotated digits $[0, 1, 8, 5, 2, 9, 6]$ respectively. If a digit is not valid, we set the corresponding rotated digit to $-1$.\n\nThen, we traverse each digit $v$ of the number $x$. If $v$ is not a valid digit, it means $x$ is not a good number, and we directly return $\\textit{false}$. Otherwise, we add the rotated digit $d[v]$ corresponding to the digit $v$ to $y$. Finally, we check whether $x$ and $y$ are equal. If they are not equal, it means $x$ is a good number, and we return $\\textit{true}$.\n\nThe time complexity is $O(n \\times \\log n)$, where $n$ is the given number. The space complexity is $O(1)$.\n\nSimilar problems:\n\n- [1056. Confusing Number](https://github.com/doocs/leetcode/blob/main/solution/1000-1099/1056.Confusing%20Number/README_EN.md)", "2": "Solution 1 is sufficient to solve this problem, but its time complexity is relatively high. If the data range of the problem reaches the level of $10^9$, the approach in Solution 1 will exceed the time limit.\n\nThis problem essentially asks for the number of numbers in the given range $[l, ..r]$ that satisfy certain conditions. The conditions are related to the composition of the numbers rather than their size, so we can use the concept of Digit DP to solve it. In Digit DP, the size of the number has little impact on the complexity.\n\nFor the range $[l, ..r]$ problem, we generally convert it to the problem of $[1, ..r]$ and then subtract the result of $[1, ..l - 1]$, i.e.:\n\n$$\nans = \\sum_{i=1}^{r} ans_i - \\sum_{i=1}^{l-1} ans_i\n$$\n\nHowever, for this problem, we only need to find the value for the range $[1, ..r]$.\n\nHere, we use memoized search to implement Digit DP. We search from the starting point downwards, and at the lowest level, we get the number of solutions. We then return the answers layer by layer upwards, and finally get the final answer from the starting point of the search.\n\nThe basic steps are as follows:\n\nWe convert the number $n$ to a string $s$. Then we define a function $\\textit{dfs}(i, \\textit{ok}, \\textit{limit})$, where $i$ represents the digit position, $\\textit{ok}$ indicates whether the current number satisfies the problem's conditions, and $\\textit{limit}$ is a boolean indicating whether the digits that can be filled are restricted.\n\nThe function executes as follows:\n\nIf $i$ is greater than or equal to the length of the string $s$, return $\\textit{ok}$;\n\nOtherwise, we get the current digit $up$. If $\\textit{limit}$ is $\\textit{true}$, $up$ is the current digit; otherwise, $up$ is $9$;\n\nNext, we iterate over $[0, ..up]$. If $j$ is a valid digit $[0, 1, 8]$, we recursively call $\\textit{dfs}(i + 1, \\textit{ok}, \\textit{limit} \\land j = \\textit{up})$; if $j$ is a valid digit $[2, 5, 6, 9]$, we recursively call $\\textit{dfs}(i + 1, 1, \\textit{limit} \\land j = \\textit{up})$. We sum all the results of the recursive calls and return.\n\nThe time complexity is $O(\\log n \\times D)$, and the space complexity is $O(\\log n)$. Here, $D = 10$.\n\nSimilar problems:\n\n- [233. Number of Digit One](https://github.com/doocs/leetcode/blob/main/solution/0200-0299/0233.Number%20of%20Digit%20One/README_EN.md)\n- [357. Count Numbers with Unique Digits](https://github.com/doocs/leetcode/blob/main/solution/0300-0399/0357.Count%20Numbers%20with%20Unique%20Digits/README_EN.md)\n- [600. Non-negative Integers without Consecutive Ones](https://github.com/doocs/leetcode/blob/main/solution/0600-0699/0600.Non-negative%20Integers%20without%20Consecutive%20Ones/README_EN.md)\n- [902. Numbers At Most N Given Digit Set](https://github.com/doocs/leetcode/blob/main/solution/0900-0999/0902.Numbers%20At%20Most%20N%20Given%20Digit%20Set/README_EN.md)\n- [1012. Numbers with Repeated Digits](https://github.com/doocs/leetcode/blob/main/solution/1000-1099/1012.Numbers%20With%20Repeated%20Digits/README_EN.md)\n- [2376. Count Special Integers](https://github.com/doocs/leetcode/blob/main/solution/2300-2399/2376.Count%20Special%20Integers/README_EN.md)" }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(1)" }, { "problem_id": 789, "explanations": { "1": "对于任意一个阻碍者,如果它到目的地的曼哈顿距离小于等于你到目的地的曼哈顿距离,那么它就可以在你到达目的地之前抓住你。因此,我们只需要判断所有阻碍者到目的地的曼哈顿距离是否都大于你到目的地的曼哈顿距离即可。\n\n时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为阻碍者的数量。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 790, "explanations": { "1": "First, we need to understand the problem. The problem is essentially asking us to find the number of ways to tile a $2 \\times n$ board, where each square on the board can only be covered by one tile.\n\nThere are two types of tiles: `2 x 1` and `L` shapes, and both types of tiles can be rotated. We denote the rotated tiles as `1 x 2` and `L'` shapes.\n\nWe define $f[i][j]$ to represent the number of ways to tile the first $2 \\times i$ board, where $j$ represents the state of the last column. The last column has 4 states:\n\n- The last column is fully covered, denoted as $0$\n- The last column has only the top square covered, denoted as $1$\n- The last column has only the bottom square covered, denoted as $2$\n- The last column is not covered, denoted as $3$\n\nThe answer is $f[n][0]$. Initially, $f[0][0] = 1$ and the rest $f[0][j] = 0$.\n\nWe consider tiling up to the $i$-th column and look at the state transition equations:\n\nWhen $j = 0$, the last column is fully covered. It can be transitioned from the previous column's states $0, 1, 2, 3$ by placing the corresponding tiles, i.e., $f[i-1][0]$ with a `1 x 2` tile, $f[i-1][1]$ with an `L'` tile, $f[i-1][2]$ with an `L'` tile, or $f[i-1][3]$ with two `2 x 1` tiles. Therefore, $f[i][0] = \\sum_{j=0}^3 f[i-1][j]$.\n\nWhen $j = 1$, the last column has only the top square covered. It can be transitioned from the previous column's states $2, 3$ by placing a `2 x 1` tile or an `L` tile. Therefore, $f[i][1] = f[i-1][2] + f[i-1][3]$.\n\nWhen $j = 2$, the last column has only the bottom square covered. It can be transitioned from the previous column's states $1, 3$ by placing a `2 x 1` tile or an `L'` tile. Therefore, $f[i][2] = f[i-1][1] + f[i-1][3]$.\n\nWhen $j = 3$, the last column is not covered. It can be transitioned from the previous column's state $0$. Therefore, $f[i][3] = f[i-1][0]$.\n\nWe can see that the state transition equations only involve the previous column's states, so we can use a rolling array to optimize the space complexity.\n\nNote that the values of the states can be very large, so we need to take modulo $10^9 + 7$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$. Where $n$ is the number of columns of the board." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 791, "explanations": { "1": "一种比较直接的思路是,用哈希表或数组 $d$ 记录字符串 $order$ 中每个字符的位置,然后对字符串 $s$ 中每个字符按照其在 $d$ 中的位置进行排序。如果某个字符不在 $d$ 中,我们可以将其位置置为 $0$。\n\n时间复杂度 $O(m + n\\times \\log n)$,空间复杂度 $O(m)$。其中 $m$ 和 $n$ 分别是字符串 $order$ 和 $s$ 的长度。", "2": "我们还可以先统计 $s$ 中每个字符的出现次数,存储在 $cnt$ 数组中。\n\n然后把字符串 $s$ 在 $order$ 中出现的字符按照 $order$ 中的顺序排序,添加到结果字符串中。最后把剩余的字符直接追加到结果字符串中。\n\n时间复杂度 $O(m+n)$,空间复杂度 $O(m)$。其中 $m$ 和 $n$ 分别是字符串 $order$ 和 $s$ 的长度。" }, "is_english": false, "time_complexity": "O(m + n\\times \\log n)", "space_complexity": "O(m)" }, { "problem_id": 792, "explanations": { "1": "题目中字符串 $s$ 的数据规模最高达到 $5 \\times 10^4$,如果暴力枚举 $words$ 中的每个字符串 $w$,判断其是否为 $s$ 的子序列,很有可能会超时。\n\n我们不妨将 $words$ 中的所有单词根据首字母来分桶,即:把所有单词按照首字母分到 $26$ 个桶中,每个桶中存储的是所有以该字母开头的所有单词。\n\n比如对于 `words = [\"a\", \"bb\", \"acd\", \"ace\"]`,我们得到以下的分桶结果:\n\n```text\na: [\"a\", \"acd\", \"ace\"]\nb: [\"bb\"]\n```\n\n然后我们从 $s$ 的第一个字符开始遍历,假设当前字符为 `'a'`,我们从 `'a'` 开头的桶中取出所有单词。对于取出的每个单词,如果此时单词长度为 $1$,说明该单词已经匹配完毕,我们将答案加 $1$;否则我们将单词的首字母去掉,然后放入下一个字母开头的桶中,比如对于单词 `\"acd\"`,去掉首字母 `'a'` 后,我们将其放入 `'c'` 开头的桶中。这一轮结束后,分桶结果变为:\n\n```text\nc: [\"cd\", \"ce\"]\nb: [\"bb\"]\n```\n\n遍历完 $s$ 后,我们就得到了答案。\n\n实际上,每个桶可以只存储单词的下标 $i$ 以及该单词当前匹配到的位置 $j$,这样可以节省空间。\n\n时间复杂度 $O(n + \\sum_{i=0}^{m-1} |w_i|)$,空间复杂度 $O(m)$。其中 $n$ 和 $m$ 分别为 $s$ 和 $words$ 的长度,而 $|w_i|$ 为 $words[i]$ 的长度。", "2": "我们还可以先用数组或哈希表 $d$ 存放字符串 $s$ 每个字符的下标,即 $d[c]$ 为 $s$ 中所有字符 $c$ 的下标组成的数组。\n\n然后我们遍历 $words$ 中的每个单词 $w$,我们通过二分查找的方法,判断 $w$ 是否为 $s$ 的子序列,是则答案加 $1$。判断逻辑如下:\n\n1. 定义指针 $i$ 表示当前指向字符串 $s$ 的第 $i$ 个字符,初始化为 $-1$。\n1. 遍历字符串 $w$ 中的每个字符 $c$,在 $d[c]$ 中二分查找第一个大于 $i$ 的位置 $j$,如果不存在,则说明 $w$ 不是 $s$ 的子序列,直接跳出循环;否则,将 $i$ 更新为 $d[c][j]$,继续遍历下一个字符。\n1. 如果遍历完 $w$ 中的所有字符,说明 $w$ 是 $s$ 的子序列。\n\n时间复杂度 $O(\\sum_{i=0}^{m-1} |w_i| \\times \\log n)$,空间复杂度 $O(m)$。其中 $n$ 和 $m$ 分别为 $s$ 和 $words$ 的长度,而 $|w_i|$ 为 $words[i]$ 的长度。", "3": "" }, "is_english": false, "time_complexity": "O(n + \\sum_{i=0}^{m-1} |w_i|)", "space_complexity": "O(m)" }, { "problem_id": 793, "explanations": { "1": "定义 $f(x)$ 为 $x!$ 末尾零的个数,那么\n\n$$\nf(x)=\n\\begin{cases}\n0, x=0\\\\\nx/5+f(x/5), x>0\n\\end{cases}\n$$\n\n定义 $g(k)$ 表示 $x!$ 末尾为零的个数为 $k$ 的最小的 $x$ 值,那么题目等价于求解 $g(k+1)-g(k)$。\n\n由于 $g(k)$ 是单调递增的,因此可以使用二分查找求解 $g(k)$。\n\n同时,由于 $f(x)=x/5+f(x/5) \\ge x/5$,因此 $f(5k)\\ge k$。所以,求解 $g(k)$ 时,二分的右边界可以取 $5k$。\n\n时间复杂度 $O(log^2k)$,其中 $k$ 为题目给定的整数。二分查找 $g(k)$ 的时间复杂度为 $O(logk)$,计算 $f(x)$ 的时间复杂度为 $O(logx)$,因此总时间复杂度为 $O(log^2k)$。" }, "is_english": false, "time_complexity": "O(log^2k)", "space_complexity": null }, { "problem_id": 794, "explanations": { "1": "我们先统计当前棋盘上 `'X'` 和 `'O'` 的数量,记为 $x$ 和 $o$。接下来,我们分情况讨论:\n\n- 如果 $x \\neq o$ 且 $x - 1 \\neq o$,则当前棋盘不可能是有效棋盘,返回 `false`。\n- 如果当前棋盘上玩家 1 获胜,但 $x-1 \\neq o$,则当前棋盘不可能是有效棋盘,返回 `false`。\n- 如果当前棋盘上玩家 2 获胜,但 $x \\neq o$,则当前棋盘不可能是有效棋盘,返回 `false`。\n- 其他情况下,当前棋盘是有效棋盘,返回 `true`。\n\n时间复杂度 $O(C)$,空间复杂度 $O(1)$。其中 $C$ 是棋盘上的格子数。本题中 $C = 9$。" }, "is_english": false, "time_complexity": "O(C)", "space_complexity": "O(1)" }, { "problem_id": 795, "explanations": { "1": "题目要我们统计数组 `nums` 中,最大值在区间 $[left, right]$ 范围内的子数组个数。\n\n对于区间 $[left,..right]$ 问题,我们可以考虑将其转换为 $[0,..right]$ 然后再减去 $[0,..left-1]$ 的问题。也就是说,所有最大元素不超过 $right$ 的子数组个数,减去所有最大元素不超过 $left-1$ 的子数组个数,剩下的就是最大元素在区间 $[left,..right]$ 范围内的子数组个数,即题目要求的结果。\n\n$$\nans = \\sum_{i=0}^{right} ans_i - \\sum_{i=0}^{left-1} ans_i\n$$\n\n对于本题,我们设计一个函数 $f(x)$,表示数组 `nums` 中,最大值不超过 $x$ 的子数组个数。那么答案为 $f(right) - f(left-1)$。函数 $f(x)$ 的执行逻辑如下:\n\n- 用变量 $cnt$ 记录最大值不超过 $x$ 的子数组的个数,用 $t$ 记录当前子数组的长度。\n- 遍历数组 `nums`,对于每个元素 $nums[i]$,如果 $nums[i] \\leq x$,则当前子数组的长度加一,即 $t=t+1$,否则当前子数组的长度重置为 0,即 $t=0$。然后将当前子数组的长度加到 $cnt$ 中,即 $cnt = cnt + t$。\n- 遍历结束,将 $cnt$ 返回即可。\n\n时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 `nums` 的长度。", "2": "我们还可以枚举数组中每个元素 $nums[i]$ 作为子数组的最大值,然后统计以该元素为最大值的子数组的个数。问题转化为求出每个元素 $nums[i]$ 左侧第一个大于该元素的下标 $l[i]$,右侧第一个大于等于该元素的下标 $r[i]$,则以该元素为最大值的子数组的个数为 $(i - l[i]) \\times (r[i] - i)$。\n\n我们可以使用单调栈方便地求出 $l[i]$ 和 $r[i]$。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。\n\n相似题目:\n\n- [907. 子数组的最小值之和](https://github.com/doocs/leetcode/blob/main/solution/0900-0999/0907.Sum%20of%20Subarray%20Minimums/README.md)" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 796, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 797, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 798, "explanations": { "1": "对于每个数,都有一个固定的 k 生效区间。我们先利用差分,预处理每个数的 k 生效区间。有最多个数能覆盖到的 k 即是答案。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 799, "explanations": { "1": "We directly simulate the process of pouring champagne.\n\nDefine a 2D array $f$, where $f[i][j]$ represents the amount of champagne in the $j$-th glass of the $i$-th layer. Initially, $f[0][0] = poured$.\n\nFor each layer, if the amount of champagne in the current glass $f[i][j]$ is greater than $1$, the champagne will flow to two glasses in the next layer. The amount flowing in is $\\frac{f[i][j]-1}{2}$, which is the amount of champagne in the current glass minus $1$ and then divided by $2$. Then the amount of champagne in the current glass is updated to $1$.\n\nAfter the simulation ends, return $f[query\\_row][query\\_glass]$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$, where $n$ is the number of layers, i.e., $\\text{query\\_row}$.", "2": "Since the amount of champagne in each layer only depends on the amount in the previous layer, we can use a rolling array approach to optimize space complexity, converting the 2D array to a 1D array.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$, where $n$ is the number of layers, i.e., $\\text{query\\_row}$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 800, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 801, "explanations": { "1": "Define $a$ and $b$ to represent the minimum number of swaps needed to make the element sequences strictly increasing up to index $[0..i]$, with the $i$-th element not swapped and swapped, respectively. The index starts from $0$.\n\nWhen $i=0$, we have $a = 0$ and $b = 1$.\n\nWhen $i \\gt 0$, we first save the previous values of $a$ and $b$ in $x$ and $y$, and then discuss the following cases:\n\nIf $nums1[i - 1] \\ge nums1[i]$ or $nums2[i - 1] \\ge nums2[i]$, to make both sequences strictly increasing, the relative positions of the elements at indices $i-1$ and $i$ must change. That is, if the previous position was swapped, then the current position should not be swapped, so $a = y$; if the previous position was not swapped, then the current position must be swapped, so $b = x + 1$.\n\nOtherwise, the relative positions of the elements at indices $i-1$ and $i$ do not need to change, so $b = y + 1$. Additionally, if $nums1[i - 1] \\lt nums2[i]$ and $nums2[i - 1] \\lt nums1[i]$, the relative positions of the elements at indices $i-1$ and $i$ can change, so $a$ and $b$ can take the smaller values, thus $a = \\min(a, y)$ and $b = \\min(b, x + 1)$.\n\nFinally, return the smaller value between $a$ and $b$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 802, "explanations": { "1": "出度为零的点是安全的,如果一个点**只能**到达安全的点,那么它同样是安全的,所以问题转换成了拓扑排序。\n\n我们可以将图中所有边反向,得到一个反图,然后在反图上运行拓扑排序。\n\n时间复杂度 $O(n+m)$,其中 $n$ 表示图中的点数,$m$ 表示图中的边数。", "2": "若起始节点位于一个环内,或者能到达一个环,则该节点不是安全的。否则,该节点是安全的。\n\n- 白色(用 0 表示):该节点尚未被访问;\n- 灰色(用 1 表示):该节点位于递归栈中,或者在某个环上;\n- 黑色(用 2 表示):该节点搜索完毕,是一个安全节点。" }, "is_english": false, "time_complexity": "O(n+m)", "space_complexity": null }, { "problem_id": 803, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 804, "explanations": { "1": "将 words 所有单词翻译成对应的摩尔斯密码,加入到哈希表中,最后返回哈希表的 size。\n\n时间复杂度 $O(n)$。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": null }, { "problem_id": 805, "explanations": { "1": "According to the problem requirements, we need to determine if the array $\\textit{nums}$ can be divided into two subarrays $A$ and $B$ such that the average values of the two subarrays are equal.\n\nLet the sum of the array $\\textit{nums}$ be $s$, and the number of elements be $n$. The sum and number of elements of subarray $A$ are $s_1$ and $k$, respectively. Then the sum of subarray $B$ is $s_2 = s - s_1$, and the number of elements is $n - k$. Thus:\n\n$$\n\\frac{s_1}{k} = \\frac{s_2}{n - k} = \\frac{s-s_1}{n-k}\n$$\n\nRearranging, we get:\n\n$$\ns_1 \\times (n-k) = (s-s_1) \\times k\n$$\n\nSimplifying, we get:\n\n$$\n\\frac{s_1}{k} = \\frac{s}{n}\n$$\n\nThis means we need to find a subarray $A$ such that its average value equals the average value of the array $\\textit{nums}$. We consider subtracting the average value of the array $\\textit{nums}$ from each element of the array $\\textit{nums}$, transforming the problem into finding a subarray in the array $\\textit{nums}$ whose sum is $0$.\n\nHowever, the average value of the array $\\textit{nums}$ may not be an integer, and floating-point calculations may have precision issues. We can multiply each element of the array $\\textit{nums}$ by $n$, i.e., $nums[i] \\leftarrow nums[i] \\times n$. The above equation becomes:\n\n$$\n\\frac{s_1\\times n}{k} = s\n$$\n\nNow, we subtract the integer $s$ from each element of the array $\\textit{nums}$, transforming the problem into finding a subarray $A$ in the array $nums$ whose sum is $0$.\n\nThe length of the array $\\textit{nums}$ ranges from $[1, 30]$. If we use brute force to enumerate subarrays, the time complexity is $O(2^n)$, which will time out. We can use binary search to reduce the time complexity to $O(2^{n/2})$.\n\nWe divide the array $\\textit{nums}$ into left and right parts. The subarray $A$ can exist in three cases:\n\n1. Subarray $A$ is entirely in the left part of the array $\\textit{nums}$;\n2. Subarray $A$ is entirely in the right part of the array $\\textit{nums}$;\n3. Subarray $A$ is partially in the left part and partially in the right part of the array $\\textit{nums}$.\n\nWe can use binary enumeration to first enumerate the sums of all subarrays in the left part. If there is a subarray with a sum of $0$, we return `true` immediately. Otherwise, we store the sums in a hash table $\\textit{vis}$. Then we enumerate the sums of all subarrays in the right part. If there is a subarray with a sum of $0$, we return `true` immediately. Otherwise, we check if the hash table $\\textit{vis}$ contains the opposite of the current sum. If it does, we return `true`.\n\nNote that we cannot select all elements from both the left and right parts simultaneously, as this would leave subarray $B$ empty, which does not meet the problem requirements. In implementation, we only need to consider $n-1$ elements of the array.\n\nThe time complexity is $O(n \\times 2^{\\frac{n}{2}})$, and the space complexity is $O(2^{\\frac{n}{2}})$." }, "is_english": true, "time_complexity": "O(2^n)", "space_complexity": "O(2^{\\frac{n}{2}})" }, { "problem_id": 806, "explanations": { "1": "We define two variables `lines` and `last`, representing the number of lines and the width of the last line, respectively. Initially, `lines = 1` and `last = 0`.\n\nWe iterate through the string $s$. For each character $c$, we calculate its width $w$. If $last + w \\leq 100$, we add $w$ to `last`. Otherwise, we increment `lines` by one and reset `last` to $w$.\n\nFinally, we return an array consisting of `lines` and `last`.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 807, "explanations": { "1": "According to the problem description, we can increase the value of each cell $(i, j)$ to the smaller value between the maximum value of the $i$-th row and the $j$-th column, ensuring it does not affect the skyline. Thus, the height added to each cell is $\\min(\\textit{rowMax}[i], \\textit{colMax}[j]) - \\textit{grid}[i][j]$.\n\nTherefore, we can first traverse the matrix once to calculate the maximum value of each row and column, storing them in the arrays $\\textit{rowMax}$ and $\\textit{colMax}$, respectively. Then, we traverse the matrix again to compute the answer.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$, where $n$ is the side length of the matrix $\\textit{grid}$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 808, "explanations": { "1": "In this problem, since each operation is a multiple of $25$, we can consider every $25ml$ of soup as one unit. This reduces the data scale to $\\left \\lceil \\frac{n}{25} \\right \\rceil$.\n\nWe design a function $dfs(i, j)$, which represents the probability result when there are $i$ units of soup $A$ and $j$ units of soup $B$ remaining.\n\nWhen $i \\leq 0$ and $j \\leq 0$, it means both soups are finished, and we should return $0.5$. When $i \\leq 0$, it means soup $A$ is finished first, and we should return $1$. When $j \\leq 0$, it means soup $B$ is finished first, and we should return $0$.\n\nNext, for each operation, we have four choices:\n\n- Take $4$ units from soup $A$ and $0$ units from soup $B$;\n- Take $3$ units from soup $A$ and $1$ unit from soup $B$;\n- Take $2$ units from soup $A$ and $2$ units from soup $B$;\n- Take $1$ unit from soup $A$ and $3$ units from soup $B$.\n\nEach choice has a probability of $0.25$, so we can derive:\n\n$$\ndfs(i, j) = 0.25 \\times (dfs(i - 4, j) + dfs(i - 3, j - 1) + dfs(i - 2, j - 2) + dfs(i - 1, j - 3))\n$$\n\nWe use memoization to store the results of the function.\n\nAdditionally, we find that when $n=4800$, the result is $0.999994994426$, and the required precision is $10^{-5}$. As $n$ increases, the result gets closer to $1$. Therefore, when $n \\gt 4800$, we can directly return $1$.\n\nThe time complexity is $O(C^2)$, and the space complexity is $O(C^2)$. In this problem, $C=200$." }, "is_english": true, "time_complexity": "O(C^2)", "space_complexity": "O(C^2)" }, { "problem_id": 809, "explanations": { "1": "We can traverse the array $\\textit{words}$, and for each word $t$ in the array, check if $t$ can be expanded to obtain $s$. If it can, increment the answer by one.\n\nTherefore, the key problem is to determine if the word $t$ can be expanded to obtain $s$. We use a function $\\textit{check}(s, t)$ to determine this. The implementation logic of the function is as follows:\n\nFirst, check the length relationship between $s$ and $t$. If the length of $t$ is greater than $s$, return $\\textit{false}$ directly. Otherwise, use two pointers $i$ and $j$ to point to $s$ and $t$, respectively, both initially set to $0$.\n\nIf the characters pointed to by $i$ and $j$ are different, then $t$ cannot be expanded to obtain $s$, and we return $\\textit{false}$. Otherwise, we need to check the relationship between the consecutive occurrence counts of the characters pointed to by $i$ and $j$, denoted as $c_1$ and $c_2$. If $c_1 \\lt c_2$ or $c_1 \\lt 3$ and $c_1 \\neq c_2$, then $t$ cannot be expanded to obtain $s$, and we return $\\textit{false}$. Otherwise, move $i$ and $j$ to the right by $c_1$ and $c_2$ times, respectively, and continue checking.\n\nIf both $i$ and $j$ reach the end of the strings, then $t$ can be expanded to obtain $s$, and we return $\\textit{true}$. Otherwise, we return $\\textit{false}$.\n\nThe time complexity is $O(n \\times m + \\sum_{i=0}^{m-1} w_i)$, where $n$ and $m$ are the lengths of the string $s$ and the array $\\textit{words}$, respectively, and $w_i$ is the length of the $i$-th word in the array $\\textit{words}$." }, "is_english": true, "time_complexity": "O(n \\times m + \\sum_{i=0}^{m-1} w_i)", "space_complexity": null }, { "problem_id": 810, "explanations": { "1": "According to the game rules, if the XOR result of all numbers on the blackboard is $0$ when it is a player's turn, that player wins. Since Alice goes first, if the XOR result of all numbers in $\\textit{nums}$ is $0$, Alice can win.\n\nWhen the XOR result of all numbers in $\\textit{nums}$ is not $0$, let's analyze Alice's winning situation based on the parity of the length of the array $\\textit{nums}$.\n\nWhen the length of $\\textit{nums}$ is even, if Alice is destined to lose, there is only one situation: no matter which number Alice erases, the XOR result of all remaining numbers equals $0$. Let's analyze whether this situation exists.\n\nAssume the length of the array $\\textit{nums}$ is $n$, and $n$ is even. Let the XOR result of all numbers be $S$, then:\n\n$$\nS = \\textit{nums}[0] \\oplus \\textit{nums}[1] \\oplus \\cdots \\oplus \\textit{nums}[n-1] \\neq 0\n$$\n\nLet $S_i$ be the XOR result after erasing the $i$-th number from the array $\\textit{nums}$, then:\n\n$$\nS_i \\oplus \\textit{nums}[i] = S\n$$\n\nXOR both sides of the equation by $\\textit{nums}[i]$, we get:\n\n$$\nS_i = S \\oplus \\textit{nums}[i]\n$$\n\nIf no matter which number Alice erases, the XOR result of all remaining numbers equals $0$, then for all $i$, we have $S_i = 0$, i.e.,\n\n$$\nS_0 \\oplus S_1 \\oplus \\cdots \\oplus S_{n-1} = 0\n$$\n\nSubstitute $S_i = S \\oplus \\textit{nums}[i]$ into the above equation, we get:\n\n$$\nS \\oplus \\textit{nums}[0] \\oplus S \\oplus \\textit{nums}[1] \\oplus \\cdots \\oplus S \\oplus \\textit{nums}[n-1] = 0\n$$\n\nThere are $n$ (even) $S$ terms in the above equation, and $\\textit{nums}[0] \\oplus \\textit{nums}[1] \\oplus \\cdots \\oplus \\textit{nums}[n-1]$ also equals $S$, so the equation is equivalent to $0 \\oplus S = 0$. This contradicts $S \\neq 0$, so this situation does not exist. Therefore, when the length of $\\textit{nums}$ is even, Alice is guaranteed to win.\n\nIf the length is odd, then after Alice erases a number, the remaining numbers are even in length, leaving Bob with an even-length situation, which means Bob is guaranteed to win, and thus Alice is destined to lose.\n\nIn conclusion, Alice can win when the length of $\\textit{nums}$ is even or the XOR result of all numbers in $\\textit{nums}$ is $0$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 811, "explanations": { "1": "我们用哈希表 `cnt` 存储每个域名(子域名)对应的访问次数。\n\n然后遍历数组,对于每个域名,我们将其拆分为子域名,然后更新哈希表 `cnt` 中对应的访问次数。\n\n最后,我们将哈希表中的键值对转换为数组,即可得到答案。\n\n时间复杂度 $O(L)$,空间复杂度 $O(L)$。其中 $L$ 是数组 `cpdomains` 中所有域名的长度之和。" }, "is_english": false, "time_complexity": "O(L)", "space_complexity": "O(L)" }, { "problem_id": 812, "explanations": { "1": "给定平面上三点 $(x_1, y_1)$, $(x_2, y_2)$, $(x_3, y_3)$,其面积公式为:\n\n$$S = \\frac{1}{2} \\left| x_1y_2 + x_2y_3 + x_3y_1 - x_1y_3 - x_2y_1 - x_3y_2 \\right|$$\n\n我们可以枚举所有的三点组合,计算面积的最大值。\n\n时间复杂度 $O(n^3)$,其中 $n$ 是点的数量。空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(n^3)", "space_complexity": "O(1)" }, { "problem_id": 813, "explanations": { "1": "We can preprocess to obtain the prefix sum array $s$, which allows us to quickly get the sum of subarrays.\n\nNext, we design a function $\\textit{dfs}(i, k)$, which represents the maximum sum of averages when dividing the array starting from index $i$ into at most $k$ groups. The answer is $\\textit{dfs}(0, k)$.\n\nThe execution logic of the function $\\textit{dfs}(i, k)$ is as follows:\n\n- When $i = n$, it means we have traversed to the end of the array, and we return $0$.\n- When $k = 1$, it means there is only one group left, and we return the average value from index $i$ to the end of the array.\n- Otherwise, we enumerate the starting position $j$ of the next group in the interval $[i + 1, n)$, calculate the average value from $i$ to $j - 1$ as $\\frac{s[j] - s[i]}{j - i}$, add the result of $\\textit{dfs}(j, k - 1)$, and take the maximum value of all results.\n\nThe time complexity is $O(n^2 \\times k)$, and the space complexity is $O(n \\times k)$. Here, $n$ represents the length of the array $\\textit{nums}$.", "2": "We can transform the memoized search from Solution 1 into dynamic programming.\n\nDefine $f[i][j]$ to represent the maximum sum of averages when dividing the first $i$ elements of the array $\\textit{nums}$ into at most $j$ groups. The answer is $f[n][k]$.\n\nFor $f[i][j]$, we can enumerate the end position $h$ of the previous group, calculate $f[h][j-1]$, add the result of $\\frac{s[i] - s[h]}{i - h}$, and take the maximum value of all results.\n\nThe time complexity is $O(n^2 \\times k)$, and the space complexity is $O(n \\times k)$. Here, $n$ represents the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n^2 \\times k)", "space_complexity": "O(n \\times k)" }, { "problem_id": 814, "explanations": { "1": "First, we check if the current node is null. If it is, we directly return the null node.\n\nOtherwise, we recursively prune the left and right subtrees and reassign the pruned subtrees to the current node's left and right children. Then, we check if the current node's value is 0 and both its left and right children are null. If so, we return the null node; otherwise, we return the current node.\n\nTime complexity is $O(n)$, and space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 815, "explanations": { "1": "First, we check if $\\textit{source}$ and $\\textit{target}$ are the same. If they are, we directly return $0$.\n\nNext, we use a hash table $\\textit{g}$ to build a mapping from stops to bus routes. For each bus route, we traverse all the stops it passes through and map each stop to that bus route, i.e., $\\textit{g}[\\textit{stop}]$ represents all bus routes passing through stop $\\textit{stop}$.\n\nThen, we check if $\\textit{source}$ and $\\textit{target}$ are in the stop mapping. If they are not, we return $-1$.\n\nWe use a queue $\\textit{q}$ to perform a breadth-first search (BFS). Each element in the queue is a tuple $(\\textit{stop}, \\textit{busCount})$, representing the current stop $\\textit{stop}$ and the number of buses taken to reach the current stop $\\textit{busCount}$.\n\nWe initialize a set $\\textit{visBus}$ to record the bus routes that have been visited and a set $\\textit{visStop}$ to record the stops that have been visited. Then, we add $\\textit{source}$ to $\\textit{visStop}$ and $(\\textit{source}, 0)$ to the queue $\\textit{q}$.\n\nNext, we start the BFS. While the queue $\\textit{q}$ is not empty, we take out the first element from the queue, which is the current stop $\\textit{stop}$ and the number of buses taken to reach the current stop $\\textit{busCount}$.\n\nIf the current stop $\\textit{stop}$ is the target stop $\\textit{target}$, we return the number of buses taken to reach the target stop $\\textit{busCount}$.\n\nOtherwise, we traverse all bus routes passing through the current stop. For each bus route, we traverse all stops on that route. If a stop $\\textit{nextStop}$ has not been visited, we add it to $\\textit{visStop}$ and add $(\\textit{nextStop}, \\textit{busCount} + 1)$ to the queue $\\textit{q}$.\n\nFinally, if we cannot reach the target stop, we return $-1$.\n\nThe time complexity is $O(L)$, and the space complexity is $O(L)$, where $L$ is the total number of stops on all bus routes." }, "is_english": true, "time_complexity": "O(L)", "space_complexity": "O(L)" }, { "problem_id": 816, "explanations": { "1": "枚举纵坐标的起始位置,然后分别获取横、纵坐标的所有可能的表示形式,最后将横、纵坐标的所有可能的表示形式组合起来。\n\n我们将一个坐标值 $x$ 或 $y$ 按照小数点的位置分成左右两部分,那么两部分应该满足以下条件:\n\n1. 左半部分不能以 0 开头,除非左半部分只有 0;\n2. 右半部分不能以 0 结尾。\n\n时间复杂度 $O(n^3)$,其中 $n$ 为字符串 $S$ 的长度。" }, "is_english": false, "time_complexity": "O(n^3)", "space_complexity": null }, { "problem_id": 817, "explanations": { "1": "题目中需要判断链表中节点的值是否在数组 `nums` 中,因此我们可以使用哈希表 $s$ 存储数组 `nums` 中的值。\n\n然后遍历链表,找到第一个在哈希表 $s$ 中的节点,然后从该节点开始遍历,直到遇到不在哈希表 $s$ 中的节点,这样就找到了一个组件,然后继续遍历链表,直到遍历完整个链表。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为链表的节点个数。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 818, "explanations": { "1": "设 $dp[i]$ 表示到达位置 $i$ 的最短指令序列的长度。答案为 $dp[target]$。\n\n对于任意位置 $i$,都有 $2^{k-1} \\leq i \\lt 2^k$,并且我们可以有三种方式到达位置 $i$:\n\n- 如果 $i$ 等于 $2^k-1$,那么我们可以直接执行 $k$ 个 `A` 指令到达位置 $i$,此时 $dp[i] = k$;\n- 否则,我们可以先执行 $k$ 个 `A` 指令到达位置 $2^k-1$,然后执行 `R` 指令,剩余距离为 $2^k-1-i$,此时 $dp[i] = dp[2^k-1-i] + k + 1$;我们也可以先执行 $k-1$ 个 `A` 指令到达位置 $2^{k-1}-1$,然后执行 `R` 指令,接着执行 $j$(其中 $0 \\le j \\lt k$) 个 `A`,再执行 `R`,剩余距离为 $i - 2^{k-1} + 2^j$,此时 $dp[i] = dp[i - 2^{k-1} + 2^j] + k - 1 + j + 2$。求出 $dp[i]$ 的最小值即可。\n\n时间复杂度 $O(n \\log n)$,其中 $n$ 为 $target$。" }, "is_english": false, "time_complexity": "O(n \\log n)", "space_complexity": null }, { "problem_id": 819, "explanations": { "1": "正则匹配(或双指针)找出所有单词,用哈希表统计每个单词出现的频率,找到出现未在 banned 中出现且频率最大的单词。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 820, "explanations": { "1": "题目大意:充分利用重叠的后缀,使有效编码尽可能短。\n\n判断当前单词是否是其他单词的后缀,若是,就不用写入助记字符串中,否则需要写入并且加上一个 # 后缀。", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 821, "explanations": { "1": "我们先创建一个长度为 $n$ 的答案数组 $ans$。\n\n接下来,我们从左到右遍历字符串 $s$,记录最近出现的字符 $c$ 的位置 $pre$,那么对于位置 $i$,答案就是 $i - pre$,即 $ans[i] = i - pre$。\n\n然后,我们从右到左遍历字符串 $s$,记录最近出现的字符 $c$ 的位置 $suf$,那么对于位置 $i$,答案就是 $suf - i$,即 $ans[i] = \\min(ans[i], suf - i)$。\n\n最后返回答案数组 $ans$ 即可。\n\n时间复杂度 $O(n)$,其中 $n$ 是字符串 $s$ 的长度。忽略答案数组的空间消耗,空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 822, "explanations": { "1": "We observe that for position $i$, if $\\textit{fronts}[i]$ is equal to $\\textit{backs}[i]$, then it certainly does not satisfy the condition.\n\nTherefore, we first identify all elements that appear the same on both the front and back sides and record them in a hash set $s$.\n\nNext, we iterate through all elements in both the front and back arrays. For any element $x$ that is **not** in the hash set $s$, we update the minimum value of the answer.\n\nFinally, if we find any element that satisfies the condition, we return the minimum answer; otherwise, we return $0$.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of the arrays." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 823, "explanations": { "1": "我们可以枚举 $arr$ 中的每一个数 $a$ 作为二叉树的根节点(根节点一定最大),然后枚举枚举左子树的值 $b$,若 $a$ 能被 $b$ 整除,则右子树的值为 $a / b$,若 $a / b$ 也在 $arr$ 中,则可以构成一棵二叉树。此时,以 $a$ 为根节点的二叉树的个数为 $f(a) = f(b) \\times f(a / b)$,其中 $f(b)$ 和 $f(a / b)$ 分别为左子树和右子树的二叉树个数。\n\n因此,我们先将 $arr$ 排序,然后用 $f[i]$ 表示以 $arr[i]$ 为根节点的二叉树的个数,最终答案即为 $f[0] + f[1] + \\cdots + f[n - 1]$。注意答案可能很大,需要对 $10^9 + 7$ 取模。\n\n时间复杂度为 $O(n^2)$,空间复杂度为 $O(n)$。其中 $n$ 为 $arr$ 的长度。" }, "is_english": false, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 824, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 825, "explanations": { "1": "We can use an array $\\textit{cnt}$ of length $121$ to record the number of people of each age.\n\nNext, we enumerate all possible age pairs $(\\textit{ax}, \\textit{ay})$. If $\\textit{ax}$ and $\\textit{ay}$ satisfy the conditions given in the problem, these age pairs $(\\textit{ax}, \\textit{ay})$ can send friend requests to each other.\n\nIf $\\textit{ax} = \\textit{ay}$, meaning the ages are the same, then the number of friend requests between $\\textit{ax}$ and $\\textit{ay}$ is $\\textit{cnt}[\\textit{ax}] \\times (\\textit{cnt}[\\textit{ax}] - 1)$. Otherwise, if the ages are different, the number of friend requests between $\\textit{ax}$ and $\\textit{ay}$ is $\\textit{cnt}[\\textit{ax}] \\times \\textit{cnt}[\\textit{ay}]$. We accumulate these friend request counts into the answer.\n\nThe time complexity is $O(n + m^2)$, where $n$ is the length of the array $\\textit{ages}$, and $m$ is the maximum age, which is $121$ in this problem." }, "is_english": true, "time_complexity": "O(n + m^2)", "space_complexity": null }, { "problem_id": 826, "explanations": { "1": "We can sort the jobs in ascending order of ability, and then sort the jobs in ascending order of difficulty.\n\nThen we traverse the workers. For each worker, we find the job with the maximum profit that he can complete, and then add this profit to the answer.\n\nThe time complexity is $O(n \\times \\log n + m \\times \\log m)$, and the space complexity is $O(n)$. Where $n$ and $m$ are the lengths of the arrays `profit` and `worker` respectively.", "2": "Let's denote $m = \\max(\\textit{difficulty})$ and define an array $f$ of length $m + 1$, where $f[i]$ represents the maximum profit among jobs with difficulty less than or equal to $i$, initially $f[i] = 0$.\n\nThen, we iterate over the jobs, and for each job $(d, p)$, if $d \\leq m$, we update $f[d] = \\max(f[d], p)$.\n\nNext, we iterate from $1$ to $m$, and for each $i$, we update $f[i] = \\max(f[i], f[i - 1])$.\n\nFinally, we iterate over the workers, and for each worker $w$, we add $f[w]$ to the answer.\n\nThe time complexity is $O(n + M)$, and the space complexity is $O(M)$. Here, $n$ is the length of the `profit` array, and $M$ is the maximum value in the `difficulty` array." }, "is_english": true, "time_complexity": "O(n \\times \\log n + m \\times \\log m)", "space_complexity": "O(n)" }, { "problem_id": 827, "explanations": { "1": "We can assign a unique identifier to each connected component, using an array $p$ to record the connected component each position belongs to, i.e., $p[i][j]$ represents the connected component number of $(i, j)$. Use an array $cnt$ to record the size of each connected component, i.e., $cnt[root]$ represents the size of the connected component $root$.\n\nFirst, we traverse the entire matrix. For each position $grid[i][j] = 1$ and $p[i][j] = 0$, we perform a depth-first search on it, mark its connected component as $root$, and count the size of the connected component.\n\nThen, we traverse the entire matrix again. For each position $grid[i][j] = 0$, we find the connected components of the four positions above, below, left, and right of it, add up the sizes of these connected components, and add $1$ for the current position, to get the maximum island area after changing the current position to $1$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Where $n$ is the length of the sides of the matrix." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 828, "explanations": { "1": "For each character $c_i$ in the string $s$, when it appears only once in a substring, it contributes to the count of unique characters in that substring.\n\nTherefore, we only need to calculate for each character $c_i$, how many substrings contain this character only once.\n\nWe use a hash table or an array $d$ of length $26$, to store the positions of each character in $s$ in order of index.\n\nFor each character $c_i$, we iterate through each position $p$ in $d[c_i]$, find the adjacent positions $l$ on the left and $r$ on the right, then the number of substrings that meet the requirements by expanding from position $p$ to both sides is $(p - l) \\times (r - p)$. We perform this operation for each character, add up the contributions of all characters, and get the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 829, "explanations": { "1": "Consecutive positive integers form an arithmetic sequence with a common difference $d = 1$. Let's assume the first term of the sequence is $a$, and the number of terms is $k$. Then, $n = (a + a + k - 1) \\times k / 2$, which simplifies to $n \\times 2 = (a \\times 2 + k - 1) \\times k$. From this, we can deduce that $k$ must divide $n \\times 2$ evenly, and $(n \\times 2) / k - k + 1$ must be an even number.\n\nGiven that $a \\geq 1$, it follows that $n \\times 2 = (a \\times 2 + k - 1) \\times k \\geq k \\times (k + 1)$.\n\nIn summary, we can conclude:\n\n1. $k$ must divide $n \\times 2$ evenly;\n2. $k \\times (k + 1) \\leq n \\times 2$;\n3. $(n \\times 2) / k - k + 1$ must be an even number.\n\nWe start enumerating from $k = 1$, and we can stop when $k \\times (k + 1) > n \\times 2$. During the enumeration, we check if $k$ divides $n \\times 2$ evenly, and if $(n \\times 2) / k - k + 1$ is an even number. If both conditions are met, it satisfies the criteria, and we increment the answer by one.\n\nAfter finishing the enumeration, we return the answer.\n\nThe time complexity is $O(\\sqrt{n})$, where $n$ is the given positive integer. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\sqrt{n})", "space_complexity": "O(1)" }, { "problem_id": 830, "explanations": { "1": "We use two pointers $i$ and $j$ to find the start and end positions of each group, then check if the group length is greater than or equal to $3$. If so, we add it to the result array.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": null }, { "problem_id": 831, "explanations": { "1": "According to the problem description, we can first determine whether the string $s$ is an email or a phone number, and then handle it accordingly.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 832, "explanations": { "1": "We can traverse the matrix, and for each row $\\textit{row}$, we use two pointers $i$ and $j$ pointing to the first and last elements of the row, respectively. If $\\textit{row}[i] = \\textit{row}[j]$, swapping them will keep their values unchanged, so we only need to XOR invert $\\textit{row}[i]$ and $\\textit{row}[j]$, then move $i$ and $j$ one position towards the center until $i \\geq j$. If $\\textit{row}[i] \\neq \\textit{row}[j]$, swapping and then inverting their values will also keep them unchanged, so no operation is needed.\n\nFinally, if $i = j$, we directly invert $\\textit{row}[i]$.\n\nThe time complexity is $O(n^2)$, where $n$ is the number of rows or columns in the matrix. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(1)" }, { "problem_id": 833, "explanations": { "1": "We iterate through each replacement operation. For the current $k$-th replacement operation $(i, \\text{src})$, if $s[i..i+|\\text{src}|-1]$ is equal to $\\text{src}$, we record that the string at index $i$ needs to be replaced with the $k$-th string in $\\text{targets}$; otherwise, no replacement is needed.\n\nNext, we only need to iterate through the original string $s$ and perform the replacements based on the recorded information.\n\nThe time complexity is $O(L)$, and the space complexity is $O(n)$, where $L$ is the sum of the lengths of all strings, and $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(L)", "space_complexity": "O(n)" }, { "problem_id": 834, "explanations": { "1": "First, we run a DFS to calculate the size of each node's subtree, recorded in the array $size$, and compute the sum of distances from node $0$ to all other nodes, recorded in $ans[0]$.\n\nNext, we run another DFS to enumerate the sum of distances from each node when it is considered as the root. Suppose the answer for the current node $i$ is $t$. When we move from node $i$ to node $j$, the sum of distances changes to $t - size[j] + n - size[j]$, meaning the sum of distances to node $j$ and its subtree nodes decreases by $size[j]$, while the sum of distances to other nodes increases by $n - size[j]$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of nodes in the tree.\n\nSimilar problems:\n\n- [2581. Count Number of Possible Root Nodes](https://github.com/doocs/leetcode/blob/main/solution/2500-2599/2581.Count%20Number%20of%20Possible%20Root%20Nodes/README_EN.md)" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 835, "explanations": { "1": "We can enumerate each position of $1$ in $\\textit{img1}$ and $\\textit{img2}$, denoted as $(i, j)$ and $(h, k)$ respectively. Then we calculate the offset $(i - h, j - k)$, denoted as $(dx, dy)$, and use a hash table $\\textit{cnt}$ to record the number of occurrences of each offset. Finally, we traverse the hash table $\\textit{cnt}$ to find the offset that appears the most, which is the answer.\n\nThe time complexity is $O(n^4)$, and the space complexity is $O(n^2)$, where $n$ is the side length of $\\textit{img1}$." }, "is_english": true, "time_complexity": "O(n^4)", "space_complexity": "O(n^2)" }, { "problem_id": 836, "explanations": { "1": "Let the coordinates of rectangle $\\text{rec1}$ be $(x_1, y_1, x_2, y_2)$, and the coordinates of rectangle $\\text{rec2}$ be $(x_3, y_3, x_4, y_4)$.\n\nThe rectangles $\\text{rec1}$ and $\\text{rec2}$ do not overlap if any of the following conditions are met:\n\n- $y_3 \\geq y_2$: $\\text{rec2}$ is above $\\text{rec1}$;\n- $y_4 \\leq y_1$: $\\text{rec2}$ is below $\\text{rec1}$;\n- $x_3 \\geq x_2$: $\\text{rec2}$ is to the right of $\\text{rec1}$;\n- $x_4 \\leq x_1$: $\\text{rec2}$ is to the left of $\\text{rec1}$.\n\nIf none of the above conditions are met, the rectangles $\\text{rec1}$ and $\\text{rec2}$ overlap.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 837, "explanations": { "1": "We design a function $dfs(i)$, which represents the probability that when the current score is $i$, the final score does not exceed $n$ when we stop drawing numbers. The answer is $dfs(0)$.\n\nThe calculation method of function $dfs(i)$ is as follows:\n\n- If $i \\ge k$, then we stop drawing numbers. If $i \\le n$, return $1$, otherwise return $0$;\n- Otherwise, we can draw the next number $j$ in the range $[1,..\\textit{maxPts}]$, then $dfs(i) = \\frac{1}{maxPts} \\sum_{j=1}^{maxPts} dfs(i+j)$.\n\nHere we can use memoized search to accelerate the calculation.\n\nThe time complexity of the above method is $O(k \\times \\textit{maxPts})$, which will exceed the time limit, so we need to optimize it.\n\nWhen $i \\lt k$, the following equation holds:\n\n$$\n\\begin{aligned}\ndfs(i) &= (dfs(i + 1) + dfs(i + 2) + \\cdots + dfs(i + \\textit{maxPts})) / \\textit{maxPts} & (1)\n\\end{aligned}\n$$\n\nWhen $i \\lt k - 1$, the following equation holds:\n\n$$\n\\begin{aligned}\ndfs(i+1) &= (dfs(i + 2) + dfs(i + 3) + \\cdots + dfs(i + \\textit{maxPts} + 1)) / \\textit{maxPts} & (2)\n\\end{aligned}\n$$\n\nTherefore, when $i \\lt k-1$, we subtract equation $(2)$ from equation $(1)$ to get:\n\n$$\n\\begin{aligned}\ndfs(i) - dfs(i+1) &= (dfs(i + 1) - dfs(i + \\textit{maxPts} + 1)) / \\textit{maxPts}\n\\end{aligned}\n$$\n\nThat is:\n\n$$\n\\begin{aligned}\ndfs(i) &= dfs(i + 1) + (dfs(i + 1) - dfs(i + \\textit{maxPts} + 1)) / \\textit{maxPts}\n\\end{aligned}\n$$\n\nIf $i=k-1$, we have:\n\n$$\n\\begin{aligned}\ndfs(i) &= dfs(k - 1) = (dfs(k) + dfs(k + 1) + \\cdots + dfs(k + \\textit{maxPts} - 1)) / \\textit{maxPts} & (3)\n\\end{aligned}\n$$\n\nWe assume there are $i$ numbers not exceeding $n$, then $k+i-1 \\leq n$, and since $i\\leq \\textit{maxPts}$, we have $i \\leq \\min(n-k+1, \\textit{maxPts})$, so equation $(3)$ can be written as:\n\n$$\n\\begin{aligned}\ndfs(k-1) &= \\min(n-k+1, \\textit{maxPts}) / \\textit{maxPts}\n\\end{aligned}\n$$\n\nIn summary, we have the following state transition equation:\n\n$$\n\\begin{aligned}\ndfs(i) &= \\begin{cases}\n1, & i \\geq k, i \\leq n \\\\\n0, & i \\geq k, i \\gt n \\\\\n\\min(n-k+1, \\textit{maxPts}) / \\textit{maxPts}, & i = k - 1 \\\\\ndfs(i + 1) + (dfs(i + 1) - dfs(i + \\textit{maxPts} + 1)) / \\textit{maxPts}, & i < k - 1\n\\end{cases}\n\\end{aligned}\n$$\n\nTime complexity $O(k + \\textit{maxPts})$, space complexity $O(k + \\textit{maxPts})$. Where $k$ is the maximum score.", "2": "We can convert the memoized search in Solution 1 into dynamic programming.\n\nDefine $f[i]$ to represent the probability that when the current score is $i$, the final score does not exceed $n$ when we stop drawing numbers. The answer is $f[0]$.\n\nWhen $k \\leq i \\leq \\min(n, k + \\textit{maxPts} - 1)$, we have $f[i] = 1$.\n\nWhen $i = k - 1$, we have $f[i] = \\min(n-k+1, \\textit{maxPts}) / \\textit{maxPts}$.\n\nWhen $i \\lt k - 1$, we have $f[i] = f[i + 1] + (f[i + 1] - f[i + \\textit{maxPts} + 1]) / \\textit{maxPts}$.\n\nTime complexity $O(k + \\textit{maxPts})$, space complexity $O(k + \\textit{maxPts})$. Where $k$ is the maximum score." }, "is_english": true, "time_complexity": "O(k \\times \\textit{maxPts})", "space_complexity": "O(k + \\textit{maxPts})" }, { "problem_id": 838, "explanations": { "1": "Treat all initially pushed dominoes (`L` or `R`) as **sources**, which simultaneously propagate their forces outward. Use a queue to perform BFS layer by layer (0, 1, 2, ...):\n\nWe define $\\text{time[i]}$ to record the first moment when the _i_-th domino is affected by a force, with `-1` indicating it has not been affected yet. We also define $\\text{force[i]}$ as a variable-length list that stores the directions (`'L'`, `'R'`) of forces acting on the domino at the same moment. Initially, push all indices of `L/R` dominoes into the queue and set their `time` to 0.\n\nWhen dequeuing index _i_, if $\\text{force[i]}$ contains only one direction, the domino will fall in that direction $f$. Let the index of the next domino be:\n\n$$\nj =\n\\begin{cases}\ni - 1, & f = L,\\\\\ni + 1, & f = R.\n\\end{cases}\n$$\n\nIf $0 \\leq j < n$:\n\n- If $\\text{time[j]} = -1$, it means _j_ has not been affected yet. Record $\\text{time[j]} = \\text{time[i]} + 1$, enqueue it, and append $f$ to $\\text{force[j]}$.\n- If $\\text{time[j]} = \\text{time[i]} + 1$, it means _j_ has already been affected by another force at the same \"next moment.\" In this case, append $f$ to $\\text{force[j]}$, causing a standoff. Subsequently, since $\\text{len(force[j])} = 2$, it will remain upright.\n\nAfter the queue is emptied, all positions where $\\text{force[i]}$ has a length of 1 will fall in the corresponding direction, while positions with a length of 2 will remain as `.`. Finally, concatenate the character array to form the answer.\n\nThe complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of dominoes." }, "is_english": true, "time_complexity": null, "space_complexity": "O(n)" }, { "problem_id": 839, "explanations": { "1": "We can enumerate any two strings $s$ and $t$ in the list of strings. Since $s$ and $t$ are anagrams, if the number of differing characters at corresponding positions between $s$ and $t$ does not exceed $2$, then $s$ and $t$ are similar. We can use the union-find data structure to merge $s$ and $t$. If the merge is successful, the number of similar string groups decreases by $1$.\n\nThe final number of similar string groups is the number of connected components in the union-find structure.\n\nTime complexity is $O(n^2 \\times (m + \\alpha(n)))$, and space complexity is $O(n)$. Here, $n$ and $m$ are the length of the list of strings and the length of the strings, respectively, and $\\alpha(n)$ is the inverse Ackermann function, which can be considered a very small constant." }, "is_english": true, "time_complexity": "O(n^2 \\times (m + \\alpha(n)))", "space_complexity": "O(n)" }, { "problem_id": 840, "explanations": { "1": "We directly enumerate the top-left coordinates $(i, j)$ of each $3 \\times 3$ submatrix, then check whether the submatrix satisfies the \"magic square\" property. If so, we increment the answer by one. After the enumeration, we return the answer.\n\nThe time complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns of the matrix, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(1)" }, { "problem_id": 841, "explanations": { "1": "We can use the Depth-First Search (DFS) method to traverse the entire graph, count the number of reachable nodes, and use an array `vis` to mark whether the current node has been visited to prevent repeated visits.\n\nFinally, we count the number of visited nodes. If it is the same as the total number of nodes, it means that all nodes can be visited; otherwise, there are nodes that cannot be reached.\n\nThe time complexity is $O(n + m)$, and the space complexity is $O(n)$, where $n$ is the number of nodes, and $m$ is the number of edges.", "2": "We can also use the Breadth-First Search (BFS) method to traverse the entire graph. We use a hash table or an array `vis` to mark whether the current node has been visited to prevent repeated visits.\n\nSpecifically, we define a queue $q$, initially put node $0$ into the queue, and then continuously traverse the queue. Each time we take out the front node $i$ of the queue, if $i$ has been visited, we skip it directly; otherwise, we mark it as visited, and then add the nodes that $i$ can reach to the queue.\n\nFinally, we count the number of visited nodes. If it is the same as the total number of nodes, it means that all nodes can be visited; otherwise, it means that there are unreachable nodes.\n\nThe time complexity is $O(n + m)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes, and $m$ is the number of edges." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(n)" }, { "problem_id": 842, "explanations": { "1": "我们设计一个函数 $dfs(i)$,表示从字符串 $num$ 的第 $i$ 个字符开始拆分,拆分出的斐波那契式序列是否满足题目要求。如果满足,我们就返回 $true$,否则返回 $false$。\n\n函数 $dfs(i)$ 的具体实现如下:\n\n如果 $i$ 等于字符串 $num$ 的长度,说明我们已经拆分完整个字符串,此时我们只需要判断拆分出的序列的长度是否大于 $2$ 即可。如果大于 $2$,说明我们找到了一组满足题目要求的斐波那契式序列,返回 $true$;否则返回 $false$。\n\n如果 $i$ 小于字符串 $num$ 的长度,我们需要枚举拆分出的第一个数 $x$,如果 $x$ 的长度大于 $1$,且以 $0$ 开头,说明 $x$ 不是一个合法的数,我们直接返回 $false$。否则我们将 $x$ 转换成十进制数,如果 $x$ 大于 $2^{31} - 1$,或者 $x$ 大于 $ans$ 的最后两个数之和,直接返回 $false$。如果 $ans$ 的长度小于 $2$,或者 $x$ 等于 $ans$ 的最后两个数之和,我们将 $x$ 加入到 $ans$ 中,然后继续拆分字符串 $num$ 的后面的部分,如果返回 $true$,说明我们找到了一组满足题目要求的斐波那契式序列,返回 $true$;否则我们将 $x$ 从 $ans$ 中移除,然后继续枚举拆分出的第一个数 $x$。\n\n时间复杂度 $O(n \\times \\log^2 M)$,空间复杂度 $O(n)$。其中 $n$ 和 $M$ 分别是字符串 $num$ 的长度和整型数的最大值。" }, "is_english": false, "time_complexity": "O(n \\times \\log^2 M)", "space_complexity": "O(n)" }, { "problem_id": 843, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 844, "explanations": { "1": "我们用双指针 $i$ 和 $j$ 分别指向字符串 $s$ 和 $t$ 的末尾。\n\n每次向前移动一个字符,如果当前字符是退格符,则跳过当前字符,同时退格符的数量加一,如果当前字符不是退格符,则判断退格符的数量,如果退格符的数量大于 $0$,则跳过当前字符,同时退格符的数量减一,如果退格符的数量等于 $0$,那么该字符需要进行比较。\n\n我们每次找到两个字符串中需要比较的字符,然后进行比较,如果两个字符不相等,则返回 $false$,如果遍历完两个字符串,都没有发现不相等的字符,则返回 $true$。\n\n时间复杂度 $O(m + n)$,空间复杂度 $O(1)$。其中 $m$ 和 $n$ 分别是字符串 $s$ 和 $t$ 的长度。" }, "is_english": false, "time_complexity": "O(m + n)", "space_complexity": "O(1)" }, { "problem_id": 845, "explanations": { "1": "我们定义两个数组 $f$ 和 $g$,其中 $f[i]$ 表示以 $arr[i]$ 结尾的最长上升子序列的长度,而 $g[i]$ 表示以 $arr[i]$ 开头的最长下降子序列的长度。那么对于每个下标 $i$,如果 $f[i] \\gt 1$ 且 $g[i] \\gt 1$,那么以 $arr[i]$ 为山顶的山脉的长度为 $f[i] + g[i] - 1$,我们只需要枚举所有的 $i$,找出最大的那个值即可。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $arr$ 的长度。", "2": "我们可以枚举山脉的左侧山脚,然后向右寻找山脉的右侧山脚。我们可以使用两个指针 $l$ 和 $r$,其中 $l$ 表示左侧山脚的下标,$r$ 表示右侧山脚的下标,初始时 $l=0$,$r=0$,然后我们向右移动 $r$,找到山顶的位置,此时判断 $r$ 是否满足 $r + 1 \\lt n$ 并且 $arr[r] \\gt arr[r + 1]$,如果满足,我们向右继续移动 $r$,直到找到右侧山脚的位置,此时山脉的长度为 $r - l + 1$,我们更新答案,然后将 $l$ 的值更新为 $r$,继续寻找下一个山脉。\n\n时间复杂度 $O(n)$,其中 $n$ 为数组 $arr$ 的长度。空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 846, "explanations": { "1": "We first check whether the length of the array $\\textit{hand}$ is divisible by $\\textit{groupSize}$. If it is not, this means that the array cannot be partitioned into multiple subarrays of length $\\textit{groupSize}$, so we return $\\text{false}$.\n\nNext, we use a hash table $\\textit{cnt}$ to count the occurrences of each number in the array $\\textit{hand}$, and then we sort the array $\\textit{hand}$.\n\nAfter that, we iterate over the sorted array $\\textit{hand}$. For each number $x$, if $\\textit{cnt}[x] \\neq 0$, we enumerate every number $y$ from $x$ to $x + \\textit{groupSize} - 1$. If $\\textit{cnt}[y] = 0$, it means that we cannot partition the array into multiple subarrays of length $\\textit{groupSize}$, so we return $\\text{false}$. Otherwise, we decrement $\\textit{cnt}[y]$ by $1$.\n\nIf the iteration completes successfully, it means that the array can be partitioned into multiple valid subarrays, so we return $\\text{true}$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{hand}$.", "2": "Similar to Solution 1, we first check whether the length of the array $\\textit{hand}$ is divisible by $\\textit{groupSize}$. If it is not, this means that the array cannot be partitioned into multiple subarrays of length $\\textit{groupSize}$, so we return $\\text{false}$.\n\nNext, we use an ordered set $\\textit{sd}$ to count the occurrences of each number in the array $\\textit{hand}$.\n\nThen, we repeatedly take the smallest value $x$ from the ordered set and enumerate each number $y$ from $x$ to $x + \\textit{groupSize} - 1$. If all these numbers appear at least once in the ordered set, we decrement their occurrence count by $1$. If any count reaches $0$, we remove that number from the ordered set. Otherwise, if we encounter a number that does not exist in the ordered set, it means that the array cannot be partitioned into valid subarrays, so we return $\\text{false}$. If the iteration completes successfully, it means that the array can be partitioned into multiple valid subarrays, so we return $\\text{true}$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{hand}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 847, "explanations": { "1": "我们注意到 $n$ 的范围不超过 $12$,因此,我们可以用一个 $12$ 位的二进制数来表示每个节点的访问情况,其中第 $i$ 位为 $1$ 表示第 $i$ 个节点已经被访问过,为 $0$ 表示该节点还没有被访问过。\n\n我们初始化队列 $q$,其中每个元素是一个二元素 $(i, st)$,表示当前位于节点 $i$,且已经遍历过的节点的集合为 $st$。初始时,队列中只有 $n$ 个元素,即 $(i, 2^i)$,表示可以从任一节点出发开始遍历。另外,我们用一个哈希表或数组 $vis$ 记录每个状态是否已经被搜索过,防止无效的重复搜索。\n\n在 BFS 的过程中,我们每次取出队首元素 $(i, st)$,如果当前 $st$ 包含 $n$ 个 $1$,那么我们就找到了一条从起点出发的遍历路径,返回当前的步数即可。否则我们枚举当前节点 $i$ 的所有连边 $(i, j)$,如果 $(j, st \\lor 2^j)$ 没有被搜索过,那么就将 $(j, st \\lor 2^j)$ 加入队列 $q$ 中,并且用 $vis$ 记录它已经被搜索过。循环此过程,直到找到一条路径。\n\n时间复杂度 $(n^2 \\times 2^n)$,空间复杂度 $O(n \\times 2^n)$。其中 $n$ 是图中的节点数。", "2": "因为每条边权值一样,所以用 BFS 就能得出最短路径,过程中可以用**状态压缩**记录节点的访问情况。另外,同一个节点 u 以及对应的节点访问情况需要保证只被搜索过一次,因此可以用 `vis(u, state)` 表示是否已经被搜索过,防止无效的重复搜索。\n\n本题也属于 BFS 最小步数模型,可以使用 A\\* 算法优化搜索。\n\nA\\* 算法主要思想如下:\n\n1. 将 BFS 队列转换为优先队列(小根堆);\n1. 队列中的每个元素为 `(dist[state] + f(state), state)`,`dist[state]` 表示从起点到当前 state 的距离,`f(state)` 表示从当前 state 到终点的估计距离,这两个距离之和作为堆排序的依据;\n1. 当终点第一次出队时,说明找到了从起点到终点的最短路径,直接返回对应的 step;\n1. `f(state)` 是估价函数,并且估价函数要满足 `f(state) <= g(state)`,其中 `g(state)` 表示 state 到终点的真实距离;\n1. A\\* 算法只能保证终点第一次出队时,即找到了一条从起点到终点的最小路径,不能保证其他点出队时也是从起点到当前点的最短路径。" }, "is_english": false, "time_complexity": "O(n \\times 2^n)", "space_complexity": "O(n \\times 2^n)" }, { "problem_id": 848, "explanations": { "1": "For each character in the string $s$, we need to calculate its final shift amount, which is the sum of $\\textit{shifts}[i]$, $\\textit{shifts}[i + 1]$, $\\textit{shifts}[i + 2]$, and so on. We can use the concept of suffix sum, traversing $\\textit{shifts}$ from back to front, calculating the final shift amount for each character, and then taking modulo $26$ to get the final character.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. Ignoring the space consumption of the answer, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 849, "explanations": { "1": "We define two variables $\\textit{first}$ and $\\textit{last}$ to represent the positions of the first and last person, respectively. We use the variable $d$ to represent the maximum distance between two people.\n\nThen, we traverse the array $\\textit{seats}$. If the current position is occupied, and if $\\textit{last}$ has been updated before, it means there was someone before, so we update $d = \\max(d, i - \\textit{last})$. If $\\textit{first}$ has not been updated before, it means there was no one before, so we update $\\textit{first} = i$. Next, we update $\\textit{last} = i$.\n\nFinally, we return $\\max(\\textit{first}, n - \\textit{last} - 1, d / 2)$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{seats}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 850, "explanations": { "1": "线段树将整个区间分割为多个不连续的子区间,子区间的数量不超过 $log(width)$。更新某个元素的值,只需要更新 $log(width)$ 个区间,并且这些区间都包含在一个包含该元素的大区间内。区间修改时,需要使用**懒标记**保证效率。\n\n- 线段树的每个节点代表一个区间;\n- 线段树具有唯一的根节点,代表的区间是整个统计范围,如 $[1, N]$;\n- 线段树的每个叶子节点代表一个长度为 1 的元区间 $[x, x]$;\n- 对于每个内部节点 $[l, r]$,它的左儿子是 $[l, mid]$,右儿子是 $[mid + 1, r]$, 其中 $mid = ⌊(l + r) / 2⌋$ (即向下取整)。\n\n对于本题,线段树节点维护的信息有:\n\n1. 区间被覆盖的次数 `cnt`;\n1. 区间被覆盖的长度 `len`。\n\n另外,由于本题利用了扫描线本身的特性,因此,区间修改时,不需要懒标记,也无须进行 pushdown 操作。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 851, "explanations": { "1": "我们先用邻接表 $g$ 存储 $richer$ 数组中的信息,其中 $g[i]$ 表示所有比 $i$ 更有钱的人的集合。\n\n然后对于每个人 $i$,我们用 DFS 遍历所有比 $i$ 更有钱的人,找到其中安静值最小的人,即为答案。\n\n时间复杂度 $O(m + n)$,空间复杂度 $O(m + n)$。其中 $m$ 和 $n$ 分别为 $richer$ 数组和 $quiet$ 数组的长度。" }, "is_english": false, "time_complexity": "O(m + n)", "space_complexity": "O(m + n)" }, { "problem_id": 852, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 853, "explanations": { "1": "我们将车辆按照位置降序排序,这样我们只需要比较相邻两辆车的到达时间即可。\n\n我们初始化一个变量 $pre$ 表示上一辆车到达终点的时间,如果当前车辆到达终点的时间大于 $pre$,说明当前车辆无法追上前面的车辆,因此需要另外开一个车队,否则当前车辆会与前面的车辆组成一个车队。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是车辆的数量。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 854, "explanations": { "1": "本题实际上是一类经典的问题:求解最小操作次数。从一个初始状态 $s_1$,经过最少 $k$ 次状态转换,变成目标状态 $s_2$。字符串长度不超过 $20$,我们考虑使用 BFS 搜索来求解。\n\n首先将初始状态 $s_1$ 入队,用哈希表 `vis` 记录所有访问过的状态。\n\n接下来每一轮,都是将队列中的所有状态转换到下一个状态,当遇到目标状态 $s_2$ 时,当前状态转换的轮数就是答案。\n\n我们发现,题目的重点在于如何进行状态转换。对于本题,转换操作就是交换一个字符串中两个位置的字符。如果当前字符串 $s[i]$ 与 $s_2[i]$ 不相等,那么我们应该在 $s$ 中找到一个位置 $j$,满足 $s[j] = s_2[i]$ 并且 $s[j] \\neq s_2[j]$,然后交换 $s[i]$ 和 $s[j]$。这样可以使得状态最接近于目标状态。这里的状态转换可以参考以下代码中的 `next()` 函数。\n\n复杂度分析:BFS 剪枝不讨论时空复杂度。", "2": "A\\* 搜索算法(A\\* 读作 A-star),简称 A\\* 算法,是一种在图形平面上,对于有多个节点的路径求出最低通过成本的算法。它属于图遍历和最佳优先搜索算法(英文:Best-first search),亦是 BFS 的改进。\n\nA\\* 算法主要步骤如下:\n\n1. 将方法一中的 BFS 队列转换为优先队列(小根堆);\n1. 队列中的每个元素为 `(dist[s] + f(s), s)`,`dist[s]` 表示从初始状态 $s_1$ 到当前状态 $s$ 的距离,`f(s)` 表示从当前状态 $s$ 到目标状态 $s_2$ 的估计距离,这两个距离之和作为堆排序的依据;\n1. 当终点第一次出队时,说明找到了从起点 $s_1$ 到终点 $s_2$ 的最短路径,直接返回对应的距离;\n1. `f(s)` 是估价函数,并且估价函数要满足 `f(s) <= g(s)`,其中 `g(s)` 表示 $s$ 到终点 $s_2$ 的真实距离;\n\n需要注意的是,A\\* 算法只能保证终点第一次出队时,即找到了一条从起点到终点的最小路径,不能保证其他点出队时也是从起点到当前点的最短路径。\n\n复杂度分析:启发式搜索不讨论时空复杂度。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 855, "explanations": { "1": "Considering that each time we call $\\text{seat}()$, we need to find the seat with the maximum distance, we can use an ordered set to store seat intervals. Each element of the ordered set is a tuple $(l, r)$, indicating that the seats between $l$ and $r$ (excluding $l$ and $r$) can be occupied by a student. Initially, the ordered set contains only one element $(-1, n)$, indicating that the seats between $(-1, n)$ can be occupied by a student.\n\nAdditionally, we use two hash tables $\\textit{left}$ and $\\textit{right}$ to maintain the left and right neighbors of each occupied seat, making it easier to merge two seat intervals when calling $\\text{leave}(p)$.\n\nThe time complexity is $O(\\log n)$, and the space complexity is $O(n)$. Here, $n$ is the number of seats in the exam room." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(n)" }, { "problem_id": 856, "explanations": { "1": "By observing, we find that `()` is the only structure that contributes to the score, and the outer parentheses just add some multipliers to this structure. So, we only need to focus on `()`.\n\nWe use $d$ to maintain the current depth of parentheses. For each `(`, we increase the depth by one, and for each `)`, we decrease the depth by one. When we encounter `()`, we add $2^d$ to the answer.\n\nLet's take `(()(()))` as an example. We first find the two closed parentheses `()` inside, and then add the corresponding $2^d$ to the score. In fact, we are calculating the score of `(()) + ((()))`.\n\n```bash\n( ( ) ( ( ) ) )\n ^ ^ ^ ^\n\n( ( ) ) + ( ( ( ) ) )\n ^ ^ ^ ^\n```\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the string.\n\nRelated problems about parentheses:\n\n- [678. Valid Parenthesis String](https://github.com/doocs/leetcode/blob/main/solution/0600-0699/0678.Valid%20Parenthesis%20String/README.md)\n- [1021. Remove Outermost Parentheses](https://github.com/doocs/leetcode/blob/main/solution/1000-1099/1021.Remove%20Outermost%20Parentheses/README.md)\n- [1096. Brace Expansion II](https://github.com/doocs/leetcode/blob/main/solution/1000-1099/1096.Brace%20Expansion%20II/README.md)\n- [1249. Minimum Remove to Make Valid Parentheses](https://github.com/doocs/leetcode/blob/main/solution/1200-1299/1249.Minimum%20Remove%20to%20Make%20Valid%20Parentheses/README.md)\n- [1541. Minimum Insertions to Balance a Parentheses String](https://github.com/doocs/leetcode/blob/main/solution/1500-1599/1541.Minimum%20Insertions%20to%20Balance%20a%20Parentheses%20String/README.md)\n- [2116. Check if a Parentheses String Can Be Valid](https://github.com/doocs/leetcode/blob/main/solution/2100-2199/2116.Check%20if%20a%20Parentheses%20String%20Can%20Be%20Valid/README.md)" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 857, "explanations": { "1": "我们假设选取了某一个工资组,总工作质量为 `tot`,总支付金额为 `c`。每个工人的工作质量为 $q_i$,工资为 $w_i$。那么,对于此工资组的每个工人,均满足 $c\\times \\frac{q_i}{tot} \\ge w_i$。即 $c\\ge tot\\times \\frac{w_i}{q_i}$。\n\n在总工作质量 `tot` 固定的情况下,支付的金额取决于权重 $\\frac{w_i}{q_i}$ 的最大值。\n\n我们可以从小到大枚举权重 $\\frac{w_i}{q_i}$ 作为工资组的最大值,此时工资组其他人员只需要在权重小于等于这个值的集合中,选取工作质量最小的 $k-1$ 名工人来组成工资组即可。因此,可以用优先队列(最大堆)维护工作质量最小的 $k-1$ 名工人。\n\n时间复杂度 $O(n\\log n)$,空间复杂度 $O(n)$。其中 $n$ 是工人数。\n\n相似题目:\n\n- [1383. 最大的团队表现值](https://github.com/doocs/leetcode/blob/main/solution/1300-1399/1383.Maximum%20Performance%20of%20a%20Team/README.md)" }, "is_english": false, "time_complexity": "O(n\\log n)", "space_complexity": "O(n)" }, { "problem_id": 858, "explanations": { "1": "根据题意,光线在每次反射时,都会向上或向下移动 $q$ 的距离,向右移动 $p$ 的距离。而由于光线最后一定会遇到接收器,因此,我们需要找到一个最小的 $k$,使得 $k \\times q$ 是 $p$ 的倍数。\n\n同时,根据 $k$ 的奇偶性,我们可以确定光线最终到达了西侧还是东侧。如果 $k$ 是偶数,那么光线最终到达的是西侧,否则光线最终到达的是东侧。\n\n另外,根据 $k \\times q$ 除以 $p$ 的结果的奇偶性,我们可以确定光线最终到达的是北侧还是南侧。如果 $k \\times q$ 是 $p$ 的偶数倍,那么光线最终到达的是南侧,否则光线最终到达的是北侧。\n\n时间复杂度 $O(\\log p)$,空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(\\log p)", "space_complexity": "O(1)" }, { "problem_id": 859, "explanations": { "1": "首先,先理解亲密字符串的意思:\n\n- 若两个字符串的长度或字符出现的频数不等,一定不是亲密字符串;\n- 若两个字符串对应位置不相等的字符数量为 2,或者数量为 0 并且字符串存在两个相同字符,则是亲密字符串。\n\n因此,我们先判断两个字符串长度,若不等,直接返回 `false`。\n\n接着,统计两个字符串的字符频数,记为 `cnt1` 和 `cnt2`,若 `cnt1` 不等于 `cnt2`,直接返回 `false`。\n\n然后枚举两个字符串,统计对应位置不相等的字符数量,若为 2,则返回 `true`;若为 0,且字符串存在两个相同字符,则返回 `true`。\n\n时间复杂度 $O(n)$,空间复杂度 $O(C)$。其中 $n$ 是字符串 `s` 或 `goal` 的长度;而 $C$ 为字符集大小。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(C)" }, { "problem_id": 860, "explanations": { "1": "我们从前往后遍历账单数组 $bills$,对于当前遍历到的账单:\n\n- 如果是 $5$ 美元,那么直接收下即可;\n- 如果是 $10$ 美元,那么需要找零 $5$ 美元;\n- 如果是 $20$ 美元,那么需要找零 $15$ 美元,此时有两种找零方式:找零 $1$ 张 $10$ 美元 + $1$ 张 $5$ 美元;找零 $3$ 张 $5$ 美元。我们优先用第一种找零方式,如果没有足够的 $10$ 美元,那么用第二种方式;\n- 如果发现 $5$ 美元的数量不够,直接返回 `false`。\n\n遍历结束,说明我们没有遇到无法找零的情况,返回 `true` 即可。\n\n时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为账单数组 $bills$ 的长度。", "2": "" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 861, "explanations": { "1": "我们注意到,对于任意一个翻转方案,翻转的次序不影响最后的结果。因此我们可以先考虑所有的行翻转,再考虑所有的列翻转。\n\n每一行的数字要尽可能大,因此,我们遍历每一行,若行首元素为 $0$,则将该行进行翻转。\n\n接下来,对于每一列 $j$,我们统计该列中 $0$ 和 $1$ 的数量,令 $cnt$ 为其中的最大值,则该列的贡献为 $cnt \\times 2^{n - j - 1}$。对所有列的贡献进行累加,即可得到答案。\n\n时间复杂度 $O(m \\times n)$,空间复杂度 $O(1)$。其中 $m$, $n$ 分别为矩阵的行数和列数。" }, "is_english": false, "time_complexity": "O(m \\times n)", "space_complexity": "O(1)" }, { "problem_id": 862, "explanations": { "1": "题目要求找到一个最短的子数组,使得子数组的和大于等于 $k$。不难想到,可以使用前缀和快速计算子数组的和。\n\n我们用一个长度为 $n+1$ 的数组 $s[i]$ 表示数组 $nums$ 前 $i$ 个元素的和。另外,我们需要维护一个严格单调递增的队列 $q$,队列中存储的是前缀和数组 $s[i]$ 的下标。注意,这里的单调递增是指下标对应的前缀和的大小,而不是下标的大小。\n\n为什么存的是下标呢?这是为了方便计算子数组的长度。那为什么队列严格单调递增?我们可以用反证法来说明。\n\n假设队列元素非严格单调递增,也即是说,存在下标 $i$ 和 $j$,满足 $i < j$,且 $s[i] \\geq s[j]$。\n\n当遍历到下标 $k$,其中 $i \\lt j \\lt k \\leq n$,此时 $s[k]-s[j] \\geq s[k]-s[i]$,且 $nums[j..k-1]$ 的长度小于 $nums[i..k-1]$ 的长度。由于下标 $j$ 的存在,子数组 $nums[i..k-1]$ 一定不是最优解,队列中的下标 $i$ 是不必要的,需要将其移除。因此,队列中的元素一定严格单调递增。\n\n回到这道题目上,我们遍历前缀和数组 $s$,对于遍历到的下标 $i$,如果 $s[i] - s[q.front] \\geq k$,说明当前遇到了一个可行解,我们可以更新答案。此时,我们需要将队首元素出队,直到队列为空或者 $s[i] - s[q.front] \\lt k$ 为止。\n\n如果此时队列不为空,为了维持队列的严格单调递增,我们还需要判断队尾元素是否需要出队,如果 $s[q.back] \\geq s[i]$,则需要循环将队尾元素出队,直到队列为空或者 $s[q.back] \\lt s[i]$ 为止。然后,我们将下标 $i$ 入队。\n\n遍历结束,如果我们没有找到可行解,那么返回 $-1$。否则,返回答案。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 $nums$ 的长度。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 863, "explanations": { "1": "We first use DFS to traverse the entire tree and save each node's parent node in the hash table $\\textit{g}$.\n\nNext, we use DFS again, starting from $\\textit{target}$, to search for nodes at a distance of $k$ both upwards and downwards, and add them to the result array.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 864, "explanations": { "1": "According to the problem description, we need to start from the initial position, move in four directions (up, down, left, right), collect all keys, and finally return the minimum number of moves required to collect all keys. If it is not possible to collect all keys, return $-1$.\n\nFirst, we traverse the 2D grid to find the starting position $(si, sj)$ and count the number of keys $k$.\n\nThen, we can use Breadth-First Search (BFS) to solve this problem. Since the number of keys ranges from $1$ to $6$, we can use a binary number to represent the state of the keys, where the $i$-th bit being $1$ indicates that the $i$-th key has been collected, and $0$ indicates that the $i$-th key has not been collected.\n\nFor example, in the following case, there are $4$ bits set to $1$, indicating that keys `'b', 'c', 'd', 'f'` have been collected.\n\n```\n1 0 1 1 1 0\n^ ^ ^ ^\nf d c b\n```\n\nWe define a queue $q$ to store the current position and the state of the collected keys, i.e., $(i, j, \\textit{state})$, where $(i, j)$ represents the current position, and $\\textit{state}$ represents the state of the collected keys. The $i$-th bit of $\\textit{state}$ being $1$ indicates that the $i$-th key has been collected; otherwise, it indicates that the $i$-th key has not been collected.\n\nAdditionally, we define a hash table or array $vis$ to record whether the current position and the state of the collected keys have been visited. If visited, there is no need to visit again. $vis[i][j][\\textit{state}]$ indicates whether the position $(i, j)$ and the state of the collected keys $state$ have been visited.\n\nWe start from the initial position $(si, sj)$, add it to the queue $q$, and set $vis[si][sj][0]$ to $true$, indicating that the initial position and the state of the collected keys $0$ have been visited.\n\nDuring the BFS process, we take out a position $(i, j, \\textit{state})$ from the front of the queue and check whether the current position is the endpoint, i.e., whether the current position has collected all keys, which means the number of $1$s in the binary representation of $state$ is $k$. If so, we return the current number of steps as the answer.\n\nOtherwise, we move from the current position in four directions (up, down, left, right). If we can move to the next position $(x, y)$, we add $(x, y, nxt)$ to the queue $q$, where $nxt$ represents the state of the keys at the next position.\n\nHere, $(x, y)$ must first be within the grid range, i.e., $0 \\leq x < m$ and $0 \\leq y < n$. Secondly, if the position $(x, y)$ is a wall, i.e., `grid[x][y] == '#'`, or the position $(x, y)$ is a lock but we do not have the corresponding key, i.e., `grid[x][y] >= 'A' && grid[x][y] <= 'F' && (state >> (grid[x][y] - 'A') & 1) == 0)`, then we cannot move to the position $(x, y)`. Otherwise, we can move to the position $(x, y)`.\n\nIf the search ends and we have not collected all keys, return $-1$.\n\nThe time complexity is $O(m \\times n \\times 2^k)$, and the space complexity is $O(m \\times n \\times 2^k)$. Here, $m$ and $n$ are the number of rows and columns of the grid, respectively, and $k$ is the number of keys." }, "is_english": true, "time_complexity": "O(m \\times n \\times 2^k)", "space_complexity": "O(m \\times n \\times 2^k)" }, { "problem_id": 865, "explanations": { "1": "We design a function $\\textit{dfs}(\\textit{root})$ that returns the smallest subtree containing all the deepest nodes in the subtree rooted at $\\textit{root}$, as well as the depth of the subtree rooted at $\\textit{root}$.\n\nThe execution process of the function $\\textit{dfs}(\\textit{root})$ is as follows:\n\n- If $\\textit{root}$ is null, return $\\text{null}$ and $0$.\n- Otherwise, recursively calculate the smallest subtree and depth of the left and right subtrees of $\\textit{root}$, denoted as $l$ and $l_d$, and $r$ and $r_d$, respectively. If $l_d > r_d$, then the smallest subtree containing all the deepest nodes in the subtree rooted at the left child of $\\textit{root}$ is $l$, with a depth of $l_d + 1$. If $l_d < r_d$, then the smallest subtree containing all the deepest nodes in the subtree rooted at the right child of $\\textit{root}$ is $r$, with a depth of $r_d + 1$. If $l_d = r_d$, then $\\textit{root}$ is the smallest subtree containing all the deepest nodes, with a depth of $l_d + 1$.\n\nFinally, return the first element of the result of $\\textit{dfs}(\\textit{root})$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 866, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 867, "explanations": { "1": "Let $m$ be the number of rows and $n$ be the number of columns in the matrix $\\textit{matrix}$. According to the definition of transpose, the transposed matrix $\\textit{ans}$ will have $n$ rows and $m$ columns.\n\nFor any position $(i, j)$ in $\\textit{ans}$, it corresponds to the position $(j, i)$ in the matrix $\\textit{matrix}$. Therefore, we traverse each element in the matrix $\\textit{matrix}$ and transpose it to the corresponding position in $\\textit{ans}$.\n\nAfter the traversal, we return $\\textit{ans}$.\n\nThe time complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns in the matrix $\\textit{matrix}$, respectively. Ignoring the space consumption of the answer, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(1)" }, { "problem_id": 868, "explanations": { "1": "We use two pointers $\\textit{pre}$ and $\\textit{cur}$ to represent the positions of the previous and current $1$ bits, respectively. Initially, $\\textit{pre} = 100$ and $\\textit{cur} = 0$. Then, we traverse the binary representation of $n$. When we encounter a $1$, we calculate the distance between the current position and the previous $1$ position and update the answer.\n\nThe time complexity is $O(\\log n)$, where $n$ is the given integer. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 869, "explanations": { "1": "We can enumerate all powers of 2 in the range $[1, 10^9]$ and check if their digit composition is the same as the given number.\n\nDefine a function $f(x)$ that represents the digit composition of number $x$. We can convert the number $x$ into an array of length 10, or a string sorted by digit size.\n\nFirst, we calculate the digit composition of the given number $n$ as $\\text{target} = f(n)$. Then, we enumerate $i$ starting from 1, shifting $i$ left by one bit each time (equivalent to multiplying by 2), until $i$ exceeds $10^9$. For each $i$, we calculate its digit composition and compare it with $\\text{target}$. If they are the same, we return $\\text{true}$; if the enumeration ends without finding the same digit composition, we return $\\text{false}$.\n\nTime complexity $O(\\log^2 M)$, space complexity $O(\\log M)$. Where $M$ is the upper limit of the input range ${10}^9$ for this problem." }, "is_english": true, "time_complexity": "O(\\log^2 M)", "space_complexity": "O(\\log M)" }, { "problem_id": 870, "explanations": { "1": "类似田忌赛马。将 $nums1$, $nums2$ 按照升序排列。然后遍历 $nums1$ 中的每个元素 $v$,若在 $nums2[i..j]$ 中找不到比 $v$ 小的,则将 $v$ 与当前 $nums2[i..j]$ 中的最大元素匹配。\n\n时间复杂度 $O(nlogn)$。" }, "is_english": false, "time_complexity": "O(nlogn)", "space_complexity": null }, { "problem_id": 871, "explanations": { "1": "We can use a priority queue (max-heap) $\\textit{pq}$ to record the fuel amounts of all the gas stations we have passed. Each time the fuel is insufficient, we greedily take out the maximum fuel amount, which is the top element of $\\textit{pq}$, and accumulate the number of refuels $\\textit{ans}$. If $\\textit{pq}$ is empty and the current fuel is still insufficient, it means we cannot reach the destination, and we return $-1$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ represents the number of gas stations." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 872, "explanations": { "1": "We can use Depth-First Search (DFS) to traverse the leaf nodes of the two trees, storing the values of the leaf nodes in two lists $l_1$ and $l_2$ respectively. Finally, we compare whether the two lists are equal.\n\nTime complexity is $O(n)$, and space complexity is $O(n)$. Here, $n$ is the number of nodes in the tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 873, "explanations": { "1": "We define $f[i][j]$ as the length of the longest Fibonacci-like subsequence, with $\\textit{arr}[i]$ as the last element and $\\textit{arr}[j]$ as the second to last element. Initially, for any $i \\in [0, n)$ and $j \\in [0, i)$, we have $f[i][j] = 2$. All other elements are $0$.\n\nWe use a hash table $d$ to record the indices of each element in the array $\\textit{arr}$.\n\nThen, we can enumerate $\\textit{arr}[i]$ and $\\textit{arr}[j]$, where $i \\in [2, n)$ and $j \\in [1, i)$. Suppose the currently enumerated elements are $\\textit{arr}[i]$ and $\\textit{arr}[j]$, we can obtain $\\textit{arr}[i] - \\textit{arr}[j]$, denoted as $t$. If $t$ is in the array $\\textit{arr}$, and the index $k$ of $t$ satisfies $k < j$, then we can get a Fibonacci-like subsequence with $\\textit{arr}[j]$ and $\\textit{arr}[i]$ as the last two elements, and its length is $f[i][j] = \\max(f[i][j], f[j][k] + 1)$. We can continuously update the value of $f[i][j]$ in this way, and then update the answer.\n\nAfter the enumeration ends, return the answer.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$, where $n$ is the length of the array $\\textit{arr}$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 874, "explanations": { "1": "We define a direction array $dirs = [0, 1, 0, -1, 0]$ of length $5$, where each pair of adjacent elements represents a direction. That is, $(dirs[0], dirs[1])$ represents north, $(dirs[1], dirs[2])$ represents east, and so on.\n\nWe use a hash table $s$ to store the coordinates of all obstacles, so we can determine in $O(1)$ time whether the next step will encounter an obstacle.\n\nAdditionally, we use two variables $x$ and $y$ to represent the robot's current coordinates, initially $x = y = 0$. The variable $k$ represents the robot's current direction, and the answer variable $ans$ represents the maximum squared Euclidean distance from the origin.\n\nNext, we iterate over each element $c$ in the array $commands$:\n\n- If $c = -2$, the robot turns left $90$ degrees, i.e., $k = (k + 3) \\bmod 4$;\n- If $c = -1$, the robot turns right $90$ degrees, i.e., $k = (k + 1) \\bmod 4$;\n- Otherwise, the robot moves forward $c$ units. We combine the robot's current direction $k$ with the direction array $dirs$ to obtain the increments along the $x$-axis and $y$-axis. We accumulate the increments step by step onto $x$ and $y$, and check whether each new coordinate $(nx, ny)$ is in the obstacle set. If not, we update the answer $ans$; otherwise, we stop the simulation and proceed to the next command.\n\nFinally, return the answer $ans$.\n\nThe time complexity is $O(C \\times n + m)$ and the space complexity is $O(m)$, where $C$ is the maximum number of steps per move, and $n$ and $m$ are the lengths of the arrays $commands$ and $obstacles$, respectively." }, "is_english": true, "time_complexity": "O(C \\times n + m)", "space_complexity": "O(m)" }, { "problem_id": 875, "explanations": { "1": "We notice that if Koko can eat all the bananas at a speed of $k$ within $h$ hours, then she can also eat all the bananas at a speed of $k' > k$ within $h$ hours. This shows monotonicity, so we can use binary search to find the smallest $k$ that satisfies the condition.\n\nWe define the left boundary of the binary search as $l = 1$, and the right boundary as $r = \\max(\\textit{piles})$. For each binary search, we take the middle value $mid = \\frac{l + r}{2}$, and then calculate the time $s$ required to eat bananas at a speed of $mid$. If $s \\leq h$, it means that the speed of $mid$ can meet the condition, and we update the right boundary $r$ to $mid$; otherwise, we update the left boundary $l$ to $mid + 1$. Finally, when $l = r$, we find the smallest $k$ that satisfies the condition.\n\nThe time complexity is $O(n \\times \\log M)$, where $n$ and $M$ are the length and maximum value of the array $\\textit{piles}$ respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(1)" }, { "problem_id": 876, "explanations": { "1": "We define two pointers $\\textit{fast}$ and $\\textit{slow}$, both initially pointing to the head of the linked list.\n\nThe fast pointer $\\textit{fast}$ moves two steps at a time, while the slow pointer $\\textit{slow}$ moves one step at a time. When the fast pointer reaches the end of the linked list, the node pointed to by the slow pointer is the middle node.\n\nThe time complexity is $O(n)$, where $n$ is the length of the linked list. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 877, "explanations": { "1": "We design a function $dfs(i, j)$ that represents the maximum difference in the number of stones between the current player and the other player when considering piles from the $i$-th to the $j$-th. The answer is then $dfs(0, n - 1) \\gt 0$.\n\nThe function $dfs(i, j)$ is computed as follows:\n\n- If $i \\gt j$, there are no stones left, so the current player cannot take any stones and the difference is $0$, i.e., $dfs(i, j) = 0$.\n- Otherwise, the current player has two choices: if they take the $i$-th pile, the difference between the current player and the other player is $piles[i] - dfs(i + 1, j)$; if they take the $j$-th pile, the difference is $piles[j] - dfs(i, j - 1)$. The current player will choose the option with the larger difference, so $dfs(i, j) = \\max(piles[i] - dfs(i + 1, j), piles[j] - dfs(i, j - 1))$.\n\nFinally, we only need to check whether $dfs(0, n - 1) \\gt 0$.\n\nTo avoid redundant computation, we can use memoization: we use an array $f$ to record all values of $dfs(i, j)$, so that when the function is called again, we can directly retrieve the answer from $f$ without recomputing.\n\nThe time complexity is $O(n^2)$ and the space complexity is $O(n^2)$, where $n$ is the number of stone piles.", "2": "We can also use dynamic programming. Define $f[i][j]$ as the maximum difference in the number of stones the current player can obtain over the other player from piles $piles[i..j]$. The final answer is then $f[0][n - 1] \\gt 0$.\n\nInitially, $f[i][i] = piles[i]$, because with only one pile, the current player can only take that pile, and the difference is $piles[i]$.\n\nFor $f[i][j]$ where $i \\lt j$, there are two cases:\n\n- If the current player takes pile $piles[i]$, the remaining piles are $piles[i + 1..j]$, and it becomes the other player's turn, so $f[i][j] = piles[i] - f[i + 1][j]$.\n- If the current player takes pile $piles[j]$, the remaining piles are $piles[i..j - 1]$, and it becomes the other player's turn, so $f[i][j] = piles[j] - f[i][j - 1]$.\n\nTherefore, the final state transition equation is $f[i][j] = \\max(piles[i] - f[i + 1][j], piles[j] - f[i][j - 1])$.\n\nFinally, we only need to check whether $f[0][n - 1] \\gt 0$.\n\nThe time complexity is $O(n^2)$ and the space complexity is $O(n^2)$, where $n$ is the number of stone piles.\n\nSimilar problems:\n\n- [486. Predict the Winner](https://github.com/doocs/leetcode/blob/main/solution/0400-0499/0486.Predict%20the%20Winner/README_EN.md)" }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 878, "explanations": { "1": "根据题目描述,神奇数字是能被 $a$ 或 $b$ 整除的正整数。\n\n而我们知道,对于任意正整数 $x$,在 $[1,..x]$ 范围内,能被 $a$ 整除的数有 $\\lfloor \\frac{x}{a} \\rfloor$ 个,能被 $b$ 整除的数有 $\\lfloor \\frac{x}{b} \\rfloor$ 个,能被 $a$ 和 $b$ 同时整除的数有 $\\lfloor \\frac{x}{c} \\rfloor$ 个,其中 $c$ 是 $a$ 和 $b$ 的最小公倍数。最小公倍数的计算公式为 $c = lcm(a, b) = \\frac{a \\times b}{gcd(a, b)}$。\n\n因此,对于任意正整数 $x$,在 $[1,..x]$ 范围内,神奇数字的个数为:\n\n$$\n\\lfloor \\frac{x}{a} \\rfloor + \\lfloor \\frac{x}{b} \\rfloor - \\lfloor \\frac{x}{c} \\rfloor\n$$\n\n为什么要减去 $\\lfloor \\frac{x}{c} \\rfloor$ 呢?可以这样理解,在 $[1,..x]$ 范围内,能被 $a$ 和 $b$ 同时整除的数,它们既能被 $a$ 整除,也能被 $b$ 整除,因此它们被计算了两次,需要减去一次。\n\n题目要我们找到第 $n$ 个神奇数字,也即是说,要找到一个最小的正整数 $x$,使得以下式子成立:\n\n$$\n\\lfloor \\frac{x}{a} \\rfloor + \\lfloor \\frac{x}{b} \\rfloor - \\lfloor \\frac{x}{c} \\rfloor \\geq n\n$$\n\n随着 $x$ 的增大,神奇数字的个数也会增大,因此我们可以使用二分查找的方法,找到最小的正整数 $x$,使得上述式子成立。\n\n注意答案的取模操作。\n\n时间复杂度 $O(\\log M)$,空间复杂度 $O(1)$。其中 $M$ 是二分查找的上界,本题可以取 $M=(a+b) \\times n$。" }, "is_english": false, "time_complexity": "O(\\log M)", "space_complexity": "O(1)" }, { "problem_id": 879, "explanations": { "1": "We design a function $dfs(i, j, k)$, which means that we start from the $i$-th job, and have chosen $j$ employees, and the current profit is $k$, then the number of schemes in this case is $dfs(0, 0, 0)$.\n\nThe execution process of function $dfs(i, j, k)$ is as follows:\n\n- If $i = n$, it means that all the jobs have been considered. If $k \\geq minProfit$, the number of schemes is $1$, otherwise the number of schemes is $0$;\n- If $i < n$, we can choose not to choose the $i$-th job, then the number of schemes is $dfs(i + 1, j, k)$; if $j + group[i] \\leq n$, we can also choose the $i$-th job, then the number of schemes is $dfs(i + 1, j + group[i], \\min(k + profit[i], minProfit))$. Here we limit the profit upper limit to $minProfit$, because the profit exceeding $minProfit$ has no effect on our answer.\n\nFinally, return $dfs(0, 0, 0)$.\n\nIn order to avoid repeated calculation, we can use the method of memoization. We use a three-dimensional array $f$ to record all the results of $dfs(i, j, k)$. When we calculate the value of $dfs(i, j, k)$, we store it in $f[i][j][k]$. When we call $dfs(i, j, k)$, if $f[i][j][k]$ has been calculated, we return $f[i][j][k]$ directly.\n\nThe time complexity is $O(m \\times n \\times minProfit)$, and th e space complexity is $O(m \\times n \\times minProfit)$. Here $m$ and $n$ are the number of jobs and employees, and $minProfit$ is the minimum profit.", "2": "We define $f[i][j][k]$ to be the number of schemes to make a profit of at least $k$ with $i$ jobs and $j$ workers. Initially, we have $f[0][j][0] = 1$, which means that there is only one scheme to make a profit of $0$ without any jobs.\n\nFor the $i$-th job, we can choose to work or not to work. If we do not work, then $f[i][j][k] = f[i - 1][j][k]$; if we work, then $f[i][j][k] = f[i - 1][j - group[i - 1]][max(0, k - profit[i - 1])]$. We need to enumerate $j$ and $k$, and add up all the schemes.\n\nThe final answer is $f[m][n][minProfit]$.\n\nThe time complexity is $O(m \\times n \\times minProfit)$, and the space complexity is $O(m \\times n \\times minProfit)$. Here $m$ and $n$ are the numbers of jobs and workers, and $minProfit$ is the minimum profit to make." }, "is_english": true, "time_complexity": "O(m \\times n \\times minProfit)", "space_complexity": "O(m \\times n \\times minProfit)" }, { "problem_id": 880, "explanations": { "1": "We can first calculate the total length $m$ of the decoded string, then traverse the string from back to front. Each time, we update $k$ to be $k \\bmod m$, until $k$ is $0$ and the current character is a letter, then we return the current character. Otherwise, if the current character is a number, we divide $m$ by this number. If the current character is a letter, we subtract $1$ from $m$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 881, "explanations": { "1": "After sorting, use two pointers to point to the beginning and end of the array respectively. Each time, compare the sum of the elements pointed to by the two pointers with `limit`. If it is less than or equal to `limit`, then both pointers move one step towards the middle. Otherwise, only the right pointer moves. Accumulate the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array `people`." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 882, "explanations": { "1": "这道题本质是求从节点 $0$ 出发,最多经过 $maxMoves$ 步,可以到达多少个节点。单源最短路,且边权非负,我们可以考虑使用 Dijkstra 算法。\n\n根据题目描述,节点 $u_i$ 到节点 $v_i$ 之间存在 $cnt_i$ 个新节点,那么节点 $u_i$ 到节点 $v_i$ 的距离为 $cnt_i + 1$。\n\n我们举个简单的例子,以下节点 $1$ 和节点 $2$ 之间存在 $3$ 个新节点,那么节点 $1$ 到节点 $2$ 之间有 $4$ 条边,也即距离为 $4$。\n\n```\n1 -- o -- o -- o -- 2\n```\n\n因此,我们可以将原图中两点之间新节点的个数 $cnt_i$ 加 $1$,得到两点之间的距离。然后构建一个邻接表 $g$,用于存储每个节点的邻接节点以及到达邻接节点的距离。\n\n接下来,我们使用 Dijkstra 算法求出从节点 $0$ 到原始图其余所有节点的最短距离,存储在数组 $dist$ 中。\n\n然后,我们遍历数组 $dist$,统计其中小于等于 $maxMoves$ 的节点个数,也就是我们可以到达的节点数。不过,这并不是最终答案,我们还需要加上新节点中符合条件的节点个数。\n\n我们可以发现,如果我们能在 $dist[u]$ 步到达节点 $u$(其中 $dist[u] \\leq maxMoves$),并且节点 $u$ 到节点 $v$ 之间有 $cnt$ 个新节点,那么我们能通过节点 $u$ 到达的新节点个数 $a=\\min(cnt, maxMoves - dist[u])$。同理,我们能通过节点 $v$ 到达的新节点个数 $b=\\min(cnt, maxMoves - dist[v])$。那么,我们能到达节点 $u$ 和节点 $v$ 之间的新节点个数为 $\\min(cnt, a + b)$。\n\n因此,我们再遍历所有的边,统计其中能到达的新节点个数,累加到答案中即可。\n\n时间复杂度 $O(n + m \\times \\log n)$,其中 $m$ 和 $n$ 分别为边数和节点数。" }, "is_english": false, "time_complexity": "O(n + m \\times \\log n)", "space_complexity": null }, { "problem_id": 883, "explanations": { "1": "We can calculate the area of the three projections separately.\n\n- Projection area on the xy plane: Each non-zero value will be projected onto the xy plane, so the projection area on the xy plane is the count of non-zero values.\n- Projection area on the yz plane: The maximum value in each row.\n- Projection area on the zx plane: The maximum value in each column.\n\nFinally, add up the three areas.\n\nThe time complexity is $O(n^2)$, where $n$ is the side length of the grid `grid`. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(1)" }, { "problem_id": 884, "explanations": { "1": "According to the problem description, as long as a word appears once, it meets the requirements of the problem. Therefore, we use a hash table `cnt` to record all words and their occurrence counts.\n\nThen we traverse the hash table, and take out all strings that appear only once.\n\nThe time complexity is $O(m + n)$, and the space complexity is $O(m + n)$. Here, $m$ and $n$ are the lengths of strings `s1` and `s2`, respectively." }, "is_english": true, "time_complexity": "O(m + n)", "space_complexity": "O(m + n)" }, { "problem_id": 885, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 886, "explanations": { "1": "我们用两种颜色对图进行染色,如果可以完成染色,那么就说明可以将所有人分进两组。\n\n具体的染色方法如下:\n\n- 初始化所有人的颜色为 $0$,表示还没有染色。\n- 遍历所有人,如果当前人没有染色,那么就用颜色 $1$ 对其进行染色,然后将其所有不喜欢的人用颜色 $2$ 进行染色。如果染色过程中出现了冲突,那么就说明无法将所有人分进两组,返回 `false`。\n- 如果所有人都染色成功,那么就说明可以将所有人分进两组,返回 `true`。\n\n时间复杂度 $O(n + m)$,其中 $n$, $m$ 分别是人数和不喜欢的关系数。", "2": "并查集是一种树形的数据结构,顾名思义,它用于处理一些不交集的**合并**及**查询**问题。 它支持两种操作:\n\n1. 查找(Find):确定某个元素处于哪个子集,单次操作时间复杂度 $O(\\alpha(n))$\n1. 合并(Union):将两个子集合并成一个集合,单次操作时间复杂度 $O(\\alpha(n))$\n\n其中 $\\alpha$ 为阿克曼函数的反函数,其增长极其缓慢,也就是说其单次操作的平均运行时间可以认为是一个很小的常数。\n\n以下是并查集的常用模板,需要熟练掌握。其中:\n\n- `n` 表示节点数\n- `p` 存储每个点的父节点,初始时每个点的父节点都是自己\n- `size` 只有当节点是祖宗节点时才有意义,表示祖宗节点所在集合中,点的数量\n- `find(x)` 函数用于查找 $x$ 所在集合的祖宗节点\n- `union(a, b)` 函数用于合并 $a$ 和 $b$ 所在的集合\n\n```python\np = list(range(n))\nsize = [1] * n\n\n\ndef find(x):\n if p[x] != x:\n # 路径压缩\n p[x] = find(p[x])\n return p[x]\n\n\ndef union(a, b):\n pa, pb = find(a), find(b)\n if pa == pb:\n return\n p[pa] = pb\n size[pb] += size[pa]\n```\n\n对于本题,我们遍历每一个人,他与他不喜欢的人不应该在同一个集合中,如果在同一个集合中,就产生了冲突,直接返回 `false`。如果没有冲突,那么就将他所有不喜欢的人合并到同一个集合中。\n\n遍历结束,说明没有冲突,返回 `true`。\n\n时间复杂度 $O(n + m\\times \\alpha(n))$。" }, "is_english": false, "time_complexity": "O(n + m)", "space_complexity": null }, { "problem_id": 887, "explanations": { "1": "我们设计一个函数 $dfs(i, j)$,表示有 $i$ 层楼以及 $j$ 个鸡蛋时,确定 $f$ 值的最小操作次数,那么答案就是 $dfs(n, k)$。\n\n函数 $dfs(i, j)$ 的执行逻辑如下:\n\n如果 $i \\lt 1$,说明楼层已经小于等于 $0$,此时返回 $0$;\n\n如果 $j = 1$,说明只有一个鸡蛋,那么只能从第一层开始一层一层试,最坏情况下需要试 $i$ 次,此时返回 $i$;\n\n否则,我们考虑枚举第一个鸡蛋从第 $x$ 层扔下的情况,其中 $1 \\le x \\le i$。如果鸡蛋在第 $x$ 层扔下时碎了,说明 $f \\lt x$,此时我们接下来需要在 $x - 1$ 层下方以及剩下的 $j - 1$ 个鸡蛋确定 $f$ 值,总共需要的最小操作次数为 $dfs(x - 1, j - 1) + 1$ 次;如果鸡蛋在第 $x$ 层扔下时没碎,说明 $f \\gt x$,此时我们需要在第 $x + 1$ 层及以上以及剩下的 $j$ 个鸡蛋确定 $f$ 值,总共需要的最小操作次数为 $dfs(i - x, j) + 1$ 次。由于我们要保证最坏情况下操作次数最少,因此 $dfs(i, j) = \\min_{1 \\le x \\le i} \\max(dfs(x - 1, j - 1), dfs(i - x, j)) + 1$。\n\n如果按照这样的方式枚举,由于状态数有 $n \\times k$,每个状态需要枚举 $n$ 次,那么总时间复杂度达到 $O(n^2 \\times k)$,这会超出时间限制,我们考虑如何进行优化。\n\n我们注意到函数 $dfs(x - 1, j - 1)$ 随着 $x$ 的增大而单调递增,而函数 $dfs(i - x, j)$ 随着 $x$ 的增大而单调递减,因此存在一个最优的 $x$ 值使得 $\\max(dfs(x - 1, j - 1), dfs(i - x, j))$ 达到最小值。我们可以对 $x$ 进行二分查找,找出这个最优的 $x$ 值。其中 $x$ 是满足 $dfs(x - 1, j - 1) \\le dfs(i - x, j)$ 的最大整数。这样我们可以将时间复杂度降低到 $O(n \\times k \\log n)$。\n\n时间复杂度 $O(n \\times k \\log n)$,空间复杂度 $O(n \\times k)$。其中 $n$ 和 $k$ 分别是楼层数和鸡蛋数。", "2": "我们也可以使用动态规划的方法解决这个问题。\n\n我们定义 $f[i][j]$ 表示有 $i$ 层楼以及 $j$ 个鸡蛋时,确定 $f$ 值的最小操作次数,那么答案就是 $f[n][k]$。\n\n状态转移方程为 $f[i][j] = \\min_{1 \\le x \\le i} \\max(f[x - 1][j - 1], f[i - x][j]) + 1$。\n\n与方法一类似,我们可以使用二分查找来优化 $x$ 的枚举过程。\n\n时间复杂度 $O(n \\times k \\log n)$,空间复杂度 $O(n \\times k)$。其中 $n$ 和 $k$ 分别是楼层数和鸡蛋数。" }, "is_english": false, "time_complexity": "O(n^2 \\times k)", "space_complexity": "O(n \\times k)" }, { "problem_id": 888, "explanations": { "1": "We can first calculate the difference in the total number of candies between Alice and Bob, divide it by two to get the difference in the number of candies to be exchanged $\\textit{diff}$, and use a hash table $\\textit{s}$ to store the number of candies in Bob's candy boxes. Then, we traverse Alice's candy boxes, and for each candy count $\\textit{a}$, we check if $\\textit{a} - \\textit{diff}$ is in the hash table $\\textit{s}$. If it exists, it means we have found a valid answer, and we return it.\n\nThe time complexity is $O(m + n)$, and the space complexity is $O(n)$. Where $m$ and $n$ are the number of candy boxes Alice and Bob have, respectively." }, "is_english": true, "time_complexity": "O(m + n)", "space_complexity": "O(n)" }, { "problem_id": 889, "explanations": { "1": "The order of pre-order traversal is: root node -> left subtree -> right subtree, and the order of post-order traversal is: left subtree -> right subtree -> root node.\n\nTherefore, the root node of the binary tree must be the first node of the pre-order traversal and the last node of the post-order traversal.\n\nNext, we need to determine the range of the left and right subtrees of the binary tree.\n\nIf the binary tree has a left subtree, then the root node of the left subtree must be the second node of the pre-order traversal; if the binary tree does not have a left subtree, then the second node of the pre-order traversal must be the root node of the right subtree. Since the results of post-order traversal in these two cases are the same, we can take the second node of the pre-order traversal as the root node of the left subtree, and then find its position in the post-order traversal, so as to determine the range of the left subtree.\n\nSpecifically, we design a recursive function $dfs(a, b, c, d)$, where $[a, b]$ represents the range of pre-order traversal, and $[c, d]$ represents the range of post-order traversal. The function of this function is to construct the root node of the binary tree based on the pre-order traversal $[a, b]$ and the post-order traversal $[c, d]$. The answer is $dfs(0, n - 1, 0, n - 1)$, where $n$ is the length of the pre-order traversal.\n\nThe execution steps of the function $dfs(a, b, c, d)$ are as follows:\n\n1. If $a > b$, the range is empty, return a null node directly.\n1. Otherwise, we construct a new node $root$, its value is the value of the first node in the pre-order traversal, which is $preorder[a]$.\n1. If $a$ equals $b$, it means that $root$ has neither a left subtree nor a right subtree, return $root$ directly.\n1. Otherwise, the value of the root node of the left subtree is $preorder[a + 1]$, we find the position of $preorder[a + 1]$ in the post-order traversal, denoted as $i$. The number of nodes in the left subtree $m = i - c + 1$, from this we know that the range of the left subtree in the pre-order traversal is $[a + 1, a + m]$, the range in the post-order traversal is $[c, i]$, the range of the right subtree in the pre-order traversal is $[a + m + 1, b]$, and the range in the post-order traversal is $[i + 1, d - 1]$.\n1. Knowing the range of the left and right subtrees, we can recursively rebuild the left and right subtrees, and then make the root nodes of the left and right subtrees as the left and right child nodes of $root$ respectively. Finally return $root$.\n\nIn the function $dfs(a, b, c, d)$, we need to use a hash table $pos$, which stores the position of each node in the post-order traversal. At the beginning of the function, we can calculate this hash table first, so that we can find the position of any node in the post-order traversal in $O(1)$ time.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes.", "2": "We can design a recursive function $dfs(i, j, n)$, where $i$ and $j$ represent the starting points of the pre-order and post-order traversals, respectively, and $n$ represents the number of nodes. This function constructs the root node of the binary tree based on the pre-order traversal $[i, i + n - 1]$ and post-order traversal $[j, j + n - 1]$. The answer is $dfs(0, 0, n)$, where $n$ is the length of the pre-order traversal.\n\nThe execution steps of the function $dfs(i, j, n)$ are as follows:\n\n1. If $n = 0$, the range is empty, so return a null node directly.\n2. Otherwise, we construct a new node $root$, whose value is the value of the first node in the pre-order traversal, which is $preorder[i]$.\n3. If $n = 1$, it means that $root$ has neither a left subtree nor a right subtree, so return $root$ directly.\n4. Otherwise, the value of the root node of the left subtree is $preorder[i + 1]$. We find the position of $preorder[i + 1]$ in the post-order traversal, denoted as $k$. Then the number of nodes in the left subtree is $m = k - j + 1$, and the number of nodes in the right subtree is $n - m - 1$. We recursively rebuild the left and right subtrees, and then make the root nodes of the left and right subtrees the left and right child nodes of $root$, respectively. Finally, return $root$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 890, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 891, "explanations": { "1": "题目求解的是数组 `nums` 中所有子序列中最大值与最小值差值之和,注意到“子序列”,并且涉及到“最大值”与“最小值”,我们考虑先对数组 `nums` 进行排序。\n\n然后我们枚举数组 `nums` 中的每个元素 $nums[i]$,该元素左侧的元素个数为 $i$,右侧的元素个数为 $n-i-1$。\n\n如果我们将元素 $nums[i]$ 作为子序列的最大值,总共有多少个满足条件的子序列呢?显然,子序列的其他元素应该从左侧的 $i$ 个元素中选取,每个元素有两种选择,即选或不选,因此总共有 $2^i$ 个子序列。同理,如果我们将元素 $nums[i]$ 作为子序列的最小值,那么总共有 $2^{n-i-1}$ 个满足条件的子序列。因此 $nums[i]$ 对答案的贡献为:\n\n$$\n\\begin{aligned}\nnums[i] \\times (2^i - 2^{n-i-1})\n\\end{aligned}\n$$\n\n我们将数组 `nums` 中所有元素的贡献累加,即为答案:\n\n$$\n\\begin{aligned}\n\\sum_{i=0}^{n-1} nums[i] \\times (2^i - 2^{n-i-1})\n\\end{aligned}\n$$\n\n我们将上式展开,可以得到:\n\n$$\n\\begin{aligned}\nnums[0] \\times (2^0 - 2^{n-1}) + nums[1] \\times (2^1 - 2^{n-2}) + ... + nums[n-1] \\times (2^{n-1} - 2^0)\n\\end{aligned}\n$$\n\n再将式子中相同的幂次项合并,可以得到:\n\n$$\n\\begin{aligned}\n(nums[0] - nums[n-1]) \\times 2^0 + (nums[1] - nums[n-2]) \\times 2^1 + ... + (nums[n-1] - nums[0]) \\times 2^{n-1}\n\\end{aligned}\n$$\n\n即:\n\n$$\n\\begin{aligned}\n\\sum_{i=0}^{n-1} (nums[i] - nums[n-i-1]) \\times 2^i\n\\end{aligned}\n$$\n\n因此我们只需要对数组 `nums` 进行排序,然后计算上述的贡献即可。注意答案的取模操作。\n\n时间复杂度 $O(n\\times \\log n)$,空间复杂度 $O(\\log n)$。其中 $n$ 为数组 `nums` 的长度。" }, "is_english": false, "time_complexity": "O(n\\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 892, "explanations": { "1": "时间复杂度 $O(n^2)$,空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(n^2)", "space_complexity": "O(1)" }, { "problem_id": 893, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 894, "explanations": { "1": "If $n=1$, return a list with a single node directly.\n\nIf $n > 1$, we can enumerate the number of nodes $i$ in the left subtree, then the number of nodes in the right subtree is $n-1-i$. For each case, we recursively construct all possible genuine binary trees for the left and right subtrees. Then we combine the left and right subtrees in pairs to get all possible genuine binary trees.\n\nThis process can be optimized with memoization search to avoid repeated calculations.\n\nThe time complexity is $O(\\frac{2^n}{\\sqrt{n}})$, and the space complexity is $O(\\frac{2^n}{\\sqrt{n}})$. Where $n$ is the number of nodes." }, "is_english": true, "time_complexity": "O(\\frac{2^n}{\\sqrt{n}})", "space_complexity": "O(\\frac{2^n}{\\sqrt{n}})" }, { "problem_id": 895, "explanations": { "1": "According to the problem description, we need to design a data structure that supports popping out the element with the highest frequency. If multiple elements have the same frequency, the element closest to the top of the stack should be popped out.\n\nWe can use a hash table $cnt$ to record the frequency of each element, and a priority queue (max heap) $q$ to maintain the frequency of elements and their corresponding timestamps.\n\nWhen performing a push operation, we first increment the current timestamp, i.e., $ts \\gets ts + 1$; then we increment the frequency of the element $val$, i.e., $cnt[val] \\gets cnt[val] + 1$, and finally, we add the triplet $(cnt[val], ts, val)$ to the priority queue $q$. The time complexity of the push operation is $O(\\log n)$.\n\nWhen performing a pop operation, we directly pop an element from the priority queue $q$. Since the elements in the priority queue $q$ are sorted in descending order of frequency, the popped element is definitely the one with the highest frequency. If multiple elements have the same frequency, the element closest to the top of the stack is popped out, i.e., the element with the largest timestamp is popped out. After popping, we decrement the frequency of the popped element, i.e., $cnt[val] \\gets cnt[val] - 1$. The time complexity of the pop operation is $O(\\log n)$.", "2": "In Solution 1, in order to pop out the required element, we maintained a priority queue and had to operate on it each time, which has a time complexity of $O(\\log n)$. If we can find the required element in $O(1)$ time, then the time complexity of each operation of the entire data structure can be reduced to $O(1)$.\n\nIn fact, we can use a variable $mx$ to record the current maximum frequency, a hash table $d$ to record the list of elements corresponding to each frequency, and as in Solution 1, a hash table $cnt$ to record the frequency of each element.\n\nWhen performing a push operation, we increment the frequency of the element, i.e., $cnt[val] \\gets cnt[val] + 1$, and then add the element $val$ to the corresponding frequency list in the hash table $d$, i.e., $d[cnt[val]].push(val)$. If the current element's frequency is greater than $mx$, then update $mx$, i.e., $mx \\gets cnt[val]$. The time complexity of the push operation is $O(1)$.\n\nWhen performing a pop operation, we take the list of elements with frequency $mx$ from the hash table $d$, pop out the last element $val$ in the list, and then remove $val$ from the hash table $d$, i.e., $d[mx].pop()$. Finally, we decrement the frequency of $val$, i.e., $cnt[val] \\gets cnt[val] - 1$. If the list $d[mx]$ is empty, it means that all elements with the current maximum frequency have been popped out, and we need to decrement $mx$, i.e., $mx \\gets mx - 1$. The time complexity of the pop operation is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": null }, { "problem_id": 896, "explanations": { "1": "We traverse the array, and if an increasing or decreasing situation occurs, we record it. We then check whether both increasing and decreasing situations have occurred. If both have occurred, it means that the array is not monotonic, and we return `false`.\n\nOtherwise, if we reach the end of the traversal, it means that the array is monotonic, and we return `true`.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 897, "explanations": { "1": "We define a virtual node $dummy$, initially the right child of $dummy$ points to the root node $root$, and a pointer $prev$ points to $dummy$.\n\nWe perform an in-order traversal on the binary search tree. During the traversal, each time we visit a node, we point the right child of $prev$ to it, then set the left child of the current node to null, and assign the current node to $prev$ for the next traversal.\n\nAfter the traversal ends, the original binary search tree is modified into a singly linked list with only right child nodes. We then return the right child of the virtual node $dummy$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary search tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 898, "explanations": { "1": "The problem asks for the number of unique bitwise OR operations results of subarrays. If we enumerate the end position $i$ of the subarray, the number of bitwise OR operations results of the subarray ending at $i-1$ does not exceed $32$. This is because the bitwise OR operation is a monotonically increasing operation.\n\nTherefore, we use a hash table $ans$ to record all the results of the bitwise OR operations of subarrays, and a hash table $s$ to record the results of the bitwise OR operations of subarrays ending with the current element. Initially, $s$ only contains one element $0$.\n\nNext, we enumerate the end position $i$ of the subarray. The result of the bitwise OR operation of the subarray ending at $i$ is the set of results of the bitwise OR operation of the subarray ending at $i-1$ and $a[i]$, plus $a[i]$ itself. We use a hash table $t$ to record the results of the bitwise OR operation of the subarray ending at $i$, then we update $s = t$, and add all elements in $t$ to $ans$.\n\nFinally, we return the number of elements in the hash table $ans$.\n\nThe time complexity is $O(n \\times \\log M)$, and the space complexity is $O(n \\times \\log M)$. Here, $n$ and $M$ are the length of the array and the maximum value in the array, respectively." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(n \\times \\log M)" }, { "problem_id": 899, "explanations": { "1": "If $k = 1$, we can only move the first character of the string to the end of the string each time, resulting in $|s|$ different states. We return the string with the smallest lexicographic order.\n\nIf $k > 1$, for a string like $abc[xy]def$, we can move $a$, $b$, and $c$ to the end in order, resulting in $[xy]defabc$. Then we move $y$ and $x$ to the end, resulting in $defabc[yx]$. Finally, we move $d$, $e$, and $f$ to the end, resulting in $abc[yx]def$. This way, we have swapped $y$ and $x$.\n\nTherefore, as long as $k > 1$, we can swap any two adjacent characters in the string, eventually obtaining a string sorted in ascending order.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 900, "explanations": { "1": "We define two pointers $i$ and $j$, where pointer $i$ points to the current run-length encoding being read, and pointer $j$ points to which character in the current run-length encoding is being read. Initially, $i = 0$, $j = 0$.\n\nEach time we call `next(n)`, we judge whether the remaining number of characters in the current run-length encoding $encoding[i] - j$ is less than $n$. If it is, we subtract $n$ by $encoding[i] - j$, add $2$ to $i$, and set $j$ to $0$, then continue to judge the next run-length encoding. If it is not, we add $n$ to $j$ and return $encoding[i + 1]$.\n\nIf $i$ exceeds the length of the run-length encoding and there is still no return value, it means that there are no remaining elements to be exhausted, and we return $-1$.\n\nThe time complexity is $O(n + q)$, and the space complexity is $O(n)$. Here, $n$ is the length of the run-length encoding, and $q$ is the number of times `next(n)` is called." }, "is_english": true, "time_complexity": "O(n + q)", "space_complexity": "O(n)" }, { "problem_id": 901, "explanations": { "1": "Based on the problem description, we know that for the current day's price $price$, we start from this price and look backwards to find the first price that is larger than this price. The difference in indices $cnt$ between these two prices is the span of the current day's price.\n\nThis is actually a classic monotonic stack model, where we find the first element larger than the current element on the left.\n\nWe maintain a stack where the prices from the bottom to the top of the stack are monotonically decreasing. Each element in the stack is a $(price, cnt)$ data pair, where $price$ represents the price, and $cnt$ represents the span of the current price.\n\nWhen the price $price$ appears, we compare it with the top element of the stack. If the price of the top element of the stack is less than or equal to $price$, we add the span $cnt$ of the current day's price to the span of the top element of the stack, and then pop the top element of the stack. This continues until the price of the top element of the stack is greater than $price$, or the stack is empty.\n\nFinally, we push $(price, cnt)$ onto the stack and return $cnt$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of times `next(price)` is called." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 902, "explanations": { "1": "This problem essentially asks for the number of positive integers that can be generated from the digits in digits within the given range $[l, .., r]$. The count depends on the number of digits and the value of each digit. We can solve this problem using the Digit DP approach. In Digit DP, the size of the number has little impact on the complexity.\n\nFor the range $[l, .., r]$ problem, we generally convert it to the problem of $[1, .., r]$ and then subtract the result of $[1, .., l - 1]$, i.e.,\n\n$$\nans = \\sum_{i=1}^{r} ans_i - \\sum_{i=1}^{l-1} ans_i\n$$\n\nHowever, for this problem, we only need to find the value for the range $[1, .., r]$.\n\nHere, we use memoization to implement Digit DP. We start searching from the top, get the number of solutions at the bottom, and return the answers layer by layer until we get the final answer from the starting point.\n\nThe basic steps are as follows:\n\nWe convert the number $n$ into a string $s$ and denote the length of the string $s$ as $m$.\n\nNext, we design a function $\\textit{dfs}(i, \\textit{lead}, \\textit{limit})$ to represent the number of solutions from the current $i$-th digit to the last digit of the string. Here:\n\n- The integer $i$ represents the current position in the string $s$.\n- The boolean $\\textit{lead}$ indicates whether the current number contains only leading zeros.\n- The boolean $\\textit{limit}$ indicates whether the current position is restricted by the upper bound.\n\nThe function executes as follows:\n\nIf $i$ is greater than or equal to $m$, it means we have processed all digits. If $\\textit{lead}$ is true, it means the current number is a leading zero, and we should return $0$. Otherwise, we should return $1$.\n\nOtherwise, we calculate the upper bound $\\textit{up}$. If $\\textit{limit}$ is true, then $\\textit{up}$ is the digit corresponding to $s[i]$. Otherwise, $\\textit{up}$ is $9$.\n\nThen, we enumerate the current digit $j$ in the range $[0, \\textit{up}]$. If $j$ is $0$ and $\\textit{lead}$ is true, we recursively calculate $\\textit{dfs}(i + 1, \\text{true}, \\textit{limit} \\wedge j = \\textit{up})$. Otherwise, if $j$ is in $\\textit{digits}$, we recursively calculate $\\textit{dfs}(i + 1, \\text{false}, \\textit{limit} \\wedge j = \\textit{up})$. We accumulate all the results as the answer.\n\nFinally, we return $\\textit{dfs}(0, \\text{true}, \\text{true})$.\n\nThe time complexity is $O(\\log n \\times D)$, and the space complexity is $O(\\log n)$. Here, $D = 10$.\n\nSimilar problems:\n\n- [233. Number of Digit One](https://github.com/doocs/leetcode/blob/main/solution/0200-0299/0233.Number%20of%20Digit%20One/README_EN.md)\n- [357. Count Numbers with Unique Digits](https://github.com/doocs/leetcode/blob/main/solution/0300-0399/0357.Count%20Numbers%20with%20Unique%20Digits/README_EN.md)\n- [600. Non-negative Integers without Consecutive Ones](https://github.com/doocs/leetcode/blob/main/solution/0600-0699/0600.Non-negative%20Integers%20without%20Consecutive%20Ones/README_EN.md)\n- [788. Rotated Digits](https://github.com/doocs/leetcode/blob/main/solution/0700-0799/0788.Rotated%20Digits/README_EN.md)\n- [1012. Numbers With Repeated Digits](https://github.com/doocs/leetcode/blob/main/solution/1000-1099/1012.Numbers%20With%20Repeated%20Digits/README_EN.md)\n- [2376. Count Special Integers](https://github.com/doocs/leetcode/blob/main/solution/2300-2399/2376.Count%20Special%20Integers/README_EN.md)" }, "is_english": true, "time_complexity": "O(\\log n \\times D)", "space_complexity": "O(\\log n)" }, { "problem_id": 903, "explanations": { "1": "We define $f[i][j]$ as the number of permutations that satisfy the problem's requirements with the first $i$ characters of the string ending with the number $j$. Initially, $f[0][0]=1$, and the rest $f[0][j]=0$. The answer is $\\sum_{j=0}^n f[n][j]$.\n\nConsider $f[i][j]$, where $j \\in [0, i]$.\n\nIf the $i$th character $s[i-1]$ is `'D'`, then $f[i][j]$ can be transferred from $f[i-1][k]$, where $k \\in [j+1, i]$. Since $k-1$ can only be up to $i-1$, we move $k$ one place to the left, so $k \\in [j, i-1]$. Therefore, we have $f[i][j] = \\sum_{k=j}^{i-1} f[i-1][k]$.\n\nIf the $i$th character $s[i-1]$ is `'I'`, then $f[i][j]$ can be transferred from $f[i-1][k]$, where $k \\in [0, j-1]$. Therefore, we have $f[i][j] = \\sum_{k=0}^{j-1} f[i-1][k]$.\n\nThe final answer is $\\sum_{j=0}^n f[n][j]$.\n\nThe time complexity is $O(n^3)$, and the space complexity is $O(n^2)$. Here, $n$ is the length of the string." }, "is_english": true, "time_complexity": "O(n^3)", "space_complexity": "O(n^2)" }, { "problem_id": 904, "explanations": { "1": "We use a hash table $cnt$ to maintain the types and corresponding quantities of fruits in the current window, and use two pointers $j$ and $i$ to maintain the left and right boundaries of the window.\n\nWe traverse the $\\textit{fruits}$ array, add the current fruit $x$ to the window, i.e., $cnt[x]++$, then judge whether the types of fruits in the current window exceed $2$. If it exceeds $2$, we need to move the left boundary $j$ of the window to the right until the types of fruits in the window do not exceed $2$. Then we update the answer, i.e., $ans = \\max(ans, i - j + 1)$.\n\nAfter the traversal ends, we can get the final answer.\n\n```\n1 2 3 2 2 1 4\n^ ^\nj i\n\n\n1 2 3 2 2 1 4\n ^ ^\n j i\n\n\n1 2 3 2 2 1 4\n ^ ^\n j i\n```\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the $\\textit{fruits}$ array.", "2": "In Solution 1, we find that the window size sometimes increases and sometimes decreases, which requires us to update the answer each time.\n\nBut what this problem actually asks for is the maximum number of fruits, that is, the \"largest\" window. We don't need to shrink the window, we just need to let the window monotonically increase. So the code omits the operation of updating the answer each time, and only needs to return the size of the window as the answer after the traversal ends.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the $\\textit{fruits}$ array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 905, "explanations": { "1": "We use two pointers $i$ and $j$ to point to the beginning and end of the array respectively. When $i < j$, we perform the following operations.\n\n- If $nums[i]$ is even, then increment $i$ by $1$.\n- If $nums[j]$ is odd, then decrement $j$ by $1$.\n- If $nums[i]$ is odd and $nums[j]$ is even, then swap $nums[i]$ and $nums[j]$. Then increment $i$ by $1$, and decrement $j$ by $1$.\n\nFinally, return the array $nums$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 906, "explanations": { "1": "According to the problem description, we assume that the super palindrome number $x = p^2 \\in [1, 10^{18})$, where $p$ is a palindrome number, so $p \\in [1, 10^9)$. We can enumerate the first half of the palindrome number $p$, then reverse it, and concatenate it to get all palindrome numbers, which are recorded in the array $ps$.\n\nNext, we traverse the array $ps$. For each $p$, we calculate $p^2$, check whether it is in the interval $[L, R]$, and also check whether $p^2$ is a palindrome number. If it is, the answer is incremented by one.\n\nAfter the traversal, return the answer.\n\nThe time complexity is $O(M^{\\frac{1}{4}} \\times \\log M)$, and the space complexity is $O(M^{\\frac{1}{4}})$. Where $M$ is the upper bound of $L$ and $R$, and in this problem, $M \\leq 10^{18}$.\n\nSimilar problems:\n\n- [2967. Minimum Cost to Make Array Equalindromic](https://github.com/doocs/leetcode/blob/main/solution/2900-2999/2967.Minimum%20Cost%20to%20Make%20Array%20Equalindromic/README_EN.md)" }, "is_english": true, "time_complexity": "O(M^{\\frac{1}{4}} \\times \\log M)", "space_complexity": "O(M^{\\frac{1}{4}})" }, { "problem_id": 907, "explanations": { "1": "The problem asks for the sum of the minimum values of each subarray, which is equivalent to finding the number of subarrays for which each element $arr[i]$ is the minimum, then multiplying by $arr[i]$, and finally summing these up.\n\nTherefore, the focus of the problem is to find the number of subarrays for which $arr[i]$ is the minimum. For $arr[i]$, we find the first position $left[i]$ to its left that is less than $arr[i]$, and the first position $right[i]$ to its right that is less than or equal to $arr[i]$. The number of subarrays for which $arr[i]$ is the minimum is $(i - left[i]) \\times (right[i] - i)$.\n\nNote, why do we find the first position $right[i]$ to the right that is less than or equal to $arr[i]$, rather than less than $arr[i]$? This is because if we find the first position $right[i]$ to the right that is less than $arr[i]$, it will lead to duplicate calculations.\n\nLet's take an example to illustrate. For the following array:\n\nThe element at index $3$ is $2$, the first element to its left that is less than $2$ is at index $0$. If we find the first element to its right that is less than $2$, we get index $7$. That is, the subarray interval is $(0, 7)$. Note that this is an open interval.\n\n```\n0 4 3 2 5 3 2 1\n* ^ *\n```\n\nIn the same way, we can find the subarray interval for the element at index $6$, and find that its subarray interval is also $(0, 7)$. That is, the subarray intervals for the elements at index $3$ and index $6$ are the same. This leads to duplicate calculations.\n\n```\n0 4 3 2 5 3 2 1\n* ^ *\n```\n\nIf we find the first element to its right that is less than or equal to its value, there will be no duplication, because the subarray interval for the element at index $3$ becomes $(0, 6)$, and the subarray interval for the element at index $6$ is $(0, 7)$, which are not the same.\n\nBack to this problem, we just need to traverse the array, for each element $arr[i]$, use a monotonic stack to find the first position $left[i]$ to its left that is less than $arr[i]$, and the first position $right[i]$ to its right that is less than or equal to $arr[i]$. The number of subarrays for which $arr[i]$ is the minimum is $(i - left[i]) \\times (right[i] - i)$, then multiply by $arr[i]$, and finally sum these up.\n\nBe aware of data overflow and modulo operations.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $arr$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 908, "explanations": { "1": "According to the problem description, we can subtract $k$ from the maximum value in the array and add $k$ to the minimum value in the array, which can reduce the difference between the maximum and minimum values in the array.\n\nTherefore, the final answer is the larger value between $\\max(\\textit{nums}) - \\min(\\textit{nums}) - 2 \\times k$ and $0$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 909, "explanations": { "1": "We can use the Breadth-First Search (BFS) method, starting from the starting point, moving forward 1 to 6 steps each time, and then checking for snakes or ladders. If there are any, move to the destination of the snake or ladder; otherwise, move to the next square.\n\nSpecifically, we use a queue $\\textit{q}$ to store the current reachable square numbers, initially putting number $1$ into the queue. At the same time, we use a set $\\textit{vis}$ to record the squares that have been reached to avoid revisiting them, initially adding number $1$ to the set $\\textit{vis}$.\n\nIn each operation, we take out the square number $x$ at the front of the queue. If $x$ is the endpoint, we can return the current number of steps. Otherwise, we move $x$ forward 1 to 6 steps, setting the new number as $y$. If $y$ falls outside the board, we skip it directly. Otherwise, we need to find the row and column corresponding to $y$. Since the row numbers decrease from bottom to top, and the column numbers depend on the parity of the row, we need to perform some calculations to get the row and column corresponding to $y$.\n\nIf the square corresponding to $y$ has a snake or ladder, we need to move to the destination of the snake or ladder, denoted as $z$. If $z$ has not been visited, we add $z$ to the queue and set, allowing us to continue the breadth-first search.\n\nIf we ultimately cannot reach the endpoint, we return $-1$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ is the length of the side of the board." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 910, "explanations": { "1": "According to the problem requirements, we need to find the minimum difference between the maximum and minimum values in the array. Each element can be increased or decreased by $k$, so we can divide the elements in the array into two parts, one part increased by $k$ and the other part decreased by $k$. Therefore, we should decrease the larger values in the array by $k$ and increase the smaller values by $k$ to ensure the minimum difference between the maximum and minimum values.\n\nTherefore, we can first sort the array, then enumerate each element in the array, divide it into two parts, one part increased by $k$ and the other part decreased by $k$, and calculate the difference between the maximum and minimum values. Finally, take the minimum value among all differences.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 911, "explanations": { "1": "We can record the winner at each moment during initialization, and then use binary search to find the largest moment less than or equal to $t$ during the query, and return the winner at that moment.\n\nDuring initialization, we use a counter $cnt$ to record the votes of each candidate, and a variable $cur$ to record the current leading candidate. Then we traverse each moment, update $cnt$ and $cur$, and record the winner at each moment.\n\nDuring the query, we use binary search to find the largest moment less than or equal to $t$, and return the winner at that moment.\n\nIn terms of time complexity, during initialization, we need $O(n)$ time, and during the query, we need $O(\\log n)$ time. The space complexity is $O(n)$." }, "is_english": true, "time_complexity": null, "space_complexity": "O(n)" }, { "problem_id": 912, "explanations": { "1": "快速排序是一种高效的排序算法。它的基本思想是通过一趟排序将待排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。\n\n时间复杂度 $O(n \\times \\log n)$,空间复杂度 $O(\\log n)$。其中 $n$ 为数组长度。", "2": "归并排序是一种分治算法,其思想是将待排序的数据序列不断地折半拆分,直到每个数据块只有一个元素为止,然后再按照拆分的顺序将每个数据块两两合并,在合并的过程中进行排序,最终得到一个有序的数据序列。\n\n归并排序是一种稳定的排序算法,时间复杂度为 $O(n \\times \\log n)$,空间复杂度为 $O(n)$。其中 $n$ 为数组长度。", "3": "" }, "is_english": false, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 913, "explanations": { "1": "According to the problem description, the state of the game is determined by the position of the mouse, the position of the cat, and the player who is moving. The outcome can be directly determined in the following situations:\n\n- When the positions of the cat and the mouse are the same, the cat wins. This is a winning state for the cat and a losing state for the mouse.\n- When the mouse is at the hole, the mouse wins. This is a winning state for the mouse and a losing state for the cat.\n\nTo determine the result of the initial state, we need to traverse all states starting from the boundary states. Each state includes the position of the mouse, the position of the cat, and the player who is moving. Based on the current state, we can determine all possible states from the previous round. The player who moved in the previous round is the opposite of the player who is moving in the current state, and the positions of the players in the previous round are different from their positions in the current state.\n\nWe use the tuple $(m, c, t)$ to represent the current state and $(pm, pc, pt)$ to represent a possible state from the previous round. The possible states from the previous round are:\n\n- If the player moving in the current round is the mouse, then the player moving in the previous round is the cat. The position of the mouse in the previous round is the same as the current position of the mouse, and the position of the cat in the previous round is any adjacent node of the current position of the cat.\n- If the player moving in the current round is the cat, then the player moving in the previous round is the mouse. The position of the cat in the previous round is the same as the current position of the cat, and the position of the mouse in the previous round is any adjacent node of the current position of the mouse.\n\nInitially, all states except the boundary states are unknown. Starting from the boundary states, for each state, we determine all possible states from the previous round and update the results. The update logic is as follows:\n\n1. If the player moving in the previous round is the same as the winner in the current round, then the player moving in the previous round can reach the current state and win. We directly update the state of the previous round to the winner of the current round.\n2. If the player moving in the previous round is different from the winner in the current round, and all states that the player moving in the previous round can reach are losing states for that player, then we update the state of the previous round to the winner of the current round.\n\nFor the second update logic, we need to record the degree of each state. Initially, the degree of each state represents the number of nodes the player moving in that state can move to, which is the number of adjacent nodes of the node where the player is located. If the player is the cat and the node is adjacent to the hole, the degree of that state is reduced by $1$.\n\nWhen all states have been updated, the result of the initial state is the final result.\n\nThe time complexity is $O(n^3)$, and the space complexity is $O(n^2)$. Here, $n$ is the number of nodes in the graph." }, "is_english": true, "time_complexity": "O(n^3)", "space_complexity": "O(n^2)" }, { "problem_id": 914, "explanations": { "1": "First, we use an array or hash table `cnt` to count the occurrence of each number. Only when $X$ is a divisor of the greatest common divisor of all `cnt[i]`, can it satisfy the problem's requirement.\n\nTherefore, we find the greatest common divisor $g$ of the occurrence of all numbers, and then check whether it is greater than or equal to $2$.\n\nThe time complexity is $O(n \\times \\log M)$, and the space complexity is $O(n + \\log M)$. Where $n$ and $M$ are the length of the array `deck` and the maximum value in the array `deck`, respectively." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(n + \\log M)" }, { "problem_id": 915, "explanations": { "1": "To satisfy the requirements of the problem after partitioning into two subarrays, we need to ensure that the \"maximum value of the array prefix\" is less than or equal to the \"minimum value of the array suffix\".\n\nTherefore, we can first preprocess the minimum value of the array suffix and record it in the `mi` array.\n\nThen, we traverse the array from front to back, maintaining the maximum value `mx` of the array prefix. When we traverse to a certain position, if the maximum value of the array prefix is less than or equal to the minimum value of the array suffix, then the current position is the dividing point of the partition, and we can return it directly.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array `nums`." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 916, "explanations": { "1": "Traverse each word `b` in `words2`, count the maximum occurrence of each letter, and record it as `cnt`.\n\nThen traverse each word `a` in `words1`, count the occurrence of each letter, and record it as `t`. If the occurrence of each letter in `cnt` is not greater than the occurrence in `t`, then `a` is a universal word, and add it to the answer.\n\nThe time complexity is $O(L)$, where $L$ is the sum of the lengths of all words in `words1` and `words2`." }, "is_english": true, "time_complexity": "O(L)", "space_complexity": null }, { "problem_id": 917, "explanations": { "1": "We use two pointers $i$ and $j$ to point to the head and tail of the string respectively. When $i < j$, we continuously move $i$ and $j$ until $i$ points to an English letter and $j$ points to an English letter, then we swap $s[i]$ and $s[j]$. Finally, we return the string.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the string." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 918, "explanations": { "1": "The maximum sum of a circular subarray can be divided into two cases:\n\n- Case 1: The subarray with the maximum sum does not include the circular part, which is the ordinary maximum subarray sum;\n- Case 2: The subarray with the maximum sum includes the circular part, which can be transformed into: the total sum of the array minus the minimum subarray sum.\n\nTherefore, we maintain the following variables:\n\n- The minimum prefix sum $pmi$, initially $0$;\n- The maximum prefix sum $pmx$, initially $-\\infty$;\n- The prefix sum $s$, initially $0$;\n- The minimum subarray sum $smi$, initially $\\infty$;\n- The answer $ans$, initially $-\\infty$.\n\nNext, we only need to traverse the array $nums$. For the current element $x$ we are traversing, we perform the following update operations:\n\n- Update the prefix sum $s = s + x$;\n- Update the answer $ans = \\max(ans, s - pmi)$, which is the answer for Case 1 (the prefix sum $s$ minus the minimum prefix sum $pmi$ can give the maximum subarray sum);\n- Update $smi = \\min(smi, s - pmx)$, which is the minimum subarray sum for Case 2;\n- Update $pmi = \\min(pmi, s)$, which is the minimum prefix sum;\n- Update $pmx = \\max(pmx, s)$, which is the maximum prefix sum.\n\nAfter the traversal, we return the maximum value of $ans$ and $s - smi$ as the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 919, "explanations": { "1": "We can use an array $tree$ to store all nodes of the complete binary tree. During initialization, we use a queue $q$ to perform level-order traversal of the given tree and store all nodes into the array $tree$.\n\nWhen inserting a node, we can find the parent node $p$ of the new node through the array $tree$. Then we create a new node $node$, insert it into the array $tree$, and make $node$ as the left child or right child of $p$. Finally, we return the value of $p$.\n\nWhen getting the root node, we directly return the first element of the array $tree$.\n\nIn terms of time complexity, it takes $O(n)$ time for initialization, and the time complexity for inserting a node and getting the root node are both $O(1)$. The space complexity is $O(n)$, where $n$ is the number of nodes in the tree." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(n)" }, { "problem_id": 920, "explanations": { "1": "We define $f[i][j]$ to be the number of playlists that can be made from $i$ songs with exactly $j$ different songs. We have $f[0][0] = 1$ and the answer is $f[goal][n]$.\n\nFor $f[i][j]$, we can choose a song that we have not listened before, so the previous state is $f[i - 1][j - 1]$, and there are $n - (j - 1) = n - j + 1$ options. Thus, $f[i][j] += f[i - 1][j - 1] \\times (n - j + 1)$. We can also choose a song that we have listened before, so the previous state is $f[i - 1][j]$, and there are $j - k$ options. Thus, $f[i][j] += f[i - 1][j] \\times (j - k)$, where $j \\geq k$.\n\nTherefore, we have the transition equation:\n\n$$\nf[i][j] = \\begin{cases}\n1 & i = 0, j = 0 \\\\\nf[i - 1][j - 1] \\times (n - j + 1) + f[i - 1][j] \\times (j - k) & i \\geq 1, j \\geq 1\n\\end{cases}\n$$\n\nThe final answer is $f[goal][n]$.\n\nThe time complexity is $O(goal \\times n)$, and the space complexity is $O(goal \\times n)$. Here, $goal$ and $n$ are the parameters given in the problem.", "2": "We notice that $f[i][j]$ is only related to $f[i - 1][j - 1]$ and $f[i - 1][j]$. Therefore, we can use a rolling array to optimize the space complexity, reducing the space complexity to $O(n)$." }, "is_english": true, "time_complexity": "O(goal \\times n)", "space_complexity": "O(goal \\times n)" }, { "problem_id": 921, "explanations": { "1": "This problem is a classic parenthesis matching problem, which can be solved using \"Greedy + Stack\".\n\nIterate through each character $c$ in the string $s$:\n\n- If $c$ is a left parenthesis, directly push $c$ into the stack;\n- If $c$ is a right parenthesis, at this point if the stack is not empty, and the top element of the stack is a left parenthesis, then pop the top element of the stack, indicating a successful match; otherwise, push $c$ into the stack.\n\nAfter the iteration ends, the number of remaining elements in the stack is the number of parentheses that need to be added.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the string $s$.", "2": "Solution 1 uses a stack to implement parenthesis matching, but we can also directly implement it through counting.\n\nDefine a variable `cnt` to represent the current number of left parentheses to be matched, and a variable `ans` to record the answer. Initially, both variables are set to $0$.\n\nIterate through each character $c$ in the string $s$:\n\n- If $c$ is a left parenthesis, increase the value of `cnt` by $1$;\n- If $c$ is a right parenthesis, at this point if $cnt > 0$, it means that there are left parentheses that can be matched, so decrease the value of `cnt` by $1$; otherwise, it means that the current right parenthesis cannot be matched, so increase the value of `ans` by $1$.\n\nAfter the iteration ends, add the value of `cnt` to `ans`, which is the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$, where $n$ is the length of the string $s$.", "3": "" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 922, "explanations": { "1": "We use two pointers $i$ and $j$ to point to even and odd indices, respectively. Initially, $i = 0$ and $j = 1$.\n\nWhen $i$ points to an even index, if $\\textit{nums}[i]$ is odd, we need to find an odd index $j$ such that $\\textit{nums}[j]$ is even, and then swap $\\textit{nums}[i]$ and $\\textit{nums}[j]$. Continue traversing until $i$ reaches the end of the array.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 923, "explanations": { "1": "We can use a hash table or an array $cnt$ of length $101$ to count the occurrence of each element in the array $arr$.\n\nThen, we enumerate each element $arr[j]$ in the array $arr$, first subtract one from $cnt[arr[j]]$, and then enumerate the elements $arr[i]$ before $arr[j]$, calculate $c = target - arr[i] - arr[j]$. If $c$ is in the range of $[0, 100]$, then the answer is increased by $cnt[c]$, and finally return the answer.\n\nNote that the answer may exceed ${10}^9 + 7$, so take the modulus after each addition operation.\n\nThe time complexity is $O(n^2)$, where $n$ is the length of the array $arr$. The space complexity is $O(C)$, where $C$ is the maximum value of the elements in the array $arr$, in this problem $C = 100$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(C)" }, { "problem_id": 924, "explanations": { "1": "According to the problem description, if there are several nodes in the same connected component initially, there can be three situations:\n\n1. None of these nodes are infected.\n2. Only one node among these nodes is infected.\n3. Multiple nodes among these nodes are infected.\n\nWhat we need to consider is to minimize the number of infected nodes left after removing a certain infected node.\n\nFor situation 1, there are no infected nodes, so we don't need to consider it; for situation 2, only one node is infected, so after removing this node, the other nodes in this connected component will not be infected; for situation 3, multiple nodes are infected, so after removing any infected node, the other nodes in this connected component will still be infected. Therefore, we only need to consider situation 2.\n\nWe use a union find set $uf$ to maintain the connectivity of nodes, a variable $ans$ to record the answer, and a variable $mx$ to record the maximum number of infections that can be reduced currently. Initially, $ans = n$, $mx = 0$.\n\nThen we traverse the array $initial$, use a hash table or an array of length $n$ named $cnt$ to count the number of infected nodes in each connected component.\n\nNext, we traverse the array $initial$ again. For each node $x$, we find the root node $root$ of its connected component. If there is only one infected node in this connected component, i.e., $cnt[root] = 1$, we update the answer. The update condition is that the number of nodes $sz$ in this connected component is greater than $mx$ or $sz$ equals $mx$ and the value of $x$ is less than $ans$.\n\nFinally, if $ans$ has not been updated, it means that there are multiple infected nodes in all connected components, so we return the minimum value in $initial$, otherwise, we return $ans$.\n\nThe time complexity is $O(n^2 \\times \\alpha(n))$, and the space complexity is $O(n)$. Where $n$ is the number of nodes, and $\\alpha(n)$ is the inverse of the Ackermann function." }, "is_english": true, "time_complexity": "O(n^2 \\times \\alpha(n))", "space_complexity": "O(n)" }, { "problem_id": 925, "explanations": { "1": "We use two pointers $i$ and $j$ to point to the first character of the strings `typed` and `name` respectively, and then start traversing. If `typed[j]` is not equal to `name[i]`, it means the two strings do not match, and we directly return `False`. Otherwise, we find the next position of the continuous identical characters, denoted as $x$ and $y$ respectively. If $x - i > y - j$, it means the number of characters in `typed` is less than the number of characters in `name`, and we directly return `False`. Otherwise, we update $i$ and $j$ to $x$ and $y$ respectively, continue traversing, until $i$ and $j$ have traversed `name` and `typed` respectively, and return `True`.\n\nThe time complexity is $O(m + n)$, where $m$ and $n$ are the lengths of the strings `name` and `typed` respectively. The space complexity is $O(1)`." }, "is_english": true, "time_complexity": "O(m + n)", "space_complexity": "O(1)" }, { "problem_id": 926, "explanations": { "1": "First, we count the number of '0's in string $s$, denoted as $tot$. We define a variable $ans$ for the answer, initially set $ans = tot$, which represents the number of flips to change all '0's to '1's.\n\nThen, we can enumerate each position $i$, change all '1's to the left of position $i$ (including $i$) to '0', and change all '0's to the right of position $i$ to '1'. We calculate the number of flips in this case, which is $i + 1 - cur + tot - cur$, where $cur$ represents the number of '0's to the left of position $i$ (including $i$). We update the answer $ans = \\min(ans, i + 1 - cur + tot - cur)$.\n\nFinally, return the answer $ans$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 927, "explanations": { "1": "We denote the length of the array as $n$, and the number of '1's in the array as $cnt$.\n\nObviously, $cnt$ must be a multiple of $3$, otherwise the array cannot be divided into three equal parts, and we can return $[-1, -1]$ in advance. If $cnt$ is $0$, it means that all elements in the array are '0', and we can directly return $[0, n - 1]$.\n\nWe divide $cnt$ by $3$ to get the number of '1's in each part, and then find the position of the first '1' in each part in the array `arr` (refer to the $find(x)$ function in the following code), denoted as $i$, $j$, $k$ respectively.\n\n```bash\n0 1 1 0 0 0 1 1 0 0 0 0 0 1 1 0 0\n ^ ^ ^\n i j k\n```\n\nThen we start from $i$, $j$, $k$ and traverse each part at the same time, check whether the corresponding values of the three parts are equal. If they are, continue to traverse until $k$ reaches the end of `arr`.\n\n```bash\n0 1 1 0 0 0 1 1 0 0 0 0 0 1 1 0 0\n ^ ^ ^\n i j k\n```\n\nAt the end of the traversal, if $k=n$, it means that it satisfies the three equal parts, and we return $[i - 1, j]$ as the answer, otherwise return $[-1, -1]$.\n\nThe time complexity is $O(n)$, where $n$ is the length of `arr`. The space complexity is $O(1)$.\n\nSimilar problems:\n\n- [1573. Number of Ways to Split a String](https://github.com/doocs/leetcode/blob/main/solution/1500-1599/1573.Number%20of%20Ways%20to%20Split%20a%20String/README_EN.md)" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 928, "explanations": { "1": "We can use the union-find data structure to merge all nodes that are not in $initial$ and satisfy $graph[i][j] = 1$.\n\nNext, we create a hash table $g$, where $g[i]$ represents the root node of the connected component that is connected to node $i$. We also need a counter $cnt$ to count how many initial nodes each root node is infected by.\n\nFor each initially infected node $i$, we traverse all nodes $j$ connected to node $i$. If node $j$ is not in $initial$, we add the root node of node $j$ to the set $g[i]$. At the same time, we count how many initial nodes each root node is infected by and save the result in the counter $cnt$.\n\nThen, we use a variable $ans$ to record the answer, and $mx$ to record the maximum number of infected nodes that can be reduced. Initially, $ans = 0$, $mx = -1$.\n\nWe traverse all initially infected nodes. For each node $i$, we traverse all root nodes in $g[i]$. If a root node is only infected by one initial node, we add the size of the connected component where the root node is located to $t$. If $t > mx$ or $t = mx$ and $i < ans$, we update $ans = i$, $mx = t$.\n\nFinally, we return $ans$.\n\nThe time complexity is $O(n^2 \\times \\alpha(n))$, and the space complexity is $O(n^2)$. Where $n$ is the number of nodes, and $\\alpha(n)$ is the inverse Ackermann function." }, "is_english": true, "time_complexity": "O(n^2 \\times \\alpha(n))", "space_complexity": "O(n^2)" }, { "problem_id": 929, "explanations": { "1": "We can use a hash table $s$ to store all unique email addresses. Then, we traverse the array $\\textit{emails}$. For each email address, we split it into the local part and the domain part. We process the local part by removing all dots and ignoring characters after a plus sign. Finally, we concatenate the processed local part with the domain part and add it to the hash table $s$.\n\nIn the end, we return the size of the hash table $s$.\n\nThe time complexity is $O(L)$, and the space complexity is $O(L)$, where $L$ is the total length of all email addresses." }, "is_english": true, "time_complexity": "O(L)", "space_complexity": "O(L)" }, { "problem_id": 930, "explanations": { "1": "我们可以用数组或哈希表 $cnt$ 记录每个前缀和出现的次数,其中 $cnt[i]$ 表示前缀和为 $i$ 的子数组个数。初始时 $cnt[0] = 1$。\n\n接下来我们遍历数组 `nums`,用变量 $s$ 维护当前的前缀和,对于每个 $s$,我们可以计算出 $s - goal$ 出现的次数,即为以当前位置结尾的满足条件的子数组个数,累加到答案中。然后我们将 $s$ 的计数值加 $1$。\n\n最终的答案即为满足条件的子数组个数。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 `nums` 的长度。", "2": "" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 931, "explanations": { "1": "我们定义 $f[i][j]$ 表示从第一行开始下降,到达第 $i$ 行第 $j$ 列的最小路径和。那么我们可以得到这样的动态规划转移方程:\n\n$$\nf[i][j] = matrix[i][j] + \\min \\left\\{ \\begin{aligned} & f[i - 1][j - 1], & j > 0 \\\\ & f[i - 1][j], & 0 \\leq j < n \\\\ & f[i - 1][j + 1], & j + 1 < n \\end{aligned} \\right.\n$$\n\n最终的答案即为 $\\min \\limits_{0 \\leq j < n} f[n - 1][j]$。\n\n时间复杂度 $O(n^2)$,空间复杂度 $O(n^2)$。\n\n我们注意到,状态 $f[i][j]$ 只与上一行的状态有关,因此我们可以使用滚动数组的方式,去掉第一维的状态,将空间复杂度优化到 $O(n)$。" }, "is_english": false, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 932, "explanations": { "1": "根据题意,漂亮数组 $A$ 需要满足对于任意 $i 基于一个性质,将漂亮数组中的每个元素 $x_i$ 变换为 $kx_i+b$,得到的数组仍然是漂亮数组。\n\n将这两个漂亮数组合并在一起,由于满足一奇一偶,那么合并后的数组也是漂亮数组,从而得到了答案。\n\n时间复杂度 $O(nlogn)$。" }, "is_english": false, "time_complexity": "O(nlogn)", "space_complexity": null }, { "problem_id": 933, "explanations": { "1": "由题得知,`t` 是**严格递增**的,当一个元素不满足 `[t - 3000, t]` 条件时,在后续的请求当中,它也不可能满足。\n\n对此,需要将其从记录容器中移除,减少无意义的比较。\n\n可以使用队列。每次将 `t` 进入队尾,同时从队头开始,依次移除小于 `t - 3000` 的元素。然后返回队列的大小(`q.size()`)即可。", "2": "`t` 严格单调递增,非常适合用二分查找来定位 `[t-3000, t]` 的左右边界。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 934, "explanations": { "1": "题目求解的是最小翻转次数,使得两个岛屿相连,实际上等价于求解两个岛屿之间的最短距离。\n\n因此,我们可以先通过 DFS 将其中一个岛屿的所有点找出来,放到一个队列 $q$ 中。然后通过 BFS 一层层向外扩展,直至碰到另一个岛屿,此时将当前扩展的层数作为答案返回即可。\n\n在 DFS 和 BFS 搜索的过程中,我们直接将已经访问过的点标记为 $2$,这样就不会重复访问。\n\n时间复杂度 $O(n^2)$,空间复杂度 $O(n^2)$。其中 $n$ 为矩阵的行数或列数。" }, "is_english": false, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 935, "explanations": { "1": "According to the problem description, we need to calculate the number of different phone numbers of length $n$. Each digit can only follow certain fixed digits, which we can list as follows:\n\n| Current Digit | Previous Digits |\n| ------------- | --------------- |\n| 0 | 4, 6 |\n| 1 | 6, 8 |\n| 2 | 7, 9 |\n| 3 | 4, 8 |\n| 4 | 0, 3, 9 |\n| 5 | |\n| 6 | 0, 1, 7 |\n| 7 | 2, 6 |\n| 8 | 1, 3 |\n| 9 | 2, 4 |\n\nWe can use a recurrence approach to calculate the number of different phone numbers of length $n$. Let $f[i]$ represent the number of different phone numbers of length $i$. Initially, $f[1] = 1$. For phone numbers of length $i$, we can calculate them based on phone numbers of length $i - 1$. Therefore, we can derive the recurrence relations:\n\n$$\n\\begin{aligned}\ng[0] & = f[4] + f[6] \\\\\ng[1] & = f[6] + f[8] \\\\\ng[2] & = f[7] + f[9] \\\\\ng[3] & = f[4] + f[8] \\\\\ng[4] & = f[0] + f[3] + f[9] \\\\\ng[6] & = f[0] + f[1] + f[7] \\\\\ng[7] & = f[2] + f[6] \\\\\ng[8] & = f[1] + f[3] \\\\\ng[9] & = f[2] + f[4]\n\\end{aligned}\n$$\n\nThen, we update $f$ to $g$ and continue calculating the phone numbers of the next length until we calculate the number of phone numbers of length $n$.\n\nFinally, we sum all the elements in $f$ and take the result modulo $10^9 + 7$ to get the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the phone number. The space complexity is $O(|\\Sigma|)$, where $\\Sigma$ is the set of digits, and in this problem $|\\Sigma| = 10$.", "2": "Let's denote $T(n)$ as a $1 \\times 10$ matrix $\\begin{bmatrix} F_0 & F_1 & F_2 \\cdots F_9 \\end{bmatrix}$, where $F_i$ represents the number of phone numbers ending with digit $i$. We want to derive $T(n)$ from $T(n - 1)$. In other words, we need a matrix $\\textit{base}$ such that $T(n - 1) \\times \\textit{base} = T(n)$, i.e.:\n\n$$\n\\begin{bmatrix}\nF_0 & F_1 & F_2 \\cdots F_9\n\\end{bmatrix} \\times \\textit{base} = \\begin{bmatrix} F_0' & F_1' & F_2' \\cdots F_9' \\end{bmatrix}\n$$\n\nSince $F_i' = \\sum_{j} F_j$, where $j$ is the previous digit of $i$, the first column of the matrix $\\textit{base}$ is:\n\n$$\n\\begin{bmatrix}\n0 \\\\\n0 \\\\\n0 \\\\\n0 \\\\\n1 \\\\\n0 \\\\\n1 \\\\\n0 \\\\\n0 \\\\\n0\n\\end{bmatrix}\n$$\n\nSimilarly, we can derive the entire matrix $\\textit{base}$ as follows:\n\n$$\n\\begin{bmatrix}\n0 & 0 & 0 & 0 & 1 & 0 & 1 & 0 & 0 & 0 \\\\\n0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 1 & 0 \\\\\n0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 1 \\\\\n0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 1 & 0 \\\\\n1 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 1 \\\\\n0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\\\\n1 & 1 & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 \\\\\n0 & 0 & 1 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\\\\n0 & 1 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\\\\n0 & 0 & 1 & 0 & 1 & 0 & 0 & 0 & 0 & 0\n\\end{bmatrix}\n$$\n\nWe define the initial matrix $res = \\begin{bmatrix} 1 & 1 & 1 \\cdots 1 \\end{bmatrix}$, and multiply it by the matrix $\\textit{base}$ raised to the power of $n - 1$ to obtain $T(n)$. Finally, we sum all elements in $T(n)$ and take the result modulo $10^9 + 7$ to get the answer. The matrix $\\textit{base}^{n - 1}$ can be computed using matrix exponentiation, which has a time complexity of $O(\\log n)$.\n\nThe time complexity is $O(\\log n)$, and the space complexity is $O(|\\Sigma|^2)$, where $\\Sigma$ is the set of digits, and in this problem $|\\Sigma| = 10$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 936, "explanations": { "1": "If we operate on the sequence in a forward manner, it would be quite complicated because subsequent operations would overwrite previous ones. Therefore, we consider operating on the sequence in a reverse manner, i.e., starting from the target string $target$ and considering the process of turning $target$ into $?????$.\n\nLet's denote the length of the stamp as $m$ and the length of the target string as $n$. If we operate on the target string with the stamp, there are $n-m+1$ starting positions where the stamp can be placed. We can enumerate these $n-m+1$ starting positions and use a method similar to topological sorting to operate in reverse.\n\nFirstly, we clarify that each starting position corresponds to a window of length $m$.\n\nNext, we define the following data structures or variables:\n\n- In-degree array $indeg$, where $indeg[i]$ represents how many characters in the $i$-th window are different from the characters in the stamp. Initially, $indeg[i]=m$. If $indeg[i]=0$, it means that all characters in the $i$-th window are the same as those in the stamp, and we can place the stamp in the $i$-th window.\n- Adjacency list $g$, where $g[i]$ represents the set of all windows with different characters from the stamp on the $i$-th position of the target string $target$.\n- Queue $q$, used to store the numbers of all windows with an in-degree of $0$.\n- Array $vis$, used to mark whether each position of the target string $target$ has been covered.\n- Array $ans$, used to store the answer.\n\nThen, we perform topological sorting. In each step of the topological sorting, we take out the window number $i$ at the head of the queue, and put $i$ into the answer array $ans$. Then, we enumerate each position $j$ in the stamp. If the $j$-th position in the $i$-th window has not been covered, we cover it and reduce the in-degree of all windows in the $indeg$ array that are the same as the $j$-th position in the $i$-th window by $1$. If the in-degree of a window becomes $0$, we put it into the queue $q$ for processing next time.\n\nAfter the topological sorting is over, if every position of the target string $target$ has been covered, then the answer array $ans$ stores the answer we are looking for. Otherwise, the target string $target$ cannot be covered, and we return an empty array.\n\nThe time complexity is $O(n \\times (n - m + 1))$, and the space complexity is $O(n \\times (n - m + 1))$. Here, $n$ and $m$ are the lengths of the target string $target$ and the stamp, respectively." }, "is_english": true, "time_complexity": "O(n \\times (n - m + 1))", "space_complexity": "O(n \\times (n - m + 1))" }, { "problem_id": 937, "explanations": { "1": "We can use a custom sorting method to divide the logs into two categories: letter logs and digit logs.\n\nFor letter logs, we need to sort them according to the problem requirements, i.e., first by content and then by identifier.\n\nFor digit logs, we only need to maintain their original relative order.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the number of logs." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 938, "explanations": { "1": "We design a function $dfs(root)$, which represents the sum of the values of all nodes in the subtree with $root$ as the root, and the values are within the range $[low, high]$. The answer is $dfs(root)$.\n\nThe execution logic of the function $dfs(root)$ is as follows:\n\n- If $root$ is null, return $0$.\n- If the value $x$ of $root$ is within the range $[low, high]$, then the initial answer of the function $dfs(root)$ is $x$, otherwise it is $0$.\n- If $x > low$, it means that there may be nodes in the left subtree of $root$ with values within the range $[low, high]$, so we need to recursively call $dfs(root.left)$ and add the result to the answer.\n- If $x < high$, it means that there may be nodes in the right subtree of $root$ with values within the range $[low, high]$, so we need to recursively call $dfs(root.right)$ and add the result to the answer.\n- Finally, return the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in the binary search tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 939, "explanations": { "1": "对于每个点,我们将其横坐标作为键,纵坐标作为值存入哈希表 $d$ 中。对于哈希表中的每个键,我们将其对应的纵坐标按照从小到大的顺序排序。\n\n然后我们从小到大枚举横坐标,对于每个横坐标,我们枚举其对应的纵坐标中的所有点对 $(y_1, y_2)$,其中 $y_1 \\lt y_2$。如果我们之前已经遇到过点对 $(y_1, y_2)$,那么就可以用当前的横坐标和之前的横坐标计算出一个矩形的面积。我们用哈希表 $pos$ 记录每个点对 $(y_1, y_2)$ 第一次出现的横坐标,这样我们就可以在常数时间内找到这个横坐标。\n\n最后,我们返回所有矩形的面积中的最小值。\n\n时间复杂度 $O(n^2 \\times \\log n)$,空间复杂度 $O(n^2)$。其中 $n$ 是点的数量。" }, "is_english": false, "time_complexity": "O(n^2 \\times \\log n)", "space_complexity": "O(n^2)" }, { "problem_id": 940, "explanations": { "1": "定义 $dp[i]$ 表示以 $s[i]$ 结尾的不同子序列的个数。由于 $s$ 中只包含小写字母,因此我们可以直接创建一个长度为 $26$ 的数组。初始时 $dp$ 所有元素均为 $0$。答案为 $\\sum_{i=0}^{25}dp[i]$。\n\n遍历字符串 $s$,对于每个位置的字符 $s[i]$,我们需要更新以 $s[i]$ 结尾的不同子序列的个数,此时 $dp[i]=\\sum_{j=0}^{25}dp[j]+1$。其中 $\\sum_{j=0}^{25}dp[j]$ 是此前我们已经计算出所有不同子序列的个数,而 $+1$ 是指 $s[i]$ 本身也可以作为一个子序列。\n\n最后,我们需要对 $dp$ 中的所有元素求和,再对 $10^9+7$ 取余,即为答案。\n\n时间复杂度 $O(n\\times C)$,其中 $n$ 是字符串 $s$ 的长度,而 $C$ 是字符集的大小,本题中 $C=26$。空间复杂度 $O(C)$。", "2": "在方法一的基础上,我们还可以维护当前 $dp$ 数组中所有元素的和 $ans$,这样我们每次更新 $dp[i]$ 时,只需要将 $dp[i]$ 加上 $ans-dp[i]+1$ 即可。\n\n时间复杂度 $O(n)$,空间复杂度 $O(C)$。\n\n相似题目:\n\n- [1987. 不同的好子序列数目](https://github.com/doocs/leetcode/blob/main/solution/1900-1999/1987.Number%20of%20Unique%20Good%20Subsequences/README.md)", "3": "" }, "is_english": false, "time_complexity": "O(n\\times C)", "space_complexity": "O(C)" }, { "problem_id": 941, "explanations": { "1": "First, we check if the length of the array is less than $3$. If it is, then it definitely is not a mountain array, so we return `false` directly.\n\nThen, we use a pointer $i$ to move from the left end of the array to the right, until we find a position $i$ such that $arr[i] > arr[i + 1]$. After that, we use a pointer $j$ to move from the right end of the array to the left, until we find a position $j$ such that $arr[j] > arr[j - 1]$. If the condition $i = j$ is satisfied, then it means that the array $arr$ is a mountain array.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 942, "explanations": { "1": "We can use two pointers `low` and `high` to represent the current minimum and maximum values, respectively. Then, we traverse the string `s`. If the current character is `I`, we add `low` to the result array, and increment `low` by 1; if the current character is `D`, we add `high` to the result array, and decrement `high` by 1.\n\nFinally, we add `low` to the result array and return the result array.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the string `s`." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 943, "explanations": { "1": "由于题目中字符串数组 `words` 的长度不超过 12,因此可以使用状态压缩的方法来表示字符串数组中的每个字符串是否被选中。\n\n定义 $dp[i][j]$ 表示字符串当前选中状态为 $i$,且最后一个选中的字符串为 $s[j]$ 时,字符串重叠部分的最大长度。其中 $i$ 的二进制表示中的第 $j$ 位为 $1$ 表示字符串 $s[j]$ 被选中,为 $0$ 表示字符串 $s[j]$ 未被选中。重叠部分达到最大时,最终得到的字符串最短。我们只要求出重叠部分的最大值以及对应的字符串 $s[j]$,记录每一步状态转移,就能够逆推出最终的字符串。\n\n字符串两两之间的重叠部分长度可以预处理出来,存储在二维数组 $g$ 中,其中 $g[i][j]$ 表示字符串 $s[i]$ 和字符串 $s[j]$ 之间的重叠部分长度。\n\n动态规划的状态转移方程如下:\n\n$$\ndp[i][j] = \\max_{k \\in \\{0, 1, \\cdots, n - 1\\}} \\{dp[i - 2^j][k] + g[k][j]\\}\n$$\n\n时间复杂度 $O(2^n \\times n^2)$,空间复杂度 $O(2^n \\times n)$。其中 $n$ 为字符串数组 `words` 的长度。" }, "is_english": false, "time_complexity": "O(2^n \\times n^2)", "space_complexity": "O(2^n \\times n)" }, { "problem_id": 944, "explanations": { "1": "We denote the number of rows in the string array $\\textit{strs}$ as $n$, and the number of columns as $m$.\n\nWe traverse each column, starting from the second row, and compare the character of the current row with that of the previous row column by column. If the character of the current row is less than that of the previous row, it indicates that the current column is not arranged in non-strictly increasing lexicographical order, and we need to delete it, incrementing the result by one, then break out of the inner loop.\n\nFinally, we return the result.\n\nThe time complexity is $O(L)$, where $L$ is the total length of the strings in the array $\\textit{strs}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(L)", "space_complexity": "O(1)" }, { "problem_id": 945, "explanations": { "1": "First, we sort the array $\\textit{nums}$, and use a variable $\\textit{y}$ to record the current maximum value, initially $\\textit{y} = -1$.\n\nThen, we iterate through the array $\\textit{nums}$. For each element $x$, we update $y$ to $\\max(y + 1, x)$, and accumulate the operation count $y - x$ into the result.\n\nAfter completing the iteration, we return the result.\n\nThe time complexity is $O(n \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array $\\textit{nums}$.", "2": "According to the problem description, the maximum value of the result array $m = \\max(\\textit{nums}) + \\textit{len}(\\textit{nums})$. We can use a counting array $\\textit{cnt}$ to record the occurrence count of each element.\n\nThen, we iterate from $0$ to $m - 1$. For each element $i$, if its occurrence count $\\textit{cnt}[i]$ is greater than $1$, then we add $\\textit{cnt}[i] - 1$ elements to $i + 1$, and accumulate the operation count into the result.\n\nAfter completing the iteration, we return the result.\n\nThe time complexity is $O(m)$, and the space complexity is $O(m)$. Here, $m$ is the length of the array $\\textit{nums}$ plus the maximum value in the array." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 946, "explanations": { "1": "We iterate through the $\\textit{pushed}$ array. For the current element $x$ being iterated, we push it into the stack $\\textit{stk}$. Then, we check if the top element of the stack is equal to the next element to be popped in the $\\textit{popped}$ array. If they are equal, we pop the top element from the stack and increment the index $i$ of the next element to be popped in the $\\textit{popped}$ array. Finally, if all elements can be popped in the order specified by the $\\textit{popped}$ array, return $\\textit{true}$; otherwise, return $\\textit{false}$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the $\\textit{pushed}$ array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 947, "explanations": { "1": "We can use a union-find data structure to maintain the relationships between stones. If two stones are in the same row or column, we consider them to be connected and use the union-find to link them together. In the end, we count how many connected components there are in the union-find, which corresponds to the number of stones that can remain. Therefore, the total number of stones that can be removed is the total number of stones minus the number of stones that can remain. We can also record the number of successful unions during the merge process, which equals the number of stones that can be removed.\n\nThe time complexity is $O(n^2 \\times \\alpha(n))$, and the space complexity is $O(n)$. Here, $n$ is the number of stones.", "2": "We can add an offset to the y-coordinates of the stones, allowing us to unify the x-coordinates and y-coordinates. Then, we use a union-find data structure to maintain the relationship between x-coordinates and y-coordinates.\n\nWe iterate through each stone, merging its x-coordinate with its y-coordinate.\n\nFinally, we iterate through all the stones again, putting the root node of each stone's x-coordinate into a set. The number of elements in this set represents the number of stones that can remain. Therefore, the total number of stones that can be removed is the total number of stones minus the number of stones that can remain.\n\nThe time complexity is $O(n \\times \\alpha(m))$, and the space complexity is $O(m)$. Here, $n$ and $m$ represent the number of stones and the maximum value of the coordinates, respectively.", "3": "" }, "is_english": true, "time_complexity": "O(n^2 \\times \\alpha(n))", "space_complexity": "O(n)" }, { "problem_id": 948, "explanations": { "1": "There are two ways to use tokens: one is to consume energy to gain points, and the other is to consume points to gain energy. Obviously, we should consume as little energy as possible to gain as many points as possible.\n\nTherefore, we can sort the tokens by the amount of energy they consume, and then use two pointers: one moving from left to right and the other from right to left. In each iteration, we try to consume energy to gain points as much as possible, and then update the maximum score. If the current energy is not enough to consume the current token, we try to consume the current token using points. If the points are not enough to consume the current token, we stop the iteration.\n\nThe time complexity is $O(n \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the number of tokens." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 949, "explanations": { "1": "我们可以枚举所有的 4 个数字的排列,然后判断每个排列是否满足题目要求,如果满足则更新答案。\n\n时间复杂度 $O(4^3)$,空间复杂度 $O(1)$。", "2": "" }, "is_english": false, "time_complexity": "O(4^3)", "space_complexity": "O(1)" }, { "problem_id": 950, "explanations": { "1": "根据题目描述,我们知道,数组 `deck` 逆序排列后的序列就是最终的结果。我们可以从最终结果入手,逆向推导出卡片顺序。\n\n遍历逆序排列后的数组 `deck`,先判断队列是否为空,若不为空,则将队尾元素移动到队首,然后将当前元素入队(题目中的逆过程)。若为空,则直接将当前元素入队。\n\n最后,将队列中的元素依次出队,即可得到最终的结果。\n\n时间复杂度 $O(n\\log n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 `deck` 的长度。" }, "is_english": false, "time_complexity": "O(n\\log n)", "space_complexity": "O(n)" }, { "problem_id": 951, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 952, "explanations": { "1": "利用“试除法”,对 $nums$ 中的每个数 $v$ 分解因数,然后将每个因数 $i$ 与 $v$ 合并,$v / i$ 与 $v$ 合并。此过程用并查集来维护连通分量。\n\n最后,遍历 $nums$ 中每个数 $v$,找出所在的连通分量,出现次数最多的连通分量就是所求的答案。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 953, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 954, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 955, "explanations": { "1": "When comparing strings in lexicographical order, we compare from left to right, and the first unequal character determines the ordering relationship between two strings. Therefore, we can traverse each column from left to right and determine whether the current column needs to be deleted.\n\nWe maintain a boolean array $\\textit{st}$ of length $n - 1$, indicating whether the ordering relationship between adjacent string pairs has been determined. If the ordering relationship has been determined, then any subsequent character comparison between these two strings will not change their ordering relationship.\n\nFor each column $j$, we traverse all adjacent string pairs $(\\textit{strs}[i], \\textit{strs}[i + 1])$:\n\n- If $\\textit{st}[i]$ is false and $\\textit{strs}[i][j] > \\textit{strs}[i + 1][j]$, it means the current column must be deleted. We increment the answer by one and skip processing this column;\n- Otherwise, if $\\textit{st}[i]$ is false and $\\textit{strs}[i][j] < \\textit{strs}[i + 1][j]$, it means the current column determines the ordering relationship between these two strings. We set $\\textit{st}[i]$ to true.\n\nAfter traversing all columns, the answer is the number of columns that need to be deleted.\n\nThis greedy strategy is optimal because lexicographical order is determined by the first different column from left to right. If the current column is not deleted and causes incorrect ordering for some string pair, then regardless of subsequent columns, this error cannot be corrected, so the current column must be deleted. If the current column is not deleted and does not cause incorrect ordering for any string pair, then keeping the current column will not affect the final lexicographical ordering relationship.\n\nThe time complexity is $O(n \\times m)$ and the space complexity is $O(n)$, where $n$ and $m$ are the length of the string array and the length of each string, respectively." }, "is_english": true, "time_complexity": "O(n \\times m)", "space_complexity": "O(n)" }, { "problem_id": 956, "explanations": { "1": "我们设计一个函数 $dfs(i, j)$,表示从第 $i$ 根钢筋开始,且当前高度差为 $j$ 时,两边的最大共同高度。那么答案就是 $dfs(0, 0)$。\n\n函数 $dfs(i, j)$ 的计算过程如下:\n\n如果 $i=n$,此时判断 $j$ 是否为 $0$,如果是则返回 $0$,否则返回 $-\\infty$。\n\n如果 $i \\lt n$,此时有三种情况:\n\n1. 不选择第 $i$ 根钢筋,此时 $dfs(i, j) = dfs(i+1, j)$;\n1. 选择第 $i$ 根钢筋,并且放置在原本高度较高的一边,那么 $dfs(i, j) = dfs(i+1, j+rods[i])$;\n1. 选择第 $i$ 根钢筋,并且放置在高度较低的一边,此时共同高度增加了 $\\min(j, rods[i])$,那么 $dfs(i, j) = dfs(i+1, |rods[i]-j|) + \\min(j, rods[i])$。\n\n我们取这三种情况下的最大值,即可得到 $dfs(i, j)$ 的值。\n\n为了避免重复计算,我们使用一个二维数组 $f$ 来记录已经计算过的 $dfs(i, j)$ 的值,调用 $dfs(i, j)$ 时,如果 $f[i][j]$ 已经被计算过,则直接返回 $f[i][j]$。否则,我们计算 $dfs(i, j)$ 的值,并将其存入 $f[i][j]$。\n\n时间复杂度 $O(n \\times S)$,空间复杂度 $O(n \\times S)$。其中 $n$ 和 $S$ 分别为 $rods$ 的长度和 $rods$ 中所有元素的和。", "2": "我们定义 $f[i][j]$ 表示前 $i$ 根钢筋,两边高度差为 $j$ 时的最大共同高度。初始时 $f[0][0]=0$,其余 $f[i][j]=-\\infty$。我们求出所有 $rods[i]$ 的和,记为 $s$,那么 $j$ 的取值范围为 $[0,..s]$。\n\n对于第 $i$ 根钢筋,我们可以不选择它,此时 $f[i][j]=f[i-1][j]$;也可以选择它,此时有三种情况:\n\n1. 放置在原本高度较高的一边,即满足 $j \\geq rods[i-1]$,此时 $f[i][j] = max(f[i][j], f[i-1][j-rods[i-1]])$;\n1. 放置在原本高度较低的一遍,如果满足 $j + rods[i-1] \\leq s$,此时 $f[i][j] = max(f[i][j], f[i-1][j+rods[i-1]] + rods[i-1])$;如果满足 $j \\lt rods[i-1]$,此时 $f[i][j] = max(f[i][j], f[i-1][rods[i-1]-j] + rods[i-1]-j)$。\n\n综上,我们可以得到状态转移方程:\n\n$$\n\\begin{aligned}\nf[i][j] &= f[i-1][j] \\\\\nf[i][j] &= max(f[i][j], f[i-1][j-rods[i-1]]) & \\textit{if } j \\geq rods[i-1] \\\\\nf[i][j] &= max(f[i][j], f[i-1][j+rods[i-1]] + rods[i-1]) & \\textit{if } j + rods[i-1] \\leq s \\\\\nf[i][j] &= max(f[i][j], f[i-1][rods[i-1]-j] + rods[i-1]-j) & \\textit{if } j \\lt rods[i-1]\n\\end{aligned}\n$$\n\n最终答案即为 $f[n][0]$。\n\n时间复杂度 $O(n \\times S)$,空间复杂度 $O(n \\times S)$。其中 $n$ 和 $S$ 分别为 $rods$ 的长度和 $rods$ 中所有元素的和。" }, "is_english": false, "time_complexity": "O(n \\times S)", "space_complexity": "O(n \\times S)" }, { "problem_id": 957, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 958, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 959, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 960, "explanations": { "1": "We define $f[i]$ as the length of the longest non-decreasing subsequence ending at column $i$. Initially, $f[i] = 1$, and the final answer is $n - \\max(f)$.\n\nTo compute $f[i]$, we iterate over all $j < i$. If for all strings $s$, we have $s[j] \\leq s[i]$, then we update $f[i]$ as follows:\n$$ f[i] = \\max(f[i], f[j] + 1) $$\n\nFinally, we return $n - \\max(f)$.\n\nThe time complexity is $O(n^2 \\times m)$, and the space complexity is $O(n)$, where $n$ is the length of each string in the array $\\textit{strs}$, and $m$ is the number of strings in the array." }, "is_english": true, "time_complexity": "O(n^2 \\times m)", "space_complexity": "O(n)" }, { "problem_id": 961, "explanations": { "1": "Since the array $\\textit{nums}$ has a total of $2n$ elements, with $n + 1$ distinct elements, and one element repeated $n$ times, this means the remaining $n$ elements in the array are all distinct.\n\nTherefore, we only need to iterate through the array $\\textit{nums}$ and use a hash table $s$ to record the elements we've encountered. When we encounter an element $x$, if $x$ already exists in the hash table $s$, it means $x$ is the repeated element, and we can directly return $x$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $\\textit{nums}$.", "2": "According to the problem description, half of the elements in the array $\\textit{nums}$ are the same. If we view the array as a circular arrangement, then there is at most $1$ other element between two identical elements.\n\nTherefore, we iterate through the array $\\textit{nums}$ starting from index $2$. For each index $i$, we compare $\\textit{nums}[i]$ with $\\textit{nums}[i - 1]$ and $\\textit{nums}[i - 2]$. If they are equal, we return that value.\n\nIf we don't find the repeated element in the above process, then the repeated element must be $\\textit{nums}[0]$, and we can directly return $\\textit{nums}[0]$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 962, "explanations": { "1": "According to the problem, we can find that the subsequence formed by all possible $\\textit{nums}[i]$ must be monotonically decreasing. Why is that? Let's prove it by contradiction.\n\nSuppose there exist $i_1 Note that if $x=1$ or $y=1$, then the value of $a$ or $b$ is always equal to $1$, and the corresponding loop only needs to be executed once to exit.\n\nThe time complexity is $O(\\log^2 bound)$, and the space complexity is $O(\\log^2 bound)$." }, "is_english": true, "time_complexity": "O(\\log^2 bound)", "space_complexity": "O(\\log^2 bound)" }, { "problem_id": 971, "explanations": { "1": "We can traverse the entire tree using depth-first search, using an index $i$ to record the current node's index in the $\\textit{voyage}$ array. If the value of the current node does not equal $\\textit{voyage}[i]$, it means that it is impossible to match after flipping, we mark $\\textit{ok}$ as `false` and return immediately. Otherwise, we increment $i$ by $1$, then check if the current node has a left child. If it does not, or if the value of the left child equals $\\textit{voyage}[i]$, we recursively traverse the current left and right children; otherwise, we need to flip the current node and then recursively traverse the current right and left children.\n\nAfter the search, if $\\textit{ok}$ is `true`, it means that it is possible to match after flipping, and we return the answer array $\\textit{ans}$, otherwise, we return $[-1]$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of nodes in the tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 972, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 973, "explanations": { "1": "We sort all points by their distance from the origin in ascending order, and then take the first $k$ points.\n\nThe time complexity is $O(n \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array $\\textit{points}$.", "2": "We can use a priority queue (max heap) to maintain the $k$ closest points to the origin.\n\nThe time complexity is $O(n \\times \\log k)$, and the space complexity is $O(k)$. Here, $n$ is the length of the array $\\textit{points}$.", "3": "We notice that as the distance increases, the number of points increases as well. There exists a critical value such that the number of points before this value is less than or equal to $k$, and the number of points after this value is greater than $k$.\n\nTherefore, we can use binary search to enumerate the distance. In each binary search iteration, we count the number of points whose distance is less than or equal to the current distance. If the count is greater than or equal to $k$, it indicates that the critical value is on the left side, so we set the right boundary equal to the current distance; otherwise, the critical value is on the right side, so we set the left boundary equal to the current distance plus one.\n\nAfter the binary search is finished, we just need to return the points whose distance is less than or equal to the left boundary.\n\nThe time complexity is $O(n \\times \\log M)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{points}$, and $M$ is the maximum value of the distance." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 974, "explanations": { "1": "Suppose there exists $i \\leq j$ such that the sum of $\\textit{nums}[i,..j]$ is divisible by $k$. If we let $s_i$ represent the sum of $\\textit{nums}[0,..i]$ and $s_j$ represent the sum of $\\textit{nums}[0,..j]$, then $s_j - s_i$ is divisible by $k$, i.e., $(s_j - s_i) \\bmod k = 0$, which means $s_j \\bmod k = s_i \\bmod k$. Therefore, we can use a hash table to count the number of prefix sums modulo $k$, allowing us to quickly determine if there exists a subarray that meets the condition.\n\nWe use a hash table $\\textit{cnt}$ to count the number of prefix sums modulo $k$, where $\\textit{cnt}[i]$ represents the number of prefix sums with a modulo $k$ value of $i$. Initially, $\\textit{cnt}[0] = 1$. We use a variable $s$ to represent the prefix sum, initially $s = 0$.\n\nNext, we traverse the array $\\textit{nums}$ from left to right. For each element $x$, we calculate $s = (s + x) \\bmod k$, then update the answer $\\textit{ans} = \\textit{ans} + \\textit{cnt}[s]$, where $\\textit{cnt}[s]$ represents the number of prefix sums with a modulo $k$ value of $s$. Finally, we increment the value of $\\textit{cnt}[s]$ by $1$ and continue to the next element.\n\nIn the end, we return the answer $\\textit{ans}$.\n\n> Note: Since the value of $s$ can be negative, we can add $k$ to the result of $s \\bmod k$ and then take modulo $k$ again to ensure that the value of $s$ is non-negative.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 975, "explanations": { "1": "We first use an ordered set to preprocess the positions that can be jumped to from each position, recorded in array $g$, where $g[i][1]$ and $g[i][0]$ represent the positions that can be jumped to when the current position is an odd jump or an even jump, respectively. If no position can be jumped to, then both $g[i][1]$ and $g[i][0]$ are $-1$.\n\nThen using memoization search, starting from each position with the current being an odd jump, we determine whether we can jump to the end of the array. If we can, then increment the result by one.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 976, "explanations": { "1": "Suppose the three sides of the triangle are $a \\leq b \\leq c$. The triangle has non-zero area if and only if $a + b \\gt c$.\n\nWe can enumerate the largest side $c$, then select the two largest remaining sides $a$ and $b$. If $a + b \\gt c$, a triangle with non-zero area can be formed, and its perimeter will be the largest possible; otherwise, continue to enumerate the next largest side $c$.\n\nThe time complexity is $O(n \\log n)$, and the space complexity is $O(\\log n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 977, "explanations": { "1": "Since the array $nums$ is already sorted in non-decreasing order, the square values of the negative numbers in the array are decreasing, and the square values of the positive numbers are increasing. We can use two pointers, each pointing to the ends of the array. Each time we compare the square values of the elements pointed to by the two pointers, we put the larger square value at the end of the result array.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. Ignoring the space consumption of the answer array, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 978, "explanations": { "1": "We define $f[i]$ as the length of the longest turbulent subarray ending at $\\textit{nums}[i]$ with an increasing state, and $g[i]$ as the length of the longest turbulent subarray ending at $\\textit{nums}[i]$ with a decreasing state. Initially, $f[0] = 1$, $g[0] = 1$. The answer is $\\max(f[i], g[i])$.\n\nFor $i \\gt 0$, if $\\textit{nums}[i] \\gt \\textit{nums}[i - 1]$, then $f[i] = g[i - 1] + 1$, otherwise $f[i] = 1$; if $\\textit{nums}[i] \\lt \\textit{nums}[i - 1]$, then $g[i] = f[i - 1] + 1$, otherwise $g[i] = 1$.\n\nSince $f[i]$ and $g[i]$ are only related to $f[i - 1]$ and $g[i - 1]$, two variables can be used instead of arrays.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 979, "explanations": { "1": "We define a function $\\textit{dfs(node)}$, which represents the coin overload in the subtree rooted at $\\textit{node}$, i.e., the number of coins minus the number of nodes. If $\\textit{dfs(node)}$ is positive, it means the subtree has more coins than nodes, and the excess coins need to be moved out of the subtree; if $\\textit{dfs(node)}$ is negative, it means the subtree has fewer coins than nodes, and the shortfall needs to be moved into the subtree.\n\nIn the function $\\textit{dfs(node)}$, we first traverse the left and right subtrees to obtain the coin overload $\\textit{left}$ and $\\textit{right}$ of the left and right subtrees, respectively. Then, the current number of moves needs to be increased by $|\\textit{left}| + |\\textit{right}|$, which means moving the coins from the left and right subtrees to the current node. After that, we return the coin overload of the entire subtree, which is $\\textit{left} + \\textit{right} + \\textit{node.val} - 1$.\n\nFinally, we return the number of moves.\n\nThe time complexity is $O(n)$, and the space complexity is $O(h)$. Here, $n$ and $h$ respectively represent the number of nodes and the height of the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(h)" }, { "problem_id": 980, "explanations": { "1": "We can first traverse the entire grid, find the starting point $(x, y)$, and count the number of blank spaces $cnt$.\n\nNext, we can start searching from the starting point to get all the path numbers. We design a function $dfs(i, j, k)$ to indicate that the path number is $k$ and the starting point is $(i, j)$.\n\nIn the function, we first determine whether the current cell is the end point. If it is, we determine whether $k$ is equal to $cnt + 1$. If it is, the current path is a valid path, and $1$ is returned, otherwise $0$ is returned.\n\nIf the current cell is not the end point, we enumerate the four adjacent cells of the current cell. If the adjacent cell has not been visited, we mark the adjacent cell as visited, and then continue to search the path number from the adjacent cell. After the search is completed, we mark the adjacent cell as unvisited. After the search is completed, we return the sum of the path numbers of all adjacent cells.\n\nFinally, we return the path number from the starting point, that is, $dfs(x, y, 1)$.\n\nThe time complexity is $O(3^{m \\times n})$, and the space complexity is $O(m \\times n)$. Where $m$ and $n$ are the number of rows and columns of the grid, respectively." }, "is_english": true, "time_complexity": "O(3^{m \\times n})", "space_complexity": "O(m \\times n)" }, { "problem_id": 981, "explanations": { "1": "We can use a hash table $\\textit{kvt}$ to record key-value pairs, where the key is the string $\\textit{key}$ and the value is an ordered set. Each element in the set is a tuple $(\\textit{timestamp}, \\textit{value})$, representing the value $\\textit{value}$ corresponding to the key $\\textit{key}$ at the timestamp $\\textit{timestamp}$.\n\nWhen we need to query the value corresponding to the key $\\textit{key}$ at the timestamp $\\textit{timestamp}$, we can use the ordered set to find the largest timestamp $\\textit{timestamp}'$ such that $\\textit{timestamp}' \\leq \\textit{timestamp}$, and then return the corresponding value.\n\nIn terms of time complexity, for the $\\textit{set}$ operation, since the insertion operation of the hash table has a time complexity of $O(1)$, the time complexity is $O(1)$. For the $\\textit{get}$ operation, since the lookup operation of the hash table has a time complexity of $O(1)$ and the lookup operation of the ordered set has a time complexity of $O(\\log n)$, the time complexity is $O(\\log n)$. The space complexity is $O(n)$, where $n$ is the number of $\\textit{set}$ operations." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(n)" }, { "problem_id": 982, "explanations": { "1": "First, we enumerate any two numbers $x$ and $y$, and use a hash table or array $cnt$ to count the occurrences of their bitwise AND result $x \\& y$.\n\nThen, we enumerate the bitwise AND result $xy$, and enumerate $z$. If $xy \\& z = 0$, then we add the value of $cnt[xy]$ to the answer.\n\nFinally, we return the answer.\n\nThe time complexity is $O(n^2 + n \\times M)$, and the space complexity is $O(M)$, where $n$ is the length of the array $nums$; and $M$ is the maximum value in the array $nums$, with $M \\leq 2^{16}$ in this problem." }, "is_english": true, "time_complexity": "O(n^2 + n \\times M)", "space_complexity": "O(M)" }, { "problem_id": 983, "explanations": { "1": "We define a function $\\textit{dfs(i)}$, which represents the minimum cost required from the $i$-th trip to the last trip. Thus, the answer is $\\textit{dfs(0)}$.\n\nThe execution process of the function $\\textit{dfs(i)}$ is as follows:\n\n- If $i \\geq n$, it means all trips have ended, return $0$;\n- Otherwise, we need to consider three types of purchases: buying a 1-day pass, buying a 7-day pass, and buying a 30-day pass. We calculate the cost for these three purchasing methods separately and use binary search to find the index $j$ of the next trip, then recursively call $\\textit{dfs(j)}$, and finally return the minimum cost among these three purchasing methods.\n\nTo avoid repeated calculations, we use memoization search to save the results that have already been calculated.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ represents the number of trips.", "2": "Let's denote the last day in the $\\textit{days}$ array as $m$. We can define an array $f$ of length $m + 1$, where $f[i]$ represents the minimum cost from day $1$ to day $i$.\n\nWe can calculate the value of $f[i]$ in increasing order of the dates in the $\\textit{days}$ array, starting from day $1$. If day $i$ is a travel day, we can consider three purchasing options: buying a 1-day pass, buying a 7-day pass, and buying a 30-day pass. We calculate the cost for these three purchasing methods separately and take the minimum cost among these three as the value of $f[i]$. If day $i$ is not a travel day, then $f[i] = f[i - 1]$.\n\nThe final answer is $f[m]$.\n\nThe time complexity is $O(m)$, and the space complexity is $O(m)$. Here, $m$ represents the last day of travel." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 984, "explanations": { "1": "循环构造字符串,当 $a$ 和 $b$ 都大于 `0` 时:\n\n1. 如果 $a\\gt b$,添加字符串 \"aab\"\n1. 如果 $b\\gt a$,添加字符串 \"bba\"\n1. 如果 $a=b$,添加字符串 \"ab\"\n\n循环结束,若 $a$ 有剩余,则添加 $a$ 个字符串 \"a\";若 $b$ 有剩余,则添加 $b$ 个字符串 \"b\"。\n\n时间复杂度 $O(a+b)$。" }, "is_english": false, "time_complexity": "O(a+b)", "space_complexity": null }, { "problem_id": 985, "explanations": { "1": "We use an integer variable $\\textit{s}$ to record the sum of all even numbers in the array $\\textit{nums}$. Initially, $\\textit{s}$ is the sum of all even numbers in the array $\\textit{nums}$.\n\nFor each query $(v, i)$, we first check if $\\textit{nums}[i]$ is even. If $\\textit{nums}[i]$ is even, we subtract $\\textit{nums}[i]$ from $\\textit{s}$. Then, we add $v$ to $\\textit{nums}[i]$. If $\\textit{nums}[i]$ is even, we add $\\textit{nums}[i]$ to $\\textit{s}$, and then add $\\textit{s}$ to the answer array.\n\nThe time complexity is $O(n + m)$, where $n$ and $m$ are the lengths of the arrays $\\textit{nums}$ and $\\textit{queries}$, respectively. Ignoring the space consumption of the answer array, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(1)" }, { "problem_id": 986, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 987, "explanations": { "1": "We design a function $dfs(root, i, j)$, where $i$ and $j$ represent the row and column of the current node. We can record the row and column information of the nodes through depth-first search, store it in an array or list $nodes$, and then sort $nodes$ in the order of column, row, and value.\n\nNext, we traverse $nodes$, putting the values of nodes in the same column into the same list, and finally return these lists.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 988, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 989, "explanations": { "1": "We can start from the last digit of the array and add each digit of the array to $k$. Then, divide $k$ by $10$, and use the remainder as the current digit's value, with the quotient as the carry. Continue this process until the array is fully traversed and $k = 0$. Finally, reverse the answer array.\n\nThe time complexity is $O(n)$, where $n$ is the length of $\\textit{num}$. Ignoring the space consumption of the answer array, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 990, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 991, "explanations": { "1": "We can use a reverse calculation method, starting from $\\textit{target}$. If $\\textit{target}$ is odd, then $\\textit{target} = \\textit{target} + 1$, otherwise $\\textit{target} = \\textit{target} / 2$. We accumulate the number of operations until $\\textit{target} \\leq \\textit{startValue}$. The final result is the number of operations plus $\\textit{startValue} - \\textit{target}$.\n\nThe time complexity is $O(\\log n)$, where $n$ is $\\textit{target}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 992, "explanations": { "1": "我们遍历数组 $nums$,对于每个 $i$,我们需要找到最小的 $j_1$,使得 $nums[j_1], nums[j_1 + 1], \\dots, nums[i]$ 中不同的整数个数小于等于 $k$,以及最小的 $j_2$,使得 $nums[j_2], nums[j_2 + 1], \\dots, nums[i]$ 中不同的整数个数小于等于 $k-1$。那么 $j_2 - j_1$ 就是以 $i$ 结尾的满足条件的子数组的个数。\n\n在实现上,我们定义一个函数 $f(k)$,表示 $nums$ 中每个位置 $i$ 对应的最小的 $j$,使得 $nums[j], nums[j + 1], \\dots, nums[i]$ 中不同的整数个数小于等于 $k$。该函数可以通过双指针实现,具体实现见代码。\n\n然后我们调用 $f(k)$ 和 $f(k-1)$,计算出每个位置对应的 $j_1$ 和 $j_2$,然后计算出以每个位置 $i$ 结尾的满足条件的子数组的个数,最后求和即可。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $nums$ 的长度。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 993, "explanations": { "1": "我们定义一个队列 $q$,队列中存储的是节点和其父节点。初始时,将根节点和空节点放入队列中。\n\n每次从队列中取出一个节点,如果该节点的值为 $x$ 或 $y$,则记录该节点的父节点和深度。如果该节点的左右子节点不为空,则将左右子节点和该节点放入队列中。\n\n当队列中所有节点都处理完毕后,如果 $x$ 和 $y$ 的深度相同且父节点不同,则返回 $true$,否则返回 $false$。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点数。", "2": "我们设计一个函数 $dfs(root, parent, depth)$,表示从根节点 $root$ 出发,其父节点为 $parent$,深度为 $depth$,进行深度优先搜索。\n\n在函数中,我们首先判断当前节点是否为空,如果为空,则直接返回。如果当前节点的值为 $x$ 或 $y$,则记录该节点的父节点和深度。然后对当前节点的左右子节点分别调用函数 $dfs$,其中父节点为当前节点,深度为当前深度加 $1$。即 $dfs(root.left, root, depth + 1)$ 和 $dfs(root.right, root, depth + 1)$。\n\n当整棵二叉树遍历完毕后,如果 $x$ 和 $y$ 的深度相同且父节点不同,则返回 $true$,否则返回 $false$。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点数。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 994, "explanations": { "1": "First, we traverse the entire grid once, count the number of fresh oranges, denoted as $\\textit{cnt}$, and add the coordinates of all rotten oranges to the queue $q$.\n\nNext, we perform a breadth-first search. In each round of the search, we let all the rotten oranges in the queue rot the fresh oranges in four directions, until the queue is empty or the number of fresh oranges is $0$.\n\nFinally, if the number of fresh oranges is $0$, we return the current round number, otherwise, we return $-1$.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Where $m$ and $n$ are the number of rows and columns of the grid, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 995, "explanations": { "1": "We notice that the result of reversing several consecutive elements is independent of the order of the reversals. Therefore, we can greedily consider the number of reversals needed at each position.\n\nWe can process the array from left to right.\n\nSuppose we need to process position $i$, and the elements to the left of position $i$ have been processed. If the element at position $i$ is $0$, then we must perform a reversal operation, we need to reverse the elements in the interval $[i,..i+k-1]$. Here we use a difference array $d$ to maintain the number of reversals at each position, then to determine whether the current position $i$ needs to be reversed, we only need to see $s = \\sum_{j=0}^{i}d[j]$ and the parity of $nums[i]$. If $s$ and $nums[i]$ have the same parity, then the element at position $i$ is still $0$ and needs to be reversed. At this time, we check whether $i+k$ exceeds the length of the array. If it exceeds the length of the array, then the target cannot be achieved, return $-1$. Otherwise, we increase $d[i]$ by $1$, decrease $d[i+k]$ by $1$, increase the answer by $1$, and increase $s$ by $1$.\n\nIn this way, when we have processed all the elements in the array, we can return the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$.", "2": "We can use a variable $\\textit{flipped}$ to indicate whether the current position has been flipped. If $\\textit{flipped} = 1$, it means the current position has already been flipped; otherwise, it means the current position has not been flipped. For positions that have been flipped, we can set their value to $-1$, allowing us to distinguish which positions have been flipped.\n\nNext, we traverse the array from left to right. For each position $i$, if $i \\geq k$ and the element at position $i-k$ is $-1$, then the flip state of the current position should be the opposite of the flip state of the previous position. That is, $\\textit{flipped} = \\textit{flipped} \\oplus 1$. If the element at the current position is the same as the current flip state, then we need to flip the current position. At this point, we check if $i+k$ exceeds the length of the array. If it does, then it is impossible to achieve the goal, and we return $-1$. Otherwise, we invert the current flip state, increase the answer by $1$, and set the element at the current position to $-1$.\n\nBy processing all elements in the array in this manner, we can return the answer upon completion.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 996, "explanations": { "1": "注意到,数组 $nums$ 的长度 $n$ 不超过 $12$,因此我们可以用一个二进制数表示当前所选的数字的状态,若第 $i$ 位为 $1$,则表示当前选择了第 $i$ 个数字,否则表示当前没有选择第 $i$ 个数字。\n\n我们定义 $f[i][j]$ 表示当前所选的数字的状态为 $i$,且最后一个数字为 $nums[j]$ 的方案数。那么答案就是 $\\sum_{j=0}^{n-1} f[2^n-1][j]$。由于最后求解的是排列数,因此还需要除以每个数字出现的次数的阶乘。\n\n接下来,我们考虑如何进行状态转移。\n\n假设当前所选的数字的状态为 $i$,最后一个数字为 $nums[j]$,那么我们可以枚举 $i$ 的每一位为 $1$ 的数字作为倒数第二个数,不妨设为 $nums[k]$,那么我们只需要判断 $nums[j]+nums[k]$ 是否为完全平方数即可,若是,方案数 $f[i][j]$ 就可以加上 $f[i \\oplus 2^j][k]$,其中 $i \\oplus 2^j$ 表示将 $i$ 的第 $j$ 位取反,即表示将 $nums[j]$ 从当前所选的数字中去除。\n\n最后,我们还需要除以每个数字出现的次数的阶乘,因为我们在枚举 $i$ 的每一位为 $1$ 的数字时,可能会重复计算某些排列,因此需要除以每个数字出现的次数的阶乘。\n\n时间复杂度 $O(2^n \\times n^2),空间复杂度 O(2^n \\times n)$。其中 $n$ 为数组 $nums$ 的长度。" }, "is_english": false, "time_complexity": "O(2^n \\times n^2)", "space_complexity": "O(2^n \\times n)" }, { "problem_id": 997, "explanations": { "1": "We create two arrays $cnt1$ and $cnt2$ of length $n + 1$, representing the number of people each person trusts and the number of people who trust each person, respectively.\n\nNext, we traverse the array $trust$, for each item $[a_i, b_i]$, we increment $cnt1[a_i]$ and $cnt2[b_i]$ by $1$.\n\nFinally, we enumerate each person $i$ in the range $[1,..n]$. If $cnt1[i] = 0$ and $cnt2[i] = n - 1$, it means that $i$ is the town judge, and we return $i$. Otherwise, if no such person is found after the traversal, we return $-1$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $trust$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 998, "explanations": { "1": "If $val$ is the maximum number, then make $val$ the new root node, and $root$ the left subtree of the new root node.\n\nIf $val$ is not the maximum number, since $val$ is the last appended number, it must be on the right side of $root$. Therefore, we can insert $val$ as a new node into the right subtree of $root$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the tree.", "2": "Search the right subtree, find the node where $curr.val \\gt val \\gt curr.right.val$, then create a new node $node$, point $node.left$ to $curr.right$, and then point $curr.right$ to $node$.\n\nFinally, return $root$.\n\nThe time complexity is $O(n)$, where $n$ is the number of nodes in the tree. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 999, "explanations": { "1": "We first traverse the board to find the position of the rook $(i, j)$. Then, starting from $(i, j)$, we traverse in four directions: up, down, left, and right.\n\n- If it is not the boundary and not a bishop, continue moving forward.\n- If it is a pawn, increment the answer by one and stop traversing in that direction.\n\nAfter traversing in all four directions, we get the answer.\n\nThe time complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns of the board, respectively. In this problem, $m = n = 8$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(1)" }, { "problem_id": 1000, "explanations": { "1": "我们不妨记题目中的 $k$ 为 $K$,石头的堆数为 $n$。\n\n定义 $f[i][j][k]$ 表示将区间 $[i, j]$ 中的石头合并成 $k$ 堆的最小成本。初始时 $f[i][i][1] = 0$,其他位置的值均为 $\\infty$。\n\n注意到 $k$ 的取值范围为 $[1, K]$,因此我们需要枚举 $k$ 的值。\n\n对于 $f[i][j][k]$,我们可以枚举 $i \\leq h \\lt j$,将区间 $[i, j]$ 拆分成两个区间 $[i, h]$ 和 $[h + 1, j]$,然后将 $[i, h]$ 中的石头合并成 $1$ 堆,将 $[h + 1, j]$ 中的石头合并成 $k - 1$ 堆,最后将这两堆石头合并成一堆,这样就可以将区间 $[i, j]$ 中的石头合并成 $k$ 堆。因此,我们可以得到状态转移方程:\n\n$$\nf[i][j][k] = \\min_{i \\leq h < j} \\{f[i][h][1] + f[h + 1][j][k - 1]\\}\n$$\n\n我们将区间 $[i, j]$ 的 $K$ 堆石头合并成一堆,因此 $f[i][j][1] = f[i][j][K] + \\sum_{t = i}^j stones[t]$,其中 $\\sum_{t = i}^j stones[t]$ 表示区间 $[i, j]$ 中石头的总数。\n\n最后答案即为 $f[1][n][1]$,其中 $n$ 为石头的堆数。\n\n时间复杂度 $O(n^3 \\times k)$,空间复杂度 $O(n^2 \\times k)$。其中 $n$ 为石头的堆数。" }, "is_english": false, "time_complexity": "O(n^3 \\times k)", "space_complexity": "O(n^2 \\times k)" }, { "problem_id": 1001, "explanations": { "1": "Suppose the coordinates of a lamp are $(x, y)$. Then, the row value is $x$, the column value is $y$, the main diagonal value is $x-y$, and the anti-diagonal value is $x+y$. Once we determine the unique value identifier for a line, we can use a hash table to record the number of lamps on that line.\n\nWe traverse the array $\\textit{lamps}$, and for each lamp, we increment the count of lamps in its row, column, main diagonal, and anti-diagonal by $1$.\n\nNote that when processing $\\textit{lamps}$, we need to remove duplicates because we treat repeated lamps as the same lamp.\n\nNext, we traverse the queries and check if there are lamps in the row, column, main diagonal, or anti-diagonal of the current query point. If there are, we set the value to $1$, indicating that the point is illuminated during the query. Then, we perform the turn-off operation by checking the eight neighboring points of the query point and the point itself to see if there are any lamps. If there are, we decrement the count of lamps in the corresponding row, column, main diagonal, and anti-diagonal by $1$ and remove the lamp from the grid.\n\nFinally, we return the answer array.\n\nThe time complexity is $O(m + q)$, where $m$ and $q$ are the lengths of the arrays $\\textit{lamps}$ and $\\textit{queries}$, respectively." }, "is_english": true, "time_complexity": "O(m + q)", "space_complexity": null }, { "problem_id": 1002, "explanations": { "1": "We use an array $cnt$ of length $26$ to record the minimum number of times each character appears in all strings. Finally, we traverse the $cnt$ array and add characters with a count greater than $0$ to the answer.\n\nThe time complexity is $O(n \\sum w_i)$, and the space complexity is $O(|\\Sigma|)$. Here, $n$ is the length of the string array $words$, $w_i$ is the length of the $i$-th string in the array $words$, and $|\\Sigma|$ is the size of the character set, which is $26$ in this problem." }, "is_english": true, "time_complexity": "O(n \\sum w_i)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 1003, "explanations": { "1": "We observe the operations in the problem and find that each time a string $\\textit{\"abc\"}$ is inserted at any position in the string. Therefore, after each insertion operation, the length of the string increases by $3$. If the string $s$ is valid, its length must be a multiple of $3$. Thus, we first check the length of the string $s$. If it is not a multiple of $3$, then $s$ must be invalid, and we can directly return $\\textit{false}$.\n\nNext, we traverse each character $c$ in the string $s$. We first push the character $c$ onto the stack $t$. If the length of the stack $t$ is greater than or equal to $3$, and the top three elements of the stack form the string $\\textit{\"abc\"}$, then we pop the top three elements from the stack. We then continue to traverse the next character in the string $s$.\n\nAfter the traversal, if the stack $t$ is empty, it means the string $s$ is valid, and we return $\\textit{true}$; otherwise, we return $\\textit{false}$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1004, "explanations": { "1": "We can iterate through the array, using a variable $\\textit{cnt}$ to record the current number of 0s in the window. When $\\textit{cnt} > k$, we move the left boundary of the window to the right by one position.\n\nAfter the iteration ends, the length of the window is the maximum number of consecutive 1s.\n\nNote that in the process above, we do not need to loop to move the left boundary of the window to the right. Instead, we directly move the left boundary to the right by one position. This is because the problem asks for the maximum number of consecutive 1s, so the length of the window will only increase, not decrease. Therefore, we do not need to loop to move the left boundary to the right.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$.\n\nSimilar problems:\n\n- [487. Max Consecutive Ones II](https://github.com/doocs/leetcode/blob/main/solution/0400-0499/0487.Max%20Consecutive%20Ones%20II/README_EN.md)\n- [2024. Maximize the Confusion of an Exam](https://github.com/doocs/leetcode/blob/main/solution/2000-2099/2024.Maximize%20the%20Confusion%20of%20an%20Exam/README_EN.md)" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1005, "explanations": { "1": "We observe that to maximize the sum of the array, we should try to turn the smallest negative numbers into positive numbers.\n\nGiven that the range of elements is $[-100, 100]$, we can use a hash table $\\textit{cnt}$ to count the occurrences of each element in the array $\\textit{nums}$. Then, starting from $-100$, we iterate through $x$. If $x$ exists in the hash table, we take $m = \\min(\\textit{cnt}[x], k)$ as the number of times to negate the element $x$. We then subtract $m$ from $\\textit{cnt}[x]$, add $m$ to $\\textit{cnt}[-x]$, and subtract $m$ from $k$. If $k$ becomes $0$, the operation is complete, and we exit the loop.\n\nIf $k$ is still odd and $\\textit{cnt}[0] = 0$, we need to take the smallest positive number $x$ in $\\textit{cnt}$, subtract $1$ from $\\textit{cnt}[x]$, and add $1$ to $\\textit{cnt}[-x]$.\n\nFinally, we traverse the hash table $\\textit{cnt}$ and sum the products of $x$ and $\\textit{cnt}[x]$ to get the answer.\n\nThe time complexity is $O(n + M)$, and the space complexity is $O(M)$. Here, $n$ and $M$ are the length of the array $\\textit{nums}$ and the size of the data range of $\\textit{nums}$, respectively." }, "is_english": true, "time_complexity": "O(n + M)", "space_complexity": "O(M)" }, { "problem_id": 1006, "explanations": { "1": "The calculation process of clumsy factorial can be seen as a simulation of a stack.\n\nWe define a stack `stk`, initially we push $n$ into the stack, and define a variable $k$ to represent the current operator, initially $k = 0$.\n\nThen we start from $n-1$, enumerate $x$, and decide how to handle $x$ based on the current value of $k$:\n\n- When $k = 0$, it represents a multiplication operation, we pop the top element of the stack, multiply it by $x$, and then push it back into the stack;\n- When $k = 1$, it represents a division operation, we pop the top element of the stack, divide it by $x$, take the integer part, and then push it back into the stack;\n- When $k = 2$, it represents an addition operation, we directly push $x$ into the stack;\n- When $k = 3$, it represents a subtraction operation, we push $-x$ into the stack.\n\nNext, we update $k = (k + 1) \\mod 4$.\n\nFinally, the sum of the elements in the stack is the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the integer $N$ given in the problem." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1007, "explanations": { "1": "According to the problem description, we know that in order to make all values in $tops$ or all values in $bottoms$ the same, the value must be one of $tops[0]$ or $bottoms[0]$.\n\nTherefore, we design a function $f(x)$ to represent the minimum number of rotations required to make all values equal to $x$. Then the answer is $\\min\\{f(\\textit{tops}[0]), f(\\textit{bottoms}[0])\\}$.\n\nThe calculation method of function $f(x)$ is as follows:\n\nWe use two variables $cnt1$ and $cnt2$ to count the number of occurrences of $x$ in $tops$ and $bottoms$, respectively. We subtract the maximum value of $cnt1$ and $cnt2$ from $n$, which is the minimum number of rotations required to make all values equal to $x$. Note that if there are no values equal to $x$ in $tops$ and $bottoms$, the value of $f(x)$ is a very large number, which we represent as $n+1$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1008, "explanations": { "1": "We design a function $\\textit{dfs}(i, j)$ to construct a binary search tree from the nodes $\\textit{preorder}[i]$ to $\\textit{preorder}[j]$. The answer is $\\textit{dfs}(0, n - 1)$.\n\nIn $\\textit{dfs}(i, j)$, we first construct the root node, which is $\\textit{preorder}[i]$. Then, we use binary search to find the first node greater than $\\textit{preorder}[i]$ and get its index $\\textit{mid}$. We set $\\textit{dfs}(i + 1, \\textit{mid} - 1)$ as the left subtree of the root node and $\\textit{dfs}(\\textit{mid}, j)$ as the right subtree of the root node.\n\nFinally, we return the root node.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{preorder}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1009, "explanations": { "1": "First, we check if $n$ is $0$. If it is, we return $1$.\n\nNext, we define two variables $\\textit{ans}$ and $i$, both initialized to $0$. Then we iterate through $n$. In each iteration, we set the $i$-th bit of $\\textit{ans}$ to the inverse of the $i$-th bit of $n$, increment $i$ by $1$, and right shift $n$ by $1$.\n\nFinally, we return $\\textit{ans}$.\n\nThe time complexity is $O(\\log n)$, where $n$ is the given decimal number. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 1010, "explanations": { "1": "If the sum of a pair $(a, b)$ is divisible by $60$, i.e., $(a + b) \\bmod 60 = 0$, then $(a \\bmod 60 + b \\bmod 60) \\bmod 60 = 0$. Let $x = a \\bmod 60$ and $y = b \\bmod 60$, then $(x + y) \\bmod 60 = 0$, which means $y = (60 - x) \\bmod 60$.\n\nTherefore, we can iterate over the song list and use an array $cnt$ of length $60$ to record the number of occurrences of each remainder $x$. For the current $x$, if there exists a remainder $y = (60 - x) \\bmod 60$ in array $cnt$, we add $cnt[y]$ to the answer. Then we increment the count of $x$ in array $cnt$ by $1$. We continue iterating until the entire song list has been traversed.\n\nAfter the iteration, we get the number of song pairs that satisfy the condition.\n\nThe time complexity is $O(n)$ and the space complexity is $O(C)$, where $n$ is the length of the song list and $C$ is the number of possible remainders, here $C = 60$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(C)" }, { "problem_id": 1011, "explanations": { "1": "我们注意到,如果运载能力 $x$ 能够在 $days$ 天内运送完所有包裹,那么运载能力 $x + 1$ 也能在 $days$ 天内运送完所有包裹。也即是说,随着运载能力的增加,运送天数只会减少,不会增加。这存在一个单调性,因此我们可以使用二分查找的方法来寻找最小的运载能力。\n\n我们定义二分查找的左边界 $left= \\max\\limits_{i=0}^{n-1} weights[i]$,右边界 $right = \\sum\\limits_{i=0}^{n-1} weights[i]$。然后二分枚举运载能力 $x$,判断是否能在 $days$ 天内运送完所有包裹。如果能,那么我们将右边界调整为 $x$,否则将左边界调整为 $x + 1$。\n\n判断是否能在 $days$ 天内运送完所有包裹的方法是,我们从左到右遍历包裹,将当前包裹加入当前运载能力的船上,如果当前船的运载能力超过了 $x$,那么我们将当前包裹放到下一天的船上,同时天数加一。如果天数超过了 $days$,那么我们返回 $false$,否则返回 $true$。\n\n时间复杂度 $O(n \\times \\log \\sum\\limits_{i=0}^{n-1} weights[i])$,空间复杂度 $O(1)$。其中 $n$ 为包裹数量。" }, "is_english": false, "time_complexity": "O(n \\times \\log \\sum\\limits_{i=0}^{n-1} weights[i])", "space_complexity": "O(1)" }, { "problem_id": 1012, "explanations": { "1": "The problem requires counting the number of integers in the range $[1, .., n]$ that have at least one repeated digit. We can approach this by defining a function $f(n)$ that counts the number of integers in the range $[1, .., n]$ with no repeated digits. Then, the answer is $n - f(n)$.\n\nAdditionally, we can use a binary number to record the digits that have appeared in the number. For example, if the digits $1$, $2$, and $4$ have appeared, the corresponding binary number is $\\underline{1}0\\underline{1}\\underline{1}0$.\n\nNext, we use memoization to implement digit DP. We start searching from the top, get the number of solutions at the bottom, and return the answers layer by layer until we get the final answer from the starting point.\n\nThe basic steps are as follows:\n\nWe convert the number $n$ into a string $s$. Next, we design a function $\\textit{dfs}(i, \\textit{mask}, \\textit{lead}, \\textit{limit})$, where:\n\n- The integer $i$ represents the current digit index, starting from $0$.\n- The integer $\\textit{mask}$ represents the digits that have appeared so far, using a binary number. The $j$-th bit of $\\textit{mask}$ being $1$ indicates that digit $j$ has appeared, while $0$ indicates it has not.\n- The boolean $\\textit{lead}$ indicates whether the current number contains only leading zeros.\n- The boolean $\\textit{limit}$ indicates whether the current position is restricted by the upper bound.\n\nThe function executes as follows:\n\nIf $i$ is greater than or equal to $m$, it means we have processed all digits. If $\\textit{lead}$ is true, it means the current number is a leading zero, and we should return $0$. Otherwise, we should return $1$.\n\nOtherwise, we calculate the upper bound $\\textit{up}$. If $\\textit{limit}$ is true, then $\\textit{up}$ is the digit corresponding to $s[i]$. Otherwise, $\\textit{up}$ is $9$.\n\nThen, we enumerate the current digit $j$ in the range $[0, \\textit{up}]$. If $j$ is $0$ and $\\textit{lead}$ is true, we recursively calculate $\\textit{dfs}(i + 1, \\textit{mask}, \\text{true}, \\textit{limit} \\wedge j = \\textit{up})$. Otherwise, if the $j$-th bit of $\\textit{mask}$ is $0$, we recursively calculate $\\textit{dfs}(i + 1, \\textit{mask} \\,|\\, 2^j, \\text{false}, \\textit{limit} \\wedge j = \\textit{up})$. We accumulate all the results as the answer.\n\nThe answer is $n - \\textit{dfs}(0, 0, \\text{true}, \\text{true})$.\n\nThe time complexity is $O(\\log n \\times 2^D \\times D)$, and the space complexity is $O(\\log n \\times 2^D)$. Here, $D = 10$.\n\nSimilar problems:\n\n- [233. Number of Digit One](https://github.com/doocs/leetcode/blob/main/solution/0200-0299/0233.Number%20of%20Digit%20One/README_EN.md)\n- [357. Count Numbers with Unique Digits](https://github.com/doocs/leetcode/blob/main/solution/0300-0399/0357.Count%20Numbers%20with%20Unique%20Digits/README_EN.md)\n- [600. Non-negative Integers without Consecutive Ones](https://github.com/doocs/leetcode/blob/main/solution/0600-0699/0600.Non-negative%20Integers%20without%20Consecutive%20Ones/README_EN.md)\n- [788. Rotated Digits](https://github.com/doocs/leetcode/blob/main/solution/0700-0799/0788.Rotated%20Digits/README_EN.md)\n- [902. Numbers At Most N Given Digit Set](https://github.com/doocs/leetcode/blob/main/solution/0900-0999/0902.Numbers%20At%20Most%20N%20Given%20Digit%20Set/README_EN.md)\n- [2376. Count Special Integers](https://github.com/doocs/leetcode/blob/main/solution/2300-2399/2376.Count%20Special%20Integers/README_EN.md)" }, "is_english": true, "time_complexity": "O(\\log n \\times 2^D \\times D)", "space_complexity": "O(\\log n \\times 2^D)" }, { "problem_id": 1013, "explanations": { "1": "First, we calculate the sum of the entire array and check if the sum is divisible by 3. If it is not, we directly return $\\textit{false}$.\n\nOtherwise, let $\\textit{s}$ represent the sum of each part. We use a variable $\\textit{cnt}$ to record the number of parts found so far, and another variable $\\textit{t}$ to record the current part's sum. Initially, $\\textit{cnt} = 0$ and $\\textit{t} = 0$.\n\nThen we traverse the array. For each element $x$, we add $x$ to $\\textit{t}$. If $\\textit{t}$ equals $s$, it means we have found one part, so we increment $\\textit{cnt}$ by one and reset $\\textit{t}$ to 0.\n\nFinally, we check if $\\textit{cnt}$ is greater than or equal to 3.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{arr}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1014, "explanations": { "1": "We can enumerate $j$ from left to right while maintaining the maximum value of $values[i] + i$ for elements to the left of $j$, denoted as $mx$. For each $j$, the maximum score is $mx + values[j] - j$. The answer is the maximum of these maximum scores for all positions.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{values}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1015, "explanations": { "1": "We observe that the positive integer $n$ starts with an initial value of $1$, and each time it is multiplied by $10$ and then $1$ is added, i.e., $n = n \\times 10 + 1$. Since $(n \\times 10 + 1) \\bmod k = ((n \\bmod k) \\times 10 + 1) \\bmod k$, we can determine whether $n$ is divisible by $k$ by calculating $n \\bmod k$.\n\nWe start from $n = 1$ and calculate $n \\bmod k$ each time until $n \\bmod k = 0$. At this point, $n$ is the smallest positive integer we are looking for, and its length is the number of digits in $n$. Otherwise, we update $n = (n \\times 10 + 1) \\bmod k$. If after looping $k$ times we still haven't found $n \\bmod k = 0$, it means no such $n$ exists, and we return $-1$.\n\nThe time complexity is $O(k)$ and the space complexity is $O(1)$, where $k$ is the given positive integer." }, "is_english": true, "time_complexity": "O(k)", "space_complexity": "O(1)" }, { "problem_id": 1016, "explanations": { "1": "We observe that the length of string $s$ does not exceed $1000$, so string $s$ can represent at most $1000$ binary integers. Therefore, if $n \\gt 1000$, then $s$ definitely cannot represent the binary representation of all integers in the range $[1,.. n]$.\n\nAdditionally, for an integer $x$, if the binary representation of $x$ is a substring of $s$, then the binary representation of $\\lfloor x / 2 \\rfloor$ is also a substring of $s$. Therefore, we only need to check whether the binary representations of integers in the range $[\\lfloor n / 2 \\rfloor + 1,.. n]$ are substrings of $s$.\n\nThe time complexity is $O(m^2 \\times \\log m)$ and the space complexity is $O(\\log n)$, where $m$ is the length of string $s$ and $n$ is the positive integer given in the problem." }, "is_english": true, "time_complexity": "O(m^2 \\times \\log m)", "space_complexity": "O(\\log n)" }, { "problem_id": 1017, "explanations": { "1": "我们可以判断 $n$ 从低位到高位的每一位,如果该位为 $1$,那么答案的该位为 $1$,否则为 $0$。如果该位为 $1$,那么我们需要将 $n$ 减去 $k$。接下来我们更新 $n = \\lfloor n / 2 \\rfloor$, $k = -k$。继续判断下一位。\n\n最后,我们将答案反转后返回即可。\n\n时间复杂度 $O(\\log n)$,其中 $n$ 为给定的整数。忽略答案的空间消耗,空间复杂度 $O(1)$。\n\n相似题目:\n\n- [1073. 负二进制数相加](https://github.com/doocs/leetcode/blob/main/solution/1000-1099/1073.Adding%20Two%20Negabinary%20Numbers/README.md)" }, "is_english": false, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 1018, "explanations": { "1": "We use a variable $x$ to represent the current binary prefix, then traverse the array $nums$. For each element $v$, we left shift $x$ by one bit, then add $v$, and take the result modulo $5$. If the result equals $0$, it means the current binary prefix is divisible by $5$, and we add $\\textit{true}$ to the answer array; otherwise, we add $\\textit{false}$ to the answer array.\n\nThe time complexity is $O(n)$, and ignoring the space consumption of the answer array, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1019, "explanations": { "1": "The problem requires finding the next larger node for each node in the linked list, that is, finding the first node to the right of each node in the linked list that is larger than it. We first traverse the linked list and store the values in the linked list in an array $nums$. For each element in the array $nums$, we just need to find the first element to its right that is larger than it. The problem of finding the next larger element can be solved using a monotonic stack.\n\nWe traverse the array $nums$ from back to front, maintaining a stack $stk$ that is monotonically decreasing from the bottom to the top. During the traversal, if the top element of the stack is less than or equal to the current element, we loop to pop the top element of the stack until the top element of the stack is larger than the current element or the stack is empty.\n\nIf the stack is empty at this time, it means that the current element does not have a next larger element, otherwise, the next larger element of the current element is the top element of the stack, and we update the answer array $ans$. Then we push the current element into the stack and continue the traversal.\n\nAfter the traversal is over, we return the answer array $ans$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the linked list." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1020, "explanations": { "1": "我们可以从边界上的陆地开始进行深度优先搜索,将所有与边界相连的陆地都标记为 $0$。最后,统计剩余的 $1$ 的个数,即为答案。\n\n时间复杂度 $O(m \\times n)$,空间复杂度 $O(m \\times n)$。其中 $m$ 和 $n$ 分别为矩阵的行数和列数。", "2": "我们也可以使用广度优先搜索的方法,将边界上的陆地入队,然后进行广度优先搜索,将所有与边界相连的陆地都标记为 $0$。最后,统计剩余的 $1$ 的个数,即为答案。\n\n时间复杂度 $O(m \\times n)$,空间复杂度 $O(m \\times n)$。其中 $m$ 和 $n$ 分别为矩阵的行数和列数。", "3": "" }, "is_english": false, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 1021, "explanations": { "1": "遍历字符串,遇到左括号 `'('` 计数器加一,此时计数器不为 $1$ 时,说明当前括号不是最外层括号,将其加入结果字符串。遇到右括号 `')'` 计数器减一,此时计数器不为 $0$ 时,说明当前括号不是最外层括号,将其加入结果字符串。\n\n时间复杂度 $O(n)$,其中 $n$ 为字符串长度。忽略答案字符串的空间开销,空间复杂度 $O(1)$。", "2": "" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1022, "explanations": { "1": "We design a recursive function $\\text{dfs}(root, t)$, which takes two parameters: the current node $root$ and the binary number $t$ corresponding to the parent node of the current node. The return value of the function is the sum of binary numbers represented by paths from the current node to leaf nodes. The answer is $\\textrm{dfs}(root, 0)$.\n\nThe logic of the recursive function is as follows:\n\n- If the current node $root$ is null, return $0$; otherwise, calculate the binary number $t$ corresponding to the current node, i.e., $t = t \\ll 1 | root.val$.\n- If the current node is a leaf node, return $t$; otherwise, return the sum of $\\textrm{dfs}(root.left, t)$ and $\\textrm{dfs}(root.right, t)$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of nodes in the binary tree. Each node is visited once; the recursion stack requires $O(n)$ space." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1023, "explanations": { "1": "We can traverse every string in `queries` and check whether it matches `pattern` or not. If it matches, we add `true` to the answer array, otherwise we add `false`.\n\nNext, we implement a function $check(s, t)$ to check whether the string $s$ matches the string $t$.\n\nWe can use two pointers $i$ and $j$ to traverse the two strings. If the characters pointed to by $i$ and $j$ are not the same and $s[i]$ is a lowercase letter, then we move the pointer $i$ to the next position.\n\nIf the pointer $i$ has reached the end of the string $s$ or the characters pointed to by $i$ and $j$ are not the same, we return `false`. Otherwise, we move both pointers $i$ and $j$ to the next position. When the pointer $j$ reaches the end of the string $t$, we need to check if the remaining characters in the string $s$ are all lowercase letters. If so, we return `true`, otherwise we return `false`.\n\nTime complexity $(n \\times m)$, where $n$ and $m$ are the length of the array `queries` and the string `pattern` respectively." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1024, "explanations": { "1": "Note that if there are multiple sub-intervals with the same starting point, it is optimal to choose the one with the largest right endpoint.\n\nTherefore, we can preprocess all sub-intervals. For each position $i$, calculate the largest right endpoint among all sub-intervals starting at $i$, and record it in the array $last[i]$.\n\nWe define a variable `mx` to represent the farthest position that can currently be reached, a variable `ans` to represent the current minimum number of sub-intervals needed, and a variable `pre` to represent the right endpoint of the last used sub-interval.\n\nNext, we start enumerating all positions $i$ from $0$, using $last[i]$ to update `mx`. If after updating, $mx = i$, it means that the next position cannot be covered, so the task cannot be completed, return $-1$.\n\nAt the same time, we record the right endpoint `pre` of the last used sub-interval. If $pre = i$, it means that a new sub-interval needs to be used, so we add $1$ to `ans` and update `pre` to `mx`.\n\nAfter the traversal is over, return `ans`.\n\nThe time complexity is $O(n+m)$, and the space complexity is $O(m)$. Where $n$ and $m$ are the lengths of the `clips` array and the value of `time`, respectively.\n\nSimilar problems:\n\n- [45. Jump Game II](https://github.com/doocs/leetcode/blob/main/solution/0000-0099/0045.Jump%20Game%20II/README_EN.md)\n- [55. Jump Game](https://github.com/doocs/leetcode/blob/main/solution/0000-0099/0055.Jump%20Game/README_EN.md)\n- [1326. Minimum Number of Taps to Open to Water a Garden](https://github.com/doocs/leetcode/blob/main/solution/1300-1399/1326.Minimum%20Number%20of%20Taps%20to%20Open%20to%20Water%20a%20Garden/README_EN.md)" }, "is_english": true, "time_complexity": "O(n+m)", "space_complexity": "O(m)" }, { "problem_id": 1025, "explanations": { "1": "- When $n=1$, the first player loses.\n- When $n=2$, the first player takes $1$, leaving $1$, the second player loses, the first player wins.\n- When $n=3$, the first player takes $1$, leaving $2$, the second player wins, the first player loses.\n- When $n=4$, the first player takes $1$, leaving $3$, the second player loses, the first player wins.\n- ...\n\nWe conjecture that when $n$ is odd, the first player loses; when $n$ is even, the first player wins.\n\nProof:\n\n1. If $n=1$ or $n=2$, the conclusion holds.\n1. If $n \\gt 2$, assume that the conclusion holds when $n \\le k$, then when $n=k+1$:\n - If $k+1$ is odd, since $x$ is a divisor of $k+1$, then $x$ can only be odd, so $k+1-x$ is even, the second player wins, the first player loses.\n - If $k+1$ is even, now $x$ can be either odd $1$ or even. If $x$ is odd, then $k+1-x$ is odd, the second player loses, the first player wins.\n\nIn conclusion, when $n$ is odd, the first player loses; when $n$ is even, the first player wins. The conclusion is correct.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 1026, "explanations": { "1": "For each node, to find the maximum difference with its ancestor nodes, we only need to find the difference between the maximum and minimum values of the ancestor nodes. The maximum difference among all nodes and their ancestor nodes is the answer.\n\nTherefore, we design a function $dfs(root, mi, mx)$, where the current node being searched is $root$, the maximum value of its ancestor nodes is $mx$, and the minimum value is $mi$. The function updates the maximum difference $ans$.\n\nThe logic of the function $dfs(root, mi, mx)$ is as follows:\n\n- If $root$ is null, return directly.\n- Otherwise, we update $ans = max(ans, |mi - root.val|, |mx - root.val|)$.\n- Then update $mi = min(mi, root.val)$, $mx = max(mx, root.val)$, and recursively search the left and right subtrees.\n\nIn the main function, we call $dfs(root, root.val, root.val)$, and finally return $ans$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1027, "explanations": { "1": "We define $f[i][j]$ as the maximum length of the arithmetic sequence ending with $nums[i]$ and having a common difference of $j$. Initially, $f[i][j]=1$, that is, each element itself is an arithmetic sequence of length $1$.\n\n> Since the common difference may be negative, and the maximum difference is $500$, we can uniformly add $500$ to the common difference, so the range of the common difference becomes $[0, 1000]$.\n\nConsidering $f[i]$, we can enumerate the previous element $nums[k]$ of $nums[i]$, then the common difference $j=nums[i]-nums[k]+500$, at this time $f[i][j]=\\max(f[i][j], f[k][j]+1)$, then we update the answer $ans=\\max(ans, f[i][j])$.\n\nFinally, return the answer.\n\n> If initially $f[i][j]=0$, then we need to add $1$ to the answer when returning the answer.\n\nThe time complexity is $O(n \\times (d + n))$, and the space complexity is $O(n \\times d)$. Where $n$ and $d$ are the length of the array $nums$ and the difference between the maximum and minimum values in the array $nums$, respectively." }, "is_english": true, "time_complexity": "O(n \\times (d + n))", "space_complexity": "O(n \\times d)" }, { "problem_id": 1028, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1029, "explanations": { "1": "我们不妨先假设所有人都去 $b$ 市,然后我们要从中选出 $n$ 个人去 $a$ 市,使得总费用最小。如果一个人去 $a$ 市的费用比去 $b$ 市的费用小,我们把这个人从 $b$ 市调到 $a$ 市,这样总费用就会减少。因此,我们可以将所有人按照去 $a$ 市的费用与去 $b$ 市的费用的差值从小到大排序,然后选出前 $n$ 个人去 $a$ 市,剩下的人去 $b$ 市,这样总费用就是最小的。\n\n时间复杂度 $O(n \\times \\log n)$,空间复杂度 $O(\\log n)$。其中 $n$ 为数组 `costs` 的长度。\n\n相似题目:\n\n- [2611. 老鼠和奶酪](https://github.com/doocs/leetcode/blob/main/solution/2600-2699/2611.Mice%20and%20Cheese/README.md)" }, "is_english": false, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 1030, "explanations": { "1": "我们定义一个队列 $q$,初始时将坐标点 $(rCenter, cCenter)$ 入队,用一个二维布尔数组 $vis$ 记录已经访问过的点,初始时 $vis[rCenter][cCenter]$ 为 $true$。\n\n接下来,我们不断地从队列中取出一个点,将其加入答案数组,然后将其上下左右四个相邻点加入队列,注意要判断这些点是否已经访问过,如果没有访问过,就将其标记为已访问,并将其加入队列。一直重复这个过程,直到队列为空,此时答案数组中的点就是按照距离从小到大的顺序排列的。\n\n时间复杂度 $O(m \\times n)$,空间复杂度 $O(m \\times n)$。其中 $m$ 和 $n$ 分别是矩阵的行数和列数。" }, "is_english": false, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 1031, "explanations": { "1": "我们先预处理得到数组 `nums` 的前缀和数组 $s$,其中 $s[i]$ 表示 $nums$ 中前 $i$ 个元素的和。\n\n接下来,我们分两种情况枚举:\n\n假设 $firstLen$ 个元素的子数组在 $secondLen$ 个元素的子数组的左边,那么我们可以枚举 $secondLen$ 个元素的子数组的左端点 $i$,用变量 $t$ 维护左边 $firstLen$ 个元素的子数组的最大和,那么答案就是 $t + s[i + secondLen] - s[i]$。枚举完所有的 $i$,就可以得到候选答案。\n\n假设 $secondLen$ 个元素的子数组在 $firstLen$ 个元素的子数组的左边,那么我们可以枚举 $firstLen$ 个元素的子数组的左端点 $i$,用变量 $t$ 维护左边 $secondLen$ 个元素的子数组的最大和,那么答案就是 $t + s[i + firstLen] - s[i]$。枚举完所有的 $i$,就可以得到候选答案。\n\n最后,我们取两种情况下的候选答案的最大值即可。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 `nums` 的长度。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1032, "explanations": { "1": "我们可以根据初始化时的字符串数组 $words$ 构建前缀树,前缀树的每个节点包含两个属性:\n\n- `children`:指向 $26$ 个字母的指针数组,用于存储当前节点的子节点。\n- `is_end`:标记当前节点是否为某个字符串的结尾。\n\n在构造函数中,我们遍历字符串数组 $words$,对于每个字符串 $w$,我们将其反转后,逐个字符插入到前缀树中,插入结束后,将当前节点的 `is_end` 标记为 `true`。\n\n在 `query` 函数中,我们将当前字符 $c$ 加入到字符流中,然后从后往前遍历字符流,对于每个字符 $c$,我们在前缀树中查找是否存在以 $c$ 为结尾的字符串,如果存在,返回 `true`,否则返回 `false`。注意到 $words$ 中的字符串长度不超过 $200$,因此查询时最多只需要遍历 $200$ 个字符。\n\n时间复杂度方面,构造函数的时间复杂度为 $O(L)$,而 `query` 函数的时间复杂度为 $O(M)$。其中 $L$ 为字符串数组 $words$ 中所有字符串的长度之和,而 $M$ 为字符串数组 $words$ 中字符串的最大长度。空间复杂度 $O(L)$。" }, "is_english": false, "time_complexity": "O(L)", "space_complexity": "O(L)" }, { "problem_id": 1033, "explanations": { "1": "我们先将 $a, b, c$ 排序,记为 $x, y, z$,即 $x \\lt y \\lt z$。\n\n接下来分情况讨论:\n\n1. 如果 $z - x \\leq 2$,说明 $3$ 个数已经相邻,不用移动,结果为 $[0, 0]$;\n1. 否则,如果 $y - x \\lt 3$,或者 $z - y \\lt 3$,说明有两个数只间隔一个位置,我们只需要把另一个数移动到这两个数的中间,最小移动次数为 $1$;其他情况,最小移动次数为 $2$;\n1. 最大移动次数就是两边的数字逐个往中间靠,最多移动 $z - x - 2$ 次。\n\n时间复杂度 $O(1)$,空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 1034, "explanations": { "1": "我们从位置 $(row, col)$ 出发,利用 DFS 搜索所有颜色为 $grid[row][col]$ 的网格块,如果该网格块的某个相邻位置的颜色不为 $grid[row][col]$,或者该网格块在网格的边界上,则将该网格块的颜色改为 $color$。\n\n时间复杂度 $O(m \\times n)$,空间复杂度 $O(m \\times n)$。其中 $m$ 和 $n$ 分别是网格的行数和列数。" }, "is_english": false, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 1035, "explanations": { "1": "We define $f[i][j]$ to represent the maximum number of connections between the first $i$ numbers of $\\textit{nums1}$ and the first $j$ numbers of $\\textit{nums2}$. Initially, $f[i][j] = 0$, and the answer is $f[m][n]$.\n\nWhen $\\textit{nums1}[i-1] = \\textit{nums2}[j-1]$, we can add a connection based on the first $i-1$ numbers of $\\textit{nums1}$ and the first $j-1$ numbers of $\\textit{nums2}$. In this case, $f[i][j] = f[i-1][j-1] + 1$.\n\nWhen $\\textit{nums1}[i-1] \\neq \\textit{nums2}[j-1]$, we either solve based on the first $i-1$ numbers of $\\textit{nums1}$ and the first $j$ numbers of $\\textit{nums2}$, or solve based on the first $i$ numbers of $\\textit{nums1}$ and the first $j-1$ numbers of $\\textit{nums2}$, taking the maximum of the two. That is, $f[i][j] = \\max(f[i-1][j], f[i][j-1])$.\n\nFinally, return $f[m][n]$.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the lengths of $\\textit{nums1}$ and $\\textit{nums2}$, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 1036, "explanations": { "1": "The problem can be interpreted as determining whether it is possible to move from a source point to a target point in a $10^6 \\times 10^6$ grid, given a small number of blocked points.\n\nSince the number of blocked points is small, the maximum area that can be blocked is no more than $|blocked|^2 / 2$. Therefore, we can perform a depth-first search (DFS) starting from both the source and the target points. The search continues until either the target point is reached or the number of visited points exceeds $|blocked|^2 / 2$. If either condition is satisfied, return $\\textit{true}$. Otherwise, return $\\textit{false}$.\n\nTime complexity is $O(m)$, and space complexity is $O(m)$, where $m$ is the size of the blocked region. In this problem, $m \\leq |blocked|^2 / 2 = 200^2 / 2 = 20000$." }, "is_english": true, "time_complexity": "O(m)", "space_complexity": "O(m)" }, { "problem_id": 1037, "explanations": { "1": "Let the three points be $(x_1, y_1)$, $(x_2, y_2)$, and $(x_3, y_3)$. The formula for calculating the slope between two points is $\\frac{y_2 - y_1}{x_2 - x_1}$.\n\nTo ensure that the three points are not collinear, the condition $\\frac{y_2 - y_1}{x_2 - x_1} \\neq \\frac{y_3 - y_2}{x_3 - x_2}$ must be satisfied. By transforming the equation, we get $(y_2 - y_1) \\cdot (x_3 - x_2) \\neq (y_3 - y_2) \\cdot (x_2 - x_1)$.\n\nNote:\n\n1. When the slope between two points does not exist, i.e., $x_1 = x_2$, the transformed equation still holds.\n2. If there are precision issues with division in slope comparison, it can be converted to multiplication.\n\nTime complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": null }, { "problem_id": 1038, "explanations": { "1": "Traverse the binary search tree in the order of \"right-root-left\". Accumulate all the node values encountered into $s$, and assign the accumulated value to the corresponding `node`.\n\nTime complexity is $O(n)$, and space complexity is $O(n)$, where $n$ is the number of nodes in the binary search tree.", "2": "Morris traversal does not require a stack, with a time complexity of $O(n)$ and a space complexity of $O(1)$. The core idea is as follows:\n\nDefine $s$ as the cumulative sum of the node values in the binary search tree. Traverse the binary tree nodes:\n\n1. If the right subtree of the current node `root` is null, **add the current node value to $s$**, update the current node value to $s$, and move the current node to `root.left`.\n2. If the right subtree of the current node `root` is not null, find the leftmost node `next` in the right subtree (i.e., the successor node of `root` in an in-order traversal):\n - If the left subtree of the successor node `next` is null, set the left subtree of `next` to point to the current node `root`, and move the current node to `root.right`.\n - If the left subtree of the successor node `next` is not null, **add the current node value to $s$**, update the current node value to $s$, then set the left subtree of `next` to null (i.e., remove the link between `next` and `root`), and move the current node to `root.left`.\n3. Repeat the above steps until the binary tree nodes are null, at which point the traversal is complete.\n4. Finally, return the root node of the binary search tree.\n\n> Morris reverse in-order traversal follows the same idea as Morris in-order traversal, except that the traversal order changes from \"left-root-right\" to \"right-root-left\"." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1039, "explanations": { "1": "We design a function $\\text{dfs}(i, j)$, which represents the minimum score after triangulating the polygon from vertex $i$ to $j$. The answer is $\\text{dfs}(0, n - 1)$.\n\nThe calculation process of $\\text{dfs}(i, j)$ is as follows:\n\n- If $i + 1 = j$, it means the polygon has only two vertices and cannot be triangulated, so we return $0$;\n- Otherwise, we enumerate a vertex $k$ between $i$ and $j$, i.e., $i \\lt k \\lt j$. Triangulating the polygon from vertex $i$ to $j$ can be divided into two subproblems: triangulating the polygon from vertex $i$ to $k$ and triangulating the polygon from vertex $k$ to $j$. The minimum scores of these two subproblems are $\\text{dfs}(i, k)$ and $\\text{dfs}(k, j)$, respectively. The score of the triangle formed by vertices $i$, $j$, and $k$ is $\\text{values}[i] \\times \\text{values}[k] \\times \\text{values}[j]$. Thus, the minimum score for this triangulation is $\\text{dfs}(i, k) + \\text{dfs}(k, j) + \\text{values}[i] \\times \\text{values}[k] \\times \\text{values}[j]$. We take the minimum value of all possibilities, which is the value of $\\text{dfs}(i, j)$.\n\nTo avoid repeated calculations, we can use memoization, i.e., use a hash table or an array to store the already computed function values.\n\nFinally, we return $\\text{dfs}(0, n - 1)$.\n\nThe time complexity is $O(n^3)$, and the space complexity is $O(n^2)$, where $n$ is the number of vertices in the polygon.", "2": "We can convert the memoization approach in Solution 1 into a dynamic programming approach.\n\nDefine $f[i][j]$ as the minimum score after triangulating the polygon from vertex $i$ to $j$. Initially, $f[i][j] = 0$, and the answer is $f[0][n-1]$.\n\nFor $f[i][j]$ (where $i + 1 \\lt j$), we first initialize $f[i][j]$ to $\\infty$.\n\nWe enumerate a vertex $k$ between $i$ and $j$, i.e., $i \\lt k \\lt j$. Triangulating the polygon from vertex $i$ to $j$ can be divided into two subproblems: triangulating the polygon from vertex $i$ to $k$ and triangulating the polygon from vertex $k$ to $j$. The minimum scores of these two subproblems are $f[i][k]$ and $f[k][j]$, respectively. The score of the triangle formed by vertices $i$, $j$, and $k$ is $\\text{values}[i] \\times \\text{values}[k] \\times \\text{values}[j]$. Thus, the minimum score for this triangulation is $f[i][k] + f[k][j] + \\text{values}[i] \\times \\text{values}[k] \\times \\text{values}[j]$. We take the minimum value of all possibilities, which becomes the value of $f[i][j]$.\n\nIn summary, we can derive the state transition equation:\n\n$$\nf[i][j]=\n\\begin{cases}\n0, & i+1=j \\\\\n\\infty, & i+1 arr[i]$, then $arr[i - 1]$ is the number we need to swap. Next, we traverse the array from right to left again, find the first index $j$ that satisfies $arr[j] < arr[i - 1]$ and $arr[j] \\neq arr[j - 1]$. Now, we swap $arr[i - 1]$ and $arr[j]$ and return the array.\n\nIf we traverse the entire array and do not find an index $i$ that meets the conditions, it means the array is already the smallest permutation, so we just return the original array.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1054, "explanations": { "1": "First, we use a hash table or array $cnt$ to count the number of occurrences of each number in the array $barcodes$. Then, we sort the numbers in $barcodes$ according to their occurrence times in $cnt$ from large to small. If the occurrence times are the same, we sort them from small to large (to ensure the same numbers are adjacent).\n\nNext, we create an answer array $ans$ of length $n$. We traverse the sorted $barcodes$, and sequentially fill the elements into the even index positions $0, 2, 4, \\cdots$ of the answer array. Then, we fill the remaining elements into the odd index positions $1, 3, 5, \\cdots$ of the answer array.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(M)$. Where $n$ and $M$ are the length of the array $barcodes$ and the maximum value in the array $barcodes$, respectively." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(M)" }, { "problem_id": 1055, "explanations": { "1": "We can use the two pointers method, where pointer $j$ points to the target string `target`. Then we traverse the source string `source` with pointer $i$ pointing to the source string `source`. If $source[i] = target[j]$, then both $i$ and $j$ move one step forward, otherwise only pointer $i$ moves. When both pointers $i$ and $j$ reach the end of the string, if no equal character is found, return $-1$, otherwise the subsequence count increases by one, and then set pointer $i$ to $0$ and continue to traverse.\n\nAfter the traversal ends, return the subsequence count.\n\nThe time complexity is $O(m \\times n)$, where $m$ and $n$ are the lengths of the strings `source` and `target` respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(1)" }, { "problem_id": 1056, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1057, "explanations": { "1": "先计算每个工人和每个自行车之间的曼哈顿距离,然后按照曼哈顿距离从小到大排序,遍历排序后的数组,如果当前工人和自行车都未被分配,则分配给当前工人和自行车。\n\n时间复杂度 $O(n\\times m\\times \\log (n\\times m))$。其中 $n$ 和 $m$ 分别为工人和自行车的数量。" }, "is_english": false, "time_complexity": "O(n\\times m\\times \\log (n\\times m))", "space_complexity": null }, { "problem_id": 1058, "explanations": { "1": "遍历价格数组 `prices`,先将每个价格 $p$ 向下舍入,累加到 `mi` 中,同时将每个价格的小数点部分添加到数组 `arr` 中。\n\n遍历结束后,判断 `target` 是否在 `mi` 和 `mi + arr.length` 之间,如果不在,直接返回 `\"-1\"`。\n\n接下来,我们计算 `target - mi`,即需要向上入的价格个数,然后将 `arr` 从大到小排序,从前往后遍历,将前 `target - mi` 个价格向上入,其余价格向下舍入,累计到 `ans` 中。\n\n时间复杂度 $O(n\\log n)$。其中 $n$ 为 `prices` 的长度。" }, "is_english": false, "time_complexity": "O(n\\log n)", "space_complexity": null }, { "problem_id": 1059, "explanations": { "1": "We use a state array $\\textit{state}$ to record the status of each node, where:\n\n- State 0 indicates the node has not been visited;\n- State 1 indicates the node is currently being visited;\n- State 2 indicates the node has been visited and can lead to the destination.\n\nFirst, we build the graph as an adjacency list, then perform a depth-first search (DFS) starting from the source node. During the DFS process:\n\n- If the current node's state is 1, it means we have encountered a cycle, and we return $\\text{false}$ directly;\n- If the current node's state is 2, it means the node has been visited and can lead to the destination, and we return $\\text{true}$ directly;\n- If the current node has no outgoing edges, we check whether it is the destination node. If so, return $\\text{true}$; otherwise, return $\\text{false}$;\n- Otherwise, set the current node's state to 1 and recursively visit all adjacent nodes;\n- If all adjacent nodes can lead to the destination, set the current node's state to 2 and return $\\text{true}$; otherwise, return $\\text{false}$.\n\nThe answer is the result of $\\text{dfs}(\\text{source})$.\n\nThe time complexity is $O(n + m)$, where $n$ and $m$ are the number of nodes and edges, respectively. The space complexity is $O(n + m)$, used to store the graph's adjacency list and state array." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(n + m)" }, { "problem_id": 1060, "explanations": { "1": "我们设计一个函数 $missing(i)$,表示 $nums[i]$ 与 $nums[0]$ 之间缺失的元素个数。那么 $missing(i)$ 就等于 $nums[i] - nums[0] - i$。我们可以通过二分查找找到最小的 $i$,使得 $missing(i) \\geq k$,那么 $nums[i - 1] + k - missing(i - 1)$ 就是第 $k$ 个缺失的元素。\n\n时间复杂度 $O(\\log n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 $nums$ 的长度。" }, "is_english": false, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 1061, "explanations": { "1": "We can use Union Find (Disjoint Set Union, DSU) to handle the equivalence relations between characters. Each character can be regarded as a node, and the equivalence relations can be seen as edges connecting these nodes. With Union Find, we can group all equivalent characters together and quickly find the representative element for each character during queries. When performing union operations, we always set the representative element to be the lexicographically smallest character. This ensures that the final string is the lexicographically smallest equivalent string.\n\nThe time complexity is $O((n + m) \\times \\log |\\Sigma|)$ and the space complexity is $O(|\\Sigma|)$, where $n$ is the length of strings $s1$ and $s2$, $m$ is the length of $baseStr$, and $|\\Sigma|$ is the size of the character set, which is $26$ in this problem." }, "is_english": true, "time_complexity": "O((n + m) \\times \\log |\\Sigma|)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 1062, "explanations": { "1": "We define $f[i][j]$ to represent the length of the longest repeating substring ending with $s[i]$ and $s[j]$. Initially, $f[i][j]=0$.\n\nWe enumerate $i$ in the range $[1, n)$ and enumerate $j$ in the range $[0, i)$. If $s[i]=s[j]$, then we have:\n\n$$\nf[i][j]=\n\\begin{cases}\nf[i-1][j-1]+1, & j>0 \\\\\n1, & j=0\n\\end{cases}\n$$\n\nThe answer is the maximum value of all $f[i][j]$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Where $n$ is the length of the string $s$.\n\nSimilar problems:\n\n- [1044. Longest Duplicate Substring 🔒](https://github.com/doocs/leetcode/blob/main/solution/1000-1099/1044.Longest%20Duplicate%20Substring/README_EN.md)" }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 1063, "explanations": { "1": "题目实际上是求解每个位置 $i$ 的右边第一个小于 $nums[i]$ 的位置 $j$,那么以 $i$ 为左端点的有效子数组的个数就是 $j - i$。\n\n我们可以使用单调栈来求解右边第一个小于 $nums[i]$ 的位置 $j$,具体做法是从右往左遍历数组,维护一个从栈顶到栈底严格单调递减的栈。如果栈不为空,并且栈顶元素大于等于 $nums[i]$,那么就将栈顶元素出栈,直到栈为空或者栈顶元素小于 $nums[i]$,此时栈顶元素就是右边第一个小于 $nums[i]$ 的位置 $j$,如果栈为空,那么 $j = n$。\n\n接下来,我们将 $i$ 入栈,继续遍历数组,直到遍历结束,最后我们就可以得到每个位置 $i$ 的右边第一个小于 $nums[i]$ 的位置 $j$,从而得到以 $i$ 为左端点的有效子数组的个数 $j-i$,将所有的 $j-i$ 累加即可得到答案。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是数组的长度。", "2": "" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1064, "explanations": { "1": "题目给定的数组是按升序排列的,因此我们可以使用二分查找的方法找出最小的满足 $arr[i]$ 等于 $i$ 的下标 $i$。\n\n我们定义二分查找的左边界 $left=0$,右边界 $right=n-1$。每一次,我们找到当前的中间位置 $mid$,如果中间位置满足 $arr[mid] \\geq mid$,那么我们就确定了最小的不动点 🔒 的位置一定不会出现在下标大于 $mid$ 的位置,因此我们令 $right=mid$;如果中间位置满足 $arr[mid] \\lt mid$,那么最小的不动点 🔒 一定出现在下标大于 $mid$ 的位置,因此我们令 $left=mid+1$。\n\n最后,如果我们没有找到最小的不动点 🔒,那么我们返回 $-1$。\n\n时间复杂度 $O(\\log n)$,其中 $n$ 是数组的长度。空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 1065, "explanations": { "1": "", "2": "相似题目:\n\n- [616. 给字符串添加加粗标签](https://github.com/doocs/leetcode/blob/main/solution/0600-0699/0616.Add%20Bold%20Tag%20in%20String/README.md)\n- [758. 字符串中的加粗单词](https://github.com/doocs/leetcode/blob/main/solution/0700-0799/0758.Bold%20Words%20in%20String/README.md)" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1066, "explanations": { "1": "我们定义 $f[i][j]$ 表示前 $i$ 个工人分配到自行车的状态为 $j$ 时的最小曼哈顿距离总和,其中 $j$ 是一个二进制数,表示自行车的分配情况。初始时 $f[0][0]=0$,其余 $f[0][j]=+\\infty$。\n\n考虑 $f[i][j]$,我们枚举第 $i$ 个工人分配到的自行车的编号 $k$,那么 $f[i][j]$ 可以从 $f[i-1][j\\oplus 2^k]$ 转移而来,其中 $\\oplus$ 表示异或运算。这是因为 $f[i-1][j\\oplus 2^k]$ 表示前 $i-1$ 个工人分配到自行车的状态为 $j\\oplus 2^k$ 时的最小曼哈顿距离总和,而第 $i$ 个工人分配到自行车 $k$ 时,其曼哈顿距离为 $|worker[i]-bike[k]|$,其中 $|x|$ 表示 $x$ 的绝对值。因此我们可以列出状态转移方程:\n\n$$\nf[i][j]=\\min_{k=0}^{m-1}\\{f[i-1][j\\oplus 2^k]+|worker[i]-bike[k]|\\}\n$$\n\n最终的答案为 $\\min_{j=0}^{2^m-1}\\{f[n][j]\\}$。\n\n时间复杂度 $O(n \\times 2^m \\times m)$,空间复杂度 $O(n \\times 2^m)$。其中 $n$ 和 $m$ 分别是工人和自行车的数量。" }, "is_english": false, "time_complexity": "O(n \\times 2^m \\times m)", "space_complexity": "O(n \\times 2^m)" }, { "problem_id": 1067, "explanations": { "1": "这道题实际上是求在给定区间 $[l,..r]$ 中,数字中出现 $d$ 的个数。个数与数的位数以及每一位上的数字有关。我们可以用数位 DP 的思路来解决这道题。数位 DP 中,数的大小对复杂度的影响很小。\n\n对于区间 $[l,..r]$ 问题,我们一般会将其转化为 $[1,..r]$ 然后再减去 $[1,..l - 1]$ 的问题,即:\n\n$$\nans = \\sum_{i=1}^{r} ans_i - \\sum_{i=1}^{l-1} ans_i\n$$\n\n这里我们用记忆化搜索来实现数位 DP。从起点向下搜索,到最底层得到方案数,一层层向上返回答案并累加,最后从搜索起点得到最终的答案。\n\n基本步骤如下:\n\n1. 将数字 $n$ 转为 int 数组 $a$,其中 $a[1]$ 为最低位,而 $a[len]$ 为最高位;\n1. 根据题目信息,设计函数 $dfs()$,对于本题,我们定义 $dfs(pos, cnt, lead, limit)$,答案为 $dfs(len, 0, true, true)$。\n\n其中:\n\n- `pos` 表示数字的位数,从末位或者第一位开始,一般根据题目的数字构造性质来选择顺序。对于本题,我们选择从高位开始,因此,`pos` 的初始值为 `len`;\n- `cnt` 表示当前数字中包含 $d$ 的个数;\n- `lead` 表示当前数字是否有前导零,如果有前导零,则 `lead` 为 `true`,否则为 `false`,初始化为 `true`;\n- `limit` 表示可填的数字的限制,如果无限制,那么可以选择 $[0,1,..9]$,否则,只能选择 $[0,..a[pos]]$。如果 `limit` 为 `true` 且已经取到了能取到的最大值,那么下一个 `limit` 同样为 `true`;如果 `limit` 为 `true` 但是还没有取到最大值,或者 `limit` 为 `false`,那么下一个 `limit` 为 `false`。\n\n关于函数的实现细节,可以参考下面的代码。\n\n时间复杂度 $O(\\log m + \\log n)$。其中 $m$, $n$ 分别为题目中的 `low` 和 `high`。\n\n相似题目:\n\n- [233. 数字 1 的个数](https://github.com/doocs/leetcode/blob/main/solution/0200-0299/0233.Number%20of%20Digit%20One/README.md)" }, "is_english": false, "time_complexity": "O(\\log m + \\log n)", "space_complexity": null }, { "problem_id": 1068, "explanations": { "1": "我们直接使用 `JOIN` 连接 `Sales` 和 `Product` 两张表,连接字段为 `product_id`,然后选择需要的字段即可。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1069, "explanations": { "1": "我们可以使用 `GROUP BY`,按照 `product_id` 分组,然后每一组对 `quantity` 求和。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1070, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1071, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1072, "explanations": { "1": "我们观察发现,如果矩阵中的两行满足以下条件之一,则它们可以通过翻转某些列的方式得到相等的行:\n\n1. 两行的对应位置元素相等,即如果其中一行元素为 $1,0,0,1$,则另一行元素也为 $1,0,0,1$;\n1. 两行的对应位置元素相反,即如果其中一行元素为 $1,0,0,1$,则另一行元素为 $0,1,1,0$。\n\n我们称满足以上条件之一的两行元素为“等价行”,那么题目所求的答案即为矩阵中最多包含等价行的行数。\n\n因此,我们可以遍历矩阵的每一行,将每一行转换成第一个元素为 $0$ 的“等价行”。具体做法如下:\n\n- 如果当前行的第一个元素为 $0$,那么当前行的元素保持不变;\n- 如果当前行的第一个元素为 $1$,那么我们将当前行的每个元素进行翻转,即 $0$ 变成 $1$, $1$ 变成 $0$。也就是说,我们将以 $1$ 开头的行翻转成以 $0$ 开头的“等价行”。\n\n这样一来,我们只需要用一个哈希表来统计转换后的每一行的出现次数,其中键为转换后的行(可以将所有数字拼接成一个字符串),值为该行出现的次数。最后,哈希表中值的最大值即为矩阵中最多包含等价行的行数。\n\n时间复杂度 $O(m \\times n)$,空间复杂度 $O(m)$。其中 $m$ 和 $n$ 分别是矩阵的行数和列数。\n\n相似题目:\n\n- [2128. 通过翻转行或列来去除所有的 1](https://github.com/doocs/leetcode/blob/main/solution/2100-2199/2128.Remove%20All%20Ones%20With%20Row%20and%20Column%20Flips/README.md)" }, "is_english": false, "time_complexity": "O(m \\times n)", "space_complexity": "O(m)" }, { "problem_id": 1073, "explanations": { "1": "我们遍历两个数组,从最低位开始,记两个数组当前位的数字为 $a$ 和 $b$,进位为 $c$,三个数相加的结果为 $x$。\n\n- 先将进位 $c$ 置为 $0$。\n- 如果 $x \\geq 2$,由于 $(-2)^{i} + (-2)^{i} = -(-2)^{i+1}$,所以我们可以将 $x$ 减去 $2$,并向高位进位 $-1$。\n- 如果 $x = -1$,由于 $-(-2)^{i} = (-2)^{i} + (-2)^{i+1}$,所以我们可以将 $x$ 置为 $1$,并向高位进位 $1$。\n\n然后,我们将 $x$ 加入到答案数组中,然后继续处理下一位。\n\n遍历结束后,去除答案数组中末尾的 $0$,并将数组反转,即可得到最终的答案。\n\n时间复杂度 $O(\\max(n, m))$,其中 $n$ 和 $m$ 分别是两个数组的长度。忽略答案的空间消耗,空间复杂度 $O(1)$。\n\n相似题目:\n\n- [1017. 负二进制转换](https://github.com/doocs/leetcode/blob/main/solution/1000-1099/1017.Convert%20to%20Base%20-2/README.md)" }, "is_english": false, "time_complexity": "O(\\max(n, m))", "space_complexity": "O(1)" }, { "problem_id": 1074, "explanations": { "1": "我们可以枚举矩阵的上下边界 $i$ 和 $j$,每次算出当前上下边界内每列的元素和,记为数组 $col$,然后问题就转换为如何在数组 $col$ 中寻找和为目标值 $target$ 的子数组个数。我们累加这些子数组的个数,就是题目要求的答案。\n\n那么题目就变成了:给定一个数组 $nums$ 和目标值 $target$,计算有多少个子数组的和为 $target$,我们可以通过函数 $f(nums, target)$ 来求解。\n\n函数 $f(nums, target)$ 的计算方法如下:\n\n- 定义一个哈希表 $d$,用来记录出现过的前缀和以及其出现次数,初始时 $d[0] = 1$;\n- 初始化变量 $s = 0, cnt = 0$,其中 $s$ 表示前缀和,而 $cnt$ 表示和为 $target$ 的子数组个数;\n- 从左到右遍历数组 $nums$,对于当前遍历到的元素 $x$,更新前缀和 $s = s + x$,如果 $d[s - target]$ 的值存在,那么更新 $cnt = cnt + d[s - target]$,即子数组个数增加 $d[s - target]$。然后更新哈希表中元素 $d[s]$ 的值,即 $d[s] = d[s] + 1$;继续遍历下一个元素;\n- 遍历结束之后,返回子数组个数 $cnt$。\n\n时间复杂度 $O(m^2 \\times n)$,空间复杂度 $O(n)$。其中 $m$ 和 $n$ 分别是矩阵的行数和列数。" }, "is_english": false, "time_complexity": "O(m^2 \\times n)", "space_complexity": "O(n)" }, { "problem_id": 1075, "explanations": { "1": "我们可以通过内连接将两张表连接起来,然后通过 `GROUP BY` 分组,最后使用 `AVG` 函数求工作年限的平均值。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1076, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1077, "explanations": { "1": "We can first perform an inner join between the `Project` table and the `Employee` table, and then use the window function `rank()` to group the `Project` table, sort it in descending order by `experience_years`, and finally select the most experienced employee for each project." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1078, "explanations": { "1": "我们可以将字符串 $text$ 按照空格分割成字符串数组 $words$,然后遍历 $words$,如果 $words[i]$ 和 $words[i+1]$ 分别等于 $first$ 和 $second$,那么就将 $words[i+2]$ 添加到答案中。\n\n遍历结束后,返回答案列表。\n\n时间复杂度 $O(L)$,空间复杂度 $O(L)$,其中 $L$ 是 $text$ 的长度。" }, "is_english": false, "time_complexity": "O(L)", "space_complexity": "O(L)" }, { "problem_id": 1079, "explanations": { "1": "我们先用一个哈希表或数组 $cnt$ 统计每个字母出现的次数。\n\n接下来定义一个函数 $dfs(cnt)$,表示当前剩余字母的计数为 $cnt$ 时,能够组成的不同序列的个数。\n\n在 $dfs$ 中,我们枚举 $cnt$ 中每个大于 $0$ 的值 $cnt[i]$,将 $cnt[i]$ 减 $1$ 表示使用了这个字母,序列个数加 $1$,然后进行下一层搜索,在搜索结束后,累加返回的序列个数,然后将 $cnt[i]$ 加 $1$。最后返回序列个数。\n\n时间复杂度 $O(n \\times n!)$,空间复杂度 $O(n)$。其中 $n$ 为字母种类数。" }, "is_english": false, "time_complexity": "O(n \\times n!)", "space_complexity": "O(n)" }, { "problem_id": 1080, "explanations": { "1": "我们递归遍历整棵树,对于当前遍历到的节点 $root$:\n\n如果 $root$ 为空,那么返回空;否则,我们将 $limit$ 减去当前节点的值,即 $limit = limit - root.val$,然后继续执行下述步骤。\n\n如果 $root$ 为叶子节点(即 $root$ 的左右子节点都为空),说明我们已经走完了一条从根节点到叶子节点的路径。如果此时 $limit \\gt 0$,说明该路径上所有节点的值的和小于 $limit$,我们返回空节点,表示删除;否则,说明该路径上所有节点的值的和大于等于 $limit$,我们返回 $root$。\n\n如果 $root$ 不是叶子节点,那么我们递归调用函数 $sufficientSubset$,对 $root$ 的左右子节点分别进行处理,并将返回值分别赋值给 $root$ 的左右子节点。\n\n如果 $root$ 的左右子节点在经过递归调用后变成了空节点,那么说明 $root$ 的左右子树中所有从根节点到叶子节点的路径上所有节点的值的和都小于 $limit$,因此我们返回空节点,表示删除 $root$;否则,说明 $root$ 的左右子树中存在从根节点到叶子节点上所有节点值的和大于等于 $limit$ 的路径,因此我们返回 $root$。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点个数。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1081, "explanations": { "1": "我们用一个数组 $last$ 记录字符串 $s$ 每个字符最后一次出现的位置,用栈来保存结果字符串,用一个数组 $vis$ 或者一个整型变量 $mask$ 记录当前字符是否在栈中。\n\n遍历字符串 $s$,对于每个字符 $c$,如果 $c$ 不在栈中,我们就需要判断栈顶元素是否大于 $c$,如果大于 $c$,且栈顶元素在后面还会出现,我们就将栈顶元素弹出,将 $c$ 压入栈中。\n\n最后将栈中元素拼接成字符串作为结果返回。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是字符串 $s$ 的长度。", "2": "" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1082, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1083, "explanations": { "1": "我们先将 `Sales` 表和 `Product` 表连接起来,然后根据 `buyer_id` 分组,最后用 `HAVING` 子句筛选出购买了 S8 却没有购买 iPhone 的买家。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1084, "explanations": { "1": "我们可以通过 `JOIN` 将 `Sales` 表和 `Product` 表连接起来,然后通过 `GROUP BY` 和 `HAVING` 来筛选出符合条件的产品。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1085, "explanations": { "1": "我们先找到数组中的最小值,记为 $x$。然后计算 $x$ 的各个数位上的数字之和,记为 $s$。最后判断 $s$ 是否为奇数,若是则返回 $0$,否则返回 $1$。\n\n时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组的长度。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1086, "explanations": { "1": "我们先用一个哈希表或数组 $d$ 记录每个学生的分数列表,然后从小到大遍历学生的编号,对于每个学生,我们将他的分数列表排序,然后取最高的五个分数求平均值即可。\n\n时间复杂度 $O(n \\log n)$,空间复杂度 $O(n)$。其中 $n$ 是学生的数量。" }, "is_english": false, "time_complexity": "O(n \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1087, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1088, "explanations": { "1": "我们先将数字 $n$ 转成字符串 $s$。\n\n接下来,我们定义一个函数 $check(x)$,用来判断 $x$ 在旋转 $180^\\circ$ 之后是否变成了一个不同的数。如果 $x$ 在旋转 $180^\\circ$ 之后变成了一个不同的数,那么我们就称 $x$ 是一个易混淆数。\n\n然后,我们定义另一个函数 $dfs(pos, limit, x)$,用于搜索从高位到低位的每一位。其中:\n\n- 参数 $pos$ 表示当前搜索到的位置,初始时为 $0$;\n- 参数 $limit$ 表示当前搜索的数是否受到上界的限制,初始时为 $true$;\n- 参数 $x$ 表示当前搜索的数,初始时为 $0$。\n\n在 $dfs(pos, limit, x)$ 中,如果 $pos \\geq len(s)$,那么我们就判断 $x$ 是否是一个易混淆数,如果是则返回 $1$,否则返回 $0$。\n\n否则,我们计算出当前位置上的数字的上界 $up$,然后枚举当前位置上的数字 $i$,如果 $i$ 在旋转 $180^\\circ$ 之后不是一个数字,那么我们就直接跳过这个数字。否则,我们将 $x$ 更新为 $x \\times 10 + i$,并根据 $limit$ 的值决定下一步搜索的时候是否受到上界的限制,最后将答案返回。\n\n最终的答案即为 $dfs(0, true, 0)$。\n\n时间复杂度 $O(5^{\\log_{10}n})$,空间复杂度 $O(\\log_{10}n)$。其中 $5^{\\log_{10}n}$ 表示 $n$ 的位数。" }, "is_english": false, "time_complexity": "O(5^{\\log_{10}n})", "space_complexity": "O(\\log_{10}n)" }, { "problem_id": 1089, "explanations": { "1": "开辟一个等长数组,将 `arr` 复刻一份,再进行简单模拟即可。\n\n- 时间复杂度:$O(n)$。\n- 空间复杂度:$O(n)$。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1090, "explanations": { "1": "根据题目描述,我们需要从 $n$ 个元素的集合中选出一个子集,子集元素个数不超过 $numWanted$,且子集中最多有相同标签的 $useLimit$ 项,使得子集的值之和最大。因此,我们应该贪心地选择集合中值较大的元素,同时记录每个标签出现的次数,当某个标签出现的次数达到 $useLimit$ 时,我们就不能再选择该标签对应的元素了。\n\n具体地,我们先将集合中的元素按照值从大到小进行排序,然后从前向后遍历排序后的元素。在遍历的过程中,我们使用一个哈希表 $cnt$ 记录每个标签出现的次数,如果某个标签出现的次数达到了 $useLimit$,那么我们就跳过该元素,否则我们就将该元素的值加到最终的答案中,并将该标签出现的次数加 $1$。同时,我们用一个变量 $num$ 记录当前子集中的元素个数,当 $num$ 达到 $numWanted$ 时,我们就可以结束遍历了。\n\n遍历结束后,我们就得到了最大的分数。\n\n时间复杂度 $O(n \\times \\log n)$,空间复杂度 $O(n)$。其中 $n$ 是集合中的元素个数。" }, "is_english": false, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1091, "explanations": { "1": "根据题目描述,一条畅通路径是从左上角单元格 $(0, 0)$ 到右下角单元格 $(n - 1, n - 1)$ 的路径,且路径上所有单元格的值都是 $0$。\n\n因此,如果左上角单元格 $(0, 0)$ 的值为 $1$,则不存在满足要求的路径,直接返回 $-1$。\n\n否则,我们创建一个队列 $q$,将左上角单元格 $(0, 0)$ 加入队列,并且将其标记为已访问,即把 $grid[0][0]$ 的值置为 $1$,然后开始广度优先搜索。\n\n在每一轮搜索中,我们每次取出队首节点 $(i, j)$,如果 $(i, j)$ 为右下角单元格 $(n - 1, n - 1)$,则路径长度为当前的搜索轮数,直接返回。否则,我们将当前节点的所有未被访问过的相邻节点加入队列,并且将它们标记为已访问。每一轮搜索结束后,我们将搜索轮数增加 $1$。然后继续执行上述过程,直到队列为空或者找到目标节点。\n\n如果在搜索结束后,我们仍然没有到达右下角的节点,那么说明右下角的节点不可达,返回 $-1$。\n\n时间复杂度 $O(n^2)$,空间复杂度 $O(n^2)$。其中 $n$ 是给定的二进制矩阵的边长。" }, "is_english": false, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 1092, "explanations": { "1": "我们先用动态规划求出两个字符串的最长公共子序列,然后根据最长公共子序列构造出最短公共超序列。\n\n定义 $f[i][j]$ 表示字符串 $str1$ 的前 $i$ 个字符和字符串 $str2$ 的前 $j$ 个字符的最长公共子序列的长度。状态转移方程如下:\n\n$$\nf[i][j] =\n\\begin{cases}\n0 & i = 0 \\textit{ or } j = 0 \\\\\nf[i - 1][j - 1] + 1 & str1[i - 1] = str2[j - 1] \\\\\n\\max(f[i - 1][j], f[i][j - 1]) & str1[i - 1] \\neq str2[j - 1]\n\\end{cases}\n$$\n\n接下来我们基于 $f[i][j]$ 构造出最短公共超序列。\n\n```bash\nstr1: a b a c\n\nstr2: c a b\n\nans: c a b a c\n```\n\n不妨对照着上面的示例字符串,来看看如何构造出最短公共超序列。\n\n我们用双指针 $i$ 和 $j$ 分别指向字符串 $str1$ 和 $str2$ 的末尾,然后从后往前遍历,每次比较 $str1[i]$ 和 $str2[j]$ 的值:\n\n- 如果 $str1[i] = str2[j]$,则将 $str1[i]$ 或 $str2[j]$ 中的任意一个字符加入到最答案序列的末尾,然后 $i$ 和 $j$ 同时减 $1$;\n- 如果 $str1[i] \\neq str2[j]$,则将 $f[i][j]$ 与 $f[i - 1][j]$ 和 $f[i][j - 1]$ 中的最大值进行比较:\n - 如果 $f[i][j] = f[i - 1][j]$,则将 $str1[i]$ 加入到答案序列的末尾,然后 $i$ 减 $1$;\n - 如果 $f[i][j] = f[i][j - 1]$,则将 $str2[j]$ 加入到答案序列的末尾,然后 $j$ 减 $1$。\n\n重复上述操作,直到 $i = 0$ 或 $j = 0$,然后将剩余的字符串加入到答案序列的末尾即可。\n\n最后我们将答案序列反转,即可得到最终的答案。\n\n时间复杂度 $O(m\\times n)$,空间复杂度 $O(m\\times n)$。其中 $m$ 和 $n$ 分别是字符串 $str1$ 和 $str2$ 的长度。" }, "is_english": false, "time_complexity": "O(m\\times n)", "space_complexity": "O(m\\times n)" }, { "problem_id": 1093, "explanations": { "1": "我们直接根据题目描述模拟即可,定义以下变量:\n\n- 变量 $mi$ 表示最小值;\n- 变量 $mx$ 表示最大值;\n- 变量 $s$ 表示总和;\n- 变量 $cnt$ 表示总个数;\n- 变量 $mode$ 表示众数。\n\n我们遍历数组 $count$,对于当前遍历到的数字 $count[k]$,如果 $count[k] \\gt 0$,那么我们做以下更新操作:\n\n- 更新 $mi = \\min(mi, k)$;\n- 更新 $mx = \\max(mx, k)$;\n- 更新 $s = s + k \\times count[k]$;\n- 更新 $cnt = cnt + count[k]$;\n- 如果 $count[k] \\gt count[mode]$,那么更新 $mode = k$。\n\n遍历结束后,我们再根据 $cnt$ 的奇偶性来计算中位数 $median$,如果 $cnt$ 是奇数,那么中位数就是第 $\\lfloor \\frac{cnt}{2} \\rfloor + 1$ 个数字,如果 $cnt$ 是偶数,那么中位数就是第 $\\lfloor \\frac{cnt}{2} \\rfloor$ 和第 $\\lfloor \\frac{cnt}{2} \\rfloor + 1$ 个数字的平均值。\n\n> 这里我们通过一个简单的辅助函数 $find(i)$ 来找到第 $i$ 个数字,具体实现可以参考下面的代码。\n\n最后,我们将 $mi, mx, \\frac{s}{cnt}, median, mode$ 放入答案数组中返回即可。\n\n时间复杂度 $O(n)$,其中 $n$ 是数组 $count$ 的长度。空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1094, "explanations": { "1": "We can use the idea of a difference array, adding the number of passengers to the starting point of each trip and subtracting from the end point. Finally, we just need to check whether the prefix sum of the difference array does not exceed the maximum passenger capacity of the car.\n\nThe time complexity is $O(n)$, and the space complexity is $O(M)$. Here, $n$ is the number of trips, and $M$ is the maximum end point in the trips. In this problem, $M \\le 1000$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(M)" }, { "problem_id": 1095, "explanations": { "1": "我们先通过二分查找,找到数组中的最大值所在的下标 $l$,那么数组就可以被分成两段,前半段是递增的,后半段是递减的。\n\n然后我们在前半段中使用二分查找,查找目标值所在的下标,如果找不到,再在后半段中使用二分查找,查找目标值所在的下标。\n\n时间复杂度 $O(\\log n)$,其中 $n$ 是数组的长度。空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 1096, "explanations": { "1": "我们设计一个递归函数 $dfs(exp)$,用于处理表达式 $exp$,并将结果存入集合 $s$ 中。\n\n对于表达式 $exp$,我们首先找到第一个右花括号的位置 $j$,如果找不到,说明 $exp$ 中没有右花括号,即 $exp$ 为单一元素,直接将 $exp$ 加入集合 $s$ 中即可。\n\n否则,我们从位置 $j$ 开始往左找到第一个左花括号的位置 $i$,此时 $exp[:i]$ 和 $exp[j + 1:]$ 分别为 $exp$ 的前缀和后缀,记为 $a$ 和 $c$。而 $exp[i + 1: j]$ 为 $exp$ 中花括号内的部分,即 $exp$ 中的子表达式,我们将其按照逗号分割成多个字符串 $b_1, b_2, \\cdots, b_k$,然后对每个 $b_i$,我们将 $a + b_i + c$ 拼接成新的表达式,递归调用 $dfs$ 函数处理新的表达式,即 $dfs(a + b_i + c)$。\n\n最后,我们将集合 $s$ 中的元素按照字典序排序,即可得到答案。\n\n时间复杂度约为 $O(n \\times 2^{n / 4})$,其中 $n$ 为表达式 $expression$ 的长度。" }, "is_english": false, "time_complexity": "O(n \\times 2^{n / 4})", "space_complexity": null }, { "problem_id": 1097, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1098, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1099, "explanations": { "1": "We can first sort the array $nums$, and initialize the answer as $-1$.\n\nNext, we enumerate each element $nums[i]$ in the array, and find the maximum $nums[j]$ in the array that satisfies $nums[j] + nums[i] < k$. Here, we can use binary search to speed up the search process. If we find such a $nums[j]$, then we can update the answer, i.e., $ans = \\max(ans, nums[i] + nums[j])$.\n\nAfter the enumeration ends, return the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array $nums$.", "2": "Similar to Solution 1, we can first sort the array $nums$, and initialize the answer as $-1$.\n\nNext, we use two pointers $i$ and $j$ to point to the left and right ends of the array, respectively. Each time we judge whether $s = nums[i] + nums[j]$ is less than $k$. If it is less than $k$, then we can update the answer, i.e., $ans = \\max(ans, s)$, and move $i$ one step to the right, otherwise move $j$ one step to the left.\n\nAfter the enumeration ends, return the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 1100, "explanations": { "1": "We maintain a sliding window of length $k$, and use a hash table $cnt$ to count the occurrences of each character in the window.\n\nFirst, we add the first $k$ characters of the string $s$ to the hash table $cnt$, and check whether the size of $cnt$ is equal to $k$. If it is, it means that all characters in the window are different, and the answer $ans$ is incremented by one.\n\nNext, we start to traverse the string $s$ from $k$. Each time we add $s[i]$ to the hash table $cnt$, and at the same time subtract $s[i-k]$ from the hash table $cnt$ by one. If $cnt[s[i-k]]$ is equal to $0$ after subtraction, we remove $s[i-k]$ from the hash table $cnt$. If the size of the hash table $cnt$ is equal to $k$ at this time, it means that all characters in the window are different, and the answer $ans$ is incremented by one.\n\nFinally, return the answer $ans$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(\\min(k, |\\Sigma|))$, where $n$ is the length of the string $s$; and $\\Sigma$ is the character set, in this problem the character set is lowercase English letters, so $|\\Sigma| = 26$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(\\min(k, |\\Sigma|))" }, { "problem_id": 1101, "explanations": { "1": "We sort all the logs in ascending order by timestamp, then traverse the sorted logs. Using a union-find set, we check whether the two people in the current log are already friends. If they are not friends, we merge them into one friend circle, until everyone is in one friend circle, then return the timestamp of the current log.\n\nIf we have traversed all the logs and not everyone is in one friend circle, then return $-1$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the number of logs.", "2": "" }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1102, "explanations": { "1": "First, we construct a triplet $(v, i, j)$ for each element in the matrix, where $v$ represents the element value, and $i$ and $j$ represent the row and column of the element in the matrix, respectively. Then we sort these triplets in descending order by element value and store them in a list $q$.\n\nNext, we take out the triplets from $q$ in order, use the corresponding element value as the score of the path, and mark the position as visited. Then we check the four adjacent positions (up, down, left, and right) of this position. If an adjacent position has been visited, we merge this position with the current position. If we find that the position $(0, 0)$ and the position $(m - 1, n - 1)$ have been merged, we can directly return the score of the current path as the answer.\n\nThe time complexity is $O(m \\times n \\times (\\log (m \\times n) + \\alpha(m \\times n)))$, where $m$ and $n$ are the number of rows and columns of the matrix, respectively.", "2": "" }, "is_english": true, "time_complexity": "O(m \\times n \\times (\\log (m \\times n) + \\alpha(m \\times n)))", "space_complexity": null }, { "problem_id": 1103, "explanations": { "1": "We can directly simulate the process of each person receiving candies, following the rules described in the problem.\n\nThe time complexity is $O(\\max(\\sqrt{candies}, num\\_people))$, and the space complexity is $O(num\\_people)$. Here, $candies$ is the number of candies." }, "is_english": true, "time_complexity": "O(\\max(\\sqrt{candies}, num\\_people))", "space_complexity": "O(num\\_people)" }, { "problem_id": 1104, "explanations": { "1": "For a complete binary tree, the number of nodes in the $i$th row is $2^{i-1}$, and the range of node labels in the $i$th row is $[2^{i-1}, 2^i - 1]$. In the problem, for odd-numbered rows, the nodes are labeled from left to right, while for even-numbered rows, the nodes are labeled from right to left. Therefore, for the node $label$ in the $i$th row, its complementary node label is $2^{i-1} + 2^i - 1 - label$. So the actual parent node label of node $label$ is $(2^{i-1} + 2^i - 1 - label) / 2$. We can find the path from the root node to node $label$ by continuously finding the complementary node label and the parent node label until we reach the root node.\n\nFinally, we need to reverse the path, because the problem requires the path from the root node to node $label$.\n\nThe time complexity is $O(\\log n)$, where $n$ is the label of the node. Ignoring the space consumption of the answer, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 1105, "explanations": { "1": "We define $f[i]$ as the minimum height for placing the first $i$ books, initially $f[0] = 0$, and the answer is $f[n]$.\n\nConsider $f[i]$, the last book is $books[i - 1]$, its thickness is $w$, and its height is $h$.\n\n- If this book is placed on a new layer alone, then $f[i] = f[i - 1] + h$;\n- If this book can be placed on the same layer with the last few books in front, we enumerate the first book $books[j-1]$ on the same layer from back to front, where $j \\in [1, i - 1]$, accumulate the thickness of the book to $w$, if $w > shelfWidth$, it means that $books[j-1]$ can no longer be placed on the same layer with $books[i-1]$, stop enumeration; otherwise, we update the maximum height $h = \\max(h, books[j-1][1])$ of the current layer, then $f[i] = \\min(f[i], f[j - 1] + h)$.\n\nThe final answer is $f[n]$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $books$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 1106, "explanations": { "1": "For this type of expression parsing problem, we can use a stack to assist.\n\nWe traverse the expression `expression` from left to right. For each character $c$ we encounter:\n\n- If $c$ is one of `\"tf!&|\"`, we push it directly onto the stack;\n- If $c$ is a right parenthesis `')'`, we pop elements from the stack until we encounter an operator `'!'`, `'&'`, or `'|'`. During this process, we use variables $t$ and $f$ to record the number of `'t'` and `'f'` characters popped from the stack. Finally, based on the number of characters popped and the operator, we calculate a new character `'t'` or `'f'` and push it onto the stack.\n\nAfter traversing the expression `expression`, there is only one character left in the stack. If it is `'t'`, return `true`, otherwise return `false`.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the expression `expression`." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1107, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1108, "explanations": { "1": "We can directly replace the `'.'` in the string with `'[.]'`.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string. Ignoring the space consumption of the answer, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1109, "explanations": { "1": "We notice that each booking is for `seats` seats on all flights within a certain interval `[first, last]`. Therefore, we can use the idea of a difference array. For each booking, we add `seats` to the number at the `first` position and subtract `seats` from the number at the `last + 1` position. Finally, we calculate the prefix sum of the difference array to get the total number of seats booked for each flight.\n\nThe time complexity is $O(n)$, where $n$ is the number of flights. Ignoring the space consumption of the answer, the space complexity is $O(1)$.", "2": "We can also use a binary indexed tree, combined with the idea of difference, to implement the above operations. We can consider each booking as booking `seats` seats on all flights within a certain interval `[first, last]`. Therefore, for each booking, we add `seats` to the `first` position of the binary indexed tree and subtract `seats` from the `last + 1` position of the binary indexed tree. Finally, we calculate the prefix sum for each position in the binary indexed tree to get the total number of seats booked for each flight.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the number of flights.\n\nHere is a basic introduction to the binary indexed tree:\n\nA binary indexed tree, also known as a \"Binary Indexed Tree\" or Fenwick tree. It can efficiently implement the following two operations:\n\n1. **Single Point Update** `update(x, delta)`: Add a value delta to the number at position x in the sequence;\n1. **Prefix Sum Query** `query(x)`: Query the interval sum of the sequence `[1,...x]`, that is, the prefix sum of position x.\n\nThe time complexity of these two operations is $O(\\log n)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1110, "explanations": { "1": "First, we use a hash table or an array of length 1001, `s`, to record all nodes that need to be deleted.\n\nNext, we design a function `dfs(root)` that returns the root of the subtree with `root` as the root after deleting all nodes that need to be deleted. The execution logic of the function `dfs(root)` is as follows:\n\n- If `root` is null, we return null;\n- Otherwise, we recursively execute `dfs(root.left)` and `dfs(root.right)`, and assign the return values to `root.left` and `root.right` respectively. If `root` does not need to be deleted, we return `root`; if `root` needs to be deleted, we check whether `root.left` and `root.right` are null. If they are not null, we add them to the answer array; finally, we return null.\n\nIn the main function, we call `dfs(root)`. If the result is not null, it means that the root node does not need to be deleted, and we add the root node to the answer array. Finally, we return the answer array.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the tree.", "2": "" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1111, "explanations": { "1": "We use a variable $x$ to maintain the current balance of parentheses, which is the number of left parentheses minus the number of right parentheses.\n\nWe traverse the string $seq$, updating the value of $x$. If $x$ is odd, we assign the current left parenthesis to $A$, otherwise we assign it to $B$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $seq$. Ignoring the space consumption of the answer, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1112, "explanations": { "1": "We can use the `RANK() OVER()` window function to sort the grades of each student in descending order. If the grades are the same, we sort them in ascending order by course number, and then select the record with a rank of $1$ for each student.", "2": "We can first query the highest grade of each student, and then query the minimum course number corresponding to the highest grade of each student." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1113, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1114, "explanations": { "1": "We can use three semaphores $a$, $b$, and $c$ to control the execution order of the three threads. Initially, the count of semaphore $a$ is $1$, and the counts of $b$ and $c$ are $0$.\n\nWhen thread $A$ executes the `first()` method, it first needs to acquire semaphore $a$. After acquiring successfully, it executes the `first()` method, and then releases semaphore $b$. This allows thread $B$ to acquire semaphore $b$ and execute the `second()` method.\n\nWhen thread $B$ executes the `second()` method, it first needs to acquire semaphore $b$. After acquiring successfully, it executes the `second()` method, and then releases semaphore $c$. This allows thread $C$ to acquire semaphore $c$ and execute the `third()` method.\n\nWhen thread $C$ executes the `third()` method, it first needs to acquire semaphore $c$. After acquiring successfully, it executes the `third()` method, and then releases semaphore $a$. This allows thread $A$ to acquire semaphore $a$ and execute the `first()` method.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$.", "2": "" }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 1115, "explanations": { "1": "We use two semaphores $f$ and $b$ to control the execution order of the two threads, where $f$ is initially set to $1$ and $b$ is set to $0$, indicating that thread $A$ executes first.\n\nWhen thread $A$ executes, it first performs the $acquire$ operation on $f$, which changes the value of $f$ to $0$. Thread $A$ then gains the right to use $f$ and can execute the $foo$ function. After that, it performs the $release$ operation on $b$, changing the value of $b$ to $1$. This allows thread $B$ to gain the right to use $b$ and execute the $bar$ function.\n\nWhen thread $B$ executes, it first performs the $acquire$ operation on $b$, which changes the value of $b$ to $0$. Thread $B$ then gains the right to use $b$ and can execute the $bar$ function. After that, it performs the $release$ operation on $f$, changing the value of $f$ to $1$. This allows thread $A$ to gain the right to use $f$ and execute the $foo$ function.\n\nTherefore, we only need to loop $n$ times, each time executing the $foo$ and $bar$ functions, first performing the $acquire$ operation, and then the $release$ operation.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1116, "explanations": { "1": "We use three semaphores $z$, $e$, and $o$ to control the execution order of the three threads, where $z$ is initially set to $1$, and $e$ and $o$ are set to $0$.\n\n- Semaphore $z$ controls the execution of the `zero` function. When the value of semaphore $z$ is $1$, the `zero` function can be executed. After execution, the value of semaphore $z$ is set to $0$, and the value of semaphore $e$ or $o$ is set to $1$, depending on whether the `even` function or the `odd` function needs to be executed next.\n- Semaphore $e$ controls the execution of the `even` function. When the value of semaphore $e$ is $1$, the `even` function can be executed. After execution, the value of semaphore $z$ is set to $1$, and the value of semaphore $e$ is set to $0$.\n- Semaphore $o$ controls the execution of the `odd` function. When the value of semaphore $o$ is $1$, the `odd` function can be executed. After execution, the value of semaphore $z$ is set to $1$, and the value of semaphore $o$ is set to $0$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1117, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1118, "explanations": { "1": "We can first determine whether the given year is a leap year. If the year can be divided by $4$ but not by $100$, or can be divided by $400$, then this year is a leap year.\n\nFebruary has $29$ days in a leap year and $28$ days in a common year.\n\nWe can use an array $days$ to store the number of days in each month of the current year, where $days[0]=0$, $days[i]$ represents the number of days in the $i$th month of the current year. Then the answer is $days[month]$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 1119, "explanations": { "1": "We can directly traverse the string according to the requirements of the problem, and append characters that are not vowels to the result string.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string. Ignoring the space consumption of the answer, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1120, "explanations": { "1": "We can use a recursive method. For each node, we calculate the sum and count of the nodes in the subtree rooted at that node, then calculate the average, compare it with the current maximum, and update the maximum if necessary.\n\nTherefore, we design a function `dfs(root)` that represents the sum and count of nodes in the subtree rooted at `root`. The return value is an array of length 2, where the first element represents the sum of nodes, and the second element represents the count of nodes.\n\nThe recursive process of the function `dfs(root)` is as follows:\n\n- If `root` is null, return `[0, 0]`;\n- Otherwise, calculate the sum and count of nodes in the left subtree of `root`, denoted as `[ls, ln]`; calculate the sum and count of nodes in the right subtree of `root`, denoted as `[rs, rn]`. The sum of nodes in the subtree rooted at `root` is `root.val + ls + rs`, and the count of nodes is `1 + ln + rn`. Calculate the average, compare it with the current maximum, and update the maximum if necessary;\n- Return `[root.val + ls + rs, 1 + ln + rn]`.\n\nFinally, return the maximum value.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1121, "explanations": { "1": "We assume that the array can be divided into $m$ strictly increasing subsequences of length at least $k$. If the number of the most frequent number in the array is $cnt$, then these $cnt$ numbers must be in different subsequences, so $m \\geq cnt$. Also, since the length of $m$ subsequences is at least $k$, the fewer the number of subsequences, the better, so $m = cnt$. Therefore, $cnt \\times k \\leq n$ must be satisfied. Hence, we only need to count the number of the most frequent number $cnt$ in the array, and then judge whether $cnt \\times k \\leq n$. If it is, return `true`, otherwise return `false`.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the array $nums$.", "2": "" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1122, "explanations": { "1": "First, we use a hash table $pos$ to record the position of each element in array $arr2$. Then, we map each element in array $arr1$ to a tuple $(pos.get(x, 1000 + x), x)$, and sort these tuples. Finally, we take out the second element of all tuples and return it.\n\nThe time complexity is $O(n \\times \\log n + m)$, and the space complexity is $O(n + m)$. Here, $n$ and $m$ are the lengths of arrays $arr1$ and $arr2$, respectively.", "2": "We can use the idea of counting sort. First, count the occurrence of each element in array $arr1$. Then, according to the order in array $arr2$, put the elements in $arr1$ into the answer array $ans$ according to their occurrence. Finally, we traverse all elements in $arr1$ and put the elements that do not appear in $arr2$ in ascending order at the end of the answer array $ans$.\n\nThe time complexity is $O(n + m)$, and the space complexity is $O(n)$. Where $n$ and $m$ are the lengths of arrays $arr1$ and $arr2$ respectively." }, "is_english": true, "time_complexity": "O(n \\times \\log n + m)", "space_complexity": "O(n + m)" }, { "problem_id": 1123, "explanations": { "1": "We design a function `dfs(root)` that returns a tuple `(l, d)`, where `l` is the deepest common ancestor of node `root`, and `d` is the depth of node `root`. The execution logic of the function `dfs(root)` is as follows:\n\n- If `root` is null, return the tuple `(None, 0)`;\n- Otherwise, we recursively call `dfs(root.left)` and `dfs(root.right)`, obtaining tuples `(l, d1)` and `(r, d2)`. If `d1 > d2`, the deepest common ancestor of `root` is `l`, and the depth is `d1 + 1`; if `d1 < d2`, the deepest common ancestor of `root` is `r`, and the depth is `d2 + 1`; if `d1 = d2`, the deepest common ancestor of `root` is `root`, and the depth is `d1 + 1`.\n\nIn the main function, we call `dfs(root)` and return the first element of its return value to get the deepest common ancestor node.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1124, "explanations": { "1": "We can use the idea of prefix sum, maintaining a variable $s$, which represents the difference between the number of \"tiring days\" and \"non-tiring days\" from index $0$ to the current index. If $s$ is greater than $0$, it means that the segment from index $0$ to the current index is a \"well-performing time period\". In addition, we use a hash table $pos$ to record the first occurrence index of each $s$.\n\nNext, we traverse the `hours` array, for each index $i$:\n\n- If $hours[i] > 8$, we increment $s$ by $1$, otherwise we decrement $s$ by $1$.\n- If $s > 0$, it means that the segment from index $0$ to the current index $i$ is a \"well-performing time period\", we update the result $ans = i + 1$. Otherwise, if $s - 1$ is in the hash table $pos$, let $j = pos[s - 1]$, it means that the segment from index $j + 1$ to the current index $i$ is a \"well-performing time period\", we update the result $ans = \\max(ans, i - j)$.\n- Then, if $s$ is not in the hash table $pos$, we record $pos[s] = i$.\n\nAfter the traversal, return the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the `hours` array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1125, "explanations": { "1": "We notice that the length of `req_skills` does not exceed $16$, so we can use a binary number of length no more than $16$ to represent whether each skill is mastered. Let's denote the length of `req_skills` as $m$ and the length of `people` as $n$.\n\nFirst, we map each skill in `req_skills` to a number, i.e., $d[s]$ represents the number of skill $s$. Then, we traverse each person in `people` and represent the skills they master with a binary number, i.e., $p[i]$ represents the skills mastered by the person with number $i$.\n\nNext, we define the following three arrays:\n\n- Array $f[i]$ represents the minimum number of people to master the skill set $i$, where each bit of the binary representation of $i$ is $1$, indicating that the corresponding skill is mastered. Initially, $f[0] = 0$, and all other positions are infinity.\n- Array $g[i]$ represents the number of the last person when the skill set $i$ is mastered by the minimum number of people.\n- Array $h[i]$ represents the previous skill set state when the skill set $i$ is mastered by the minimum number of people.\n\nWe enumerate each skill set in the range of $[0,..2^m-1]$, for each skill set $i$:\n\nWe enumerate each person $j$ in `people`. If $f[i] + 1 \\lt f[i | p[j]]$, it means that $f[i | p[j]]$ can be transferred from $f[i]$. At this time, we update $f[i | p[j]]$ to $f[i] + 1$, and update $g[i | p[j]]$ to $j$, and update $h[i | p[j]]$ to $i$. That is, when the current skill set state is $i | p[j]$, the number of the last person is $j$, and the previous skill set state is $i$. Here, the symbol $|$ represents bitwise OR operation.\n\nFinally, we start from the skill set $i=2^m-1$, find the number of the last person at this time $g[i]$, add it to the answer, then update $i$ to $h[i]$, and keep backtracking until $i=0$, to get the personnel numbers in the smallest necessary team.\n\nThe time complexity is $O(2^m \\times n)$, and the space complexity is $O(2^m)$. Here, $m$ and $n$ are the lengths of `req_skills` and `people`, respectively." }, "is_english": true, "time_complexity": "O(2^m \\times n)", "space_complexity": "O(2^m)" }, { "problem_id": 1126, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1127, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1128, "explanations": { "1": "We can concatenate the two numbers of each domino in order of size to form a two-digit number, so that equivalent dominoes can be concatenated into the same two-digit number. For example, both `[1, 2]` and `[2, 1]` are concatenated into the two-digit number `12`, and both `[3, 4]` and `[4, 3]` are concatenated into the two-digit number `34`.\n\nThen we traverse all the dominoes, using an array $cnt$ of length $100$ to record the number of occurrences of each two-digit number. For each domino, the two-digit number we concatenate is $x$, then the answer will increase by $cnt[x]$, and then we add $1$ to the value of $cnt[x]$. Continue to traverse the next domino, and we can count the number of all equivalent domino pairs.\n\nThe time complexity is $O(n)$, and the space complexity is $O(C)$. Here, $n$ is the number of dominoes, and $C$ is the maximum number of two-digit numbers concatenated in the dominoes, which is $100$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(C)" }, { "problem_id": 1129, "explanations": { "1": "The problem is essentially a shortest path problem, which we can consider solving using BFS.\n\nFirst, we preprocess all the edges, categorizing all the edges by color and storing them in a multi-dimensional array $g$. Where $g[0]$ stores all red edges, and $g[1]$ stores all blue edges.\n\nNext, we define the following data structures or variables:\n\n- Queue $q$: used to store the currently searched node and the color of the current edge;\n- Set $vis$: used to store the nodes that have been searched and the color of the current edge;\n- Variable $d$: used to represent the current search level, i.e., the distance from the currently searched node to the starting point;\n- Array $ans$: used to store the shortest distance from each node to the starting point. Initially, we initialize all elements in the $ans$ array to $-1$, indicating that the distance from all nodes to the starting point is unknown.\n\nWe first enqueue the starting point $0$ and the color of the starting edge $0$ or $1$, indicating that we start from the starting point and the current edge is red or blue.\n\nNext, we start the BFS search. Each time we take out a node $(i, c)$ from the queue, if the answer of the current node has not been updated, then we update the answer of the current node to the current level $d$, i.e., $ans[i] = d$. Then, we flip the color of the current edge $c$, i.e., if the current edge is red, we change it to blue, and vice versa. We take out all edges corresponding to the color, if the other end node $j$ of the edge has not been searched, then we enqueue it.\n\nAfter the search is over, return the answer array.\n\nThe time complexity is $O(n + m)$, and the space complexity is $O(n + m)$. Here, $n$ and $m$ are the number of nodes and edges, respectively." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(n + m)" }, { "problem_id": 1130, "explanations": { "1": "According to the problem description, the values in the array $arr$ correspond one-to-one with the values in the inorder traversal of each leaf node of the tree. We can divide the array into two non-empty sub-arrays, corresponding to the left and right subtrees of the tree, and recursively solve for the minimum possible sum of all non-leaf node values in each subtree.\n\nWe design a function $dfs(i, j)$, which represents the minimum possible sum of all non-leaf node values in the index range $[i, j]$ of the array $arr$. The answer is $dfs(0, n - 1)$, where $n$ is the length of the array $arr$.\n\nThe calculation process of the function $dfs(i, j)$ is as follows:\n\n- If $i = j$, it means that there is only one element in the array $arr[i..j]$, and there are no non-leaf nodes, so $dfs(i, j) = 0$.\n- Otherwise, we enumerate $k \\in [i, j - 1]$, divide the array $arr$ into two sub-arrays $arr[i..k]$ and $arr[k + 1..j]$. For each $k$, we recursively calculate $dfs(i, k)$ and $dfs(k + 1, j)$. Here, $dfs(i, k)$ represents the minimum possible sum of all non-leaf node values in the index range $[i, k]$ of the array $arr$, and $dfs(k + 1, j)$ represents the minimum possible sum of all non-leaf node values in the index range $[k + 1, j]$ of the array $arr$. So $dfs(i, j) = \\min_{i \\leq k < j} \\{dfs(i, k) + dfs(k + 1, j) + \\max_{i \\leq t \\leq k} \\{arr[t]\\} \\max_{k < t \\leq j} \\{arr[t]\\}\\}$.\n\nIn summary, we can get:\n\n$$\ndfs(i, j) = \\begin{cases}\n0, & \\textit{if } i = j \\\\\n\\min_{i \\leq k < j} \\{dfs(i, k) + dfs(k + 1, j) + \\max_{i \\leq t \\leq k} \\{arr[t]\\} \\max_{k < t \\leq j} \\{arr[t]\\}\\}, & \\textit{if } i < j\n\\end{cases}\n$$\n\nIn the above recursive process, we can use the method of memoization search to avoid repeated calculations. Additionally, we can use an array $g$ to record the maximum value of all leaf nodes in the index range $[i, j]$ of the array $arr$. This allows us to optimize the calculation process of $dfs(i, j)$:\n\n$$\ndfs(i, j) = \\begin{cases}\n0, & \\textit{if } i = j \\\\\n\\min_{i \\leq k < j} \\{dfs(i, k) + dfs(k + 1, j) + g[i][k] \\cdot g[k + 1][j]\\}, & \\textit{if } i < j\n\\end{cases}\n$$\n\nFinally, we return $dfs(0, n - 1)$.\n\nThe time complexity is $O(n^3)$, and the space complexity is $O(n^2)$. Here, $n$ is the length of the array $arr$.", "2": "We can change the memoization search in Solution 1 to dynamic programming.\n\nDefine $f[i][j]$ to represent the minimum possible sum of all non-leaf node values in the index range $[i, j]$ of the array $arr$, and $g[i][j]$ to represent the maximum value of all leaf nodes in the index range $[i, j]$ of the array $arr$. Then, the state transition equation is:\n\n$$\nf[i][j] = \\begin{cases}\n0, & \\textit{if } i = j \\\\\n\\min_{i \\leq k < j} \\{f[i][k] + f[k + 1][j] + g[i][k] \\cdot g[k + 1][j]\\}, & \\textit{if } i < j\n\\end{cases}\n$$\n\nFinally, we return $f[0][n - 1]$.\n\nThe time complexity is $O(n^3)$, and the space complexity is $O(n^2)$. Here, $n$ is the length of the array $arr$.", "3": "" }, "is_english": true, "time_complexity": "O(n^3)", "space_complexity": "O(n^2)" }, { "problem_id": 1131, "explanations": { "1": "Let's denote $x_i = arr1[i]$, $y_i = arr2[i]$. Since the size relationship between $i$ and $j$ does not affect the value of the expression, we can assume $i \\ge j$. Then the expression can be transformed into:\n\n$$\n| x_i - x_j | + | y_i - y_j | + i - j = \\max \\begin{cases} (x_i + y_i) - (x_j + y_j) \\\\ (x_i - y_i) - (x_j - y_j) \\\\ (-x_i + y_i) - (-x_j + y_j) \\\\ (-x_i - y_i) - (-x_j - y_j) \\end{cases} + i - j\\\\\n= \\max \\begin{cases} (x_i + y_i + i) - (x_j + y_j + j) \\\\ (x_i - y_i + i) - (x_j - y_j + j) \\\\ (-x_i + y_i + i) - (-x_j + y_j + j) \\\\ (-x_i - y_i + i) - (-x_j - y_j + j) \\end{cases}\n$$\n\nTherefore, we just need to find the maximum value $mx$ and the minimum value $mi$ of $a \\times x_i + b \\times y_i + i$, where $a, b \\in \\{-1, 1\\}$. The answer is the maximum value among all $mx - mi$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$.\n\nSimilar problems:\n\n- [1330. Reverse Subarray To Maximize Array Value](https://github.com/doocs/leetcode/blob/main/solution/1300-1399/1330.Reverse%20Subarray%20To%20Maximize%20Array%20Value/README_EN.md)" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1132, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1133, "explanations": { "1": "Given the data range in the problem, we can use an array of length $1001$ to count the occurrence of each number. Then, we traverse the array in reverse order to find the first number that appears only once. If no such number is found, we return $-1$.\n\nThe time complexity is $O(n + M)$, and the space complexity is $O(M)$. Here, $n$ is the length of the array, and $M$ is the maximum number that appears in the array. In this problem, $M \\leq 1000$." }, "is_english": true, "time_complexity": "O(n + M)", "space_complexity": "O(M)" }, { "problem_id": 1134, "explanations": { "1": "We can first calculate the number of digits $k$, then calculate the sum $s$ of the $k$th power of each digit, and finally check whether $s$ equals $n$.\n\nThe time complexity is $O(\\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the given number." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 1135, "explanations": { "1": "Kruskal's algorithm is a greedy algorithm used to compute the minimum spanning tree.\n\nThe basic idea of Kruskal's algorithm is to select the smallest edge from the edge set each time. If the two vertices connected by this edge are not in the same connected component, then add this edge to the minimum spanning tree, otherwise discard this edge.\n\nFor this problem, we can sort the edges in ascending order of connection cost, use a union-find set to maintain connected components, select the smallest edge each time, and if the two vertices connected by this edge are not in the same connected component, then merge these two vertices and accumulate the connection cost. If a situation occurs where the number of connected components is $1$, it means that all vertices are connected, and we return the accumulated connection cost, otherwise, we return $-1$.\n\nThe time complexity is $O(m \\times \\log m)$, and the space complexity is $O(n)$. Here, $m$ and $n$ are the number of edges and vertices, respectively." }, "is_english": true, "time_complexity": "O(m \\times \\log m)", "space_complexity": "O(n)" }, { "problem_id": 1136, "explanations": { "1": "We can first build a graph $g$ to represent the prerequisite relationships between courses, and count the in-degree $indeg$ of each course.\n\nThen we enqueue the courses with an in-degree of $0$ and start topological sorting. Each time, we dequeue a course from the queue, reduce the in-degree of the courses that it points to by $1$, and if the in-degree becomes $0$ after reduction, we enqueue that course. When the queue is empty, if there are still courses that have not been completed, it means that it is impossible to complete all courses, so we return $-1$. Otherwise, we return the number of semesters required to complete all courses.\n\nThe time complexity is $O(n + m)$, and the space complexity is $O(n + m)$. Here, $n$ and $m$ are the number of courses and the number of prerequisite relationships, respectively." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(n + m)" }, { "problem_id": 1137, "explanations": { "1": "According to the recurrence relation given in the problem, we can use dynamic programming to solve it.\n\nWe define three variables $a$, $b$, $c$ to represent $T_{n-3}$, $T_{n-2}$, $T_{n-1}$, respectively, with initial values of $0$, $1$, $1$.\n\nThen we decrease $n$ to $0$, updating the values of $a$, $b$, $c$ each time, until $n$ is $0$, at which point the answer is $a$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the given integer.", "2": "We define $Tib(n)$ as a $1 \\times 3$ matrix $\\begin{bmatrix} T_n & T_{n - 1} & T_{n - 2} \\end{bmatrix}$, where $T_n$, $T_{n - 1}$ and $T_{n - 2}$ represent the $n$th, $(n - 1)$th and $(n - 2)$th Tribonacci numbers, respectively.\n\nWe hope to derive $Tib(n)$ from $Tib(n-1) = \\begin{bmatrix} T_{n - 1} & T_{n - 2} & T_{n - 3} \\end{bmatrix}$. That is, we need a matrix $base$ such that $Tib(n - 1) \\times base = Tib(n)$, i.e.,\n\n$$\n\\begin{bmatrix}\nT_{n - 1} & T_{n - 2} & T_{n - 3}\n\\end{bmatrix} \\times base = \\begin{bmatrix} T_n & T_{n - 1} & T_{n - 2} \\end{bmatrix}\n$$\n\nSince $T_n = T_{n - 1} + T_{n - 2} + T_{n - 3}$, the matrix $base$ is:\n\n$$\n\\begin{bmatrix}\n 1 & 1 & 0 \\\\\n 1 & 0 & 1 \\\\\n 1 & 0 & 0\n\\end{bmatrix}\n$$\n\nWe define the initial matrix $res = \\begin{bmatrix} 1 & 1 & 0 \\end{bmatrix}$, then $T_n$ is equal to the sum of all elements in the result matrix of $res$ multiplied by $base^{n - 3}$. This can be solved using matrix exponentiation.\n\nThe time complexity is $O(\\log n)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1138, "explanations": { "1": "Starting from the origin point $(0, 0)$, simulate each step of the movement, appending the result of each step to the answer. Note that the direction of movement follows the order \"left, up, right, down\".\n\nThe time complexity is $O(n)$, where $n$ is the length of the string target, as each character in the string target needs to be traversed. Ignoring the space consumption of the answer, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1139, "explanations": { "1": "We can use the prefix sum method to preprocess the number of consecutive 1s down and to the right of each position, denoted as `down[i][j]` and `right[i][j]`.\n\nThen we enumerate the side length $k$ of the square, starting from the largest side length. Then we enumerate the upper left corner position $(i, j)$ of the square. If it meets the condition, we can return $k^2$.\n\nThe time complexity is $O(m \\times n \\times \\min(m, n))$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the number of rows and columns of the grid, respectively." }, "is_english": true, "time_complexity": "O(m \\times n \\times \\min(m, n))", "space_complexity": "O(m \\times n)" }, { "problem_id": 1140, "explanations": { "1": "Since the player can take all the stones from the first $X$ piles each time, that is, they can take the stones from an interval, we can first preprocess a prefix sum array $s$ of length $n+1$, where $s[i]$ represents the sum of the first $i$ elements of the array `piles`.\n\nThen we design a function $dfs(i, m)$, which represents the maximum number of stones that the current player can take when they can start from index $i$ of the array `piles`, and the current $M$ is $m$. Initially, Alice starts from index $0$, and $M=1$, so the answer we need to find is $dfs(0, 1)$.\n\nThe calculation process of the function $dfs(i, m)$ is as follows:\n\n- If the current player can take all the remaining stones, the maximum number of stones they can take is $s[n] - s[i]$;\n- Otherwise, the current player can take all the stones from the first $x$ piles of the remaining ones, where $1 \\leq x \\leq 2m$, and the maximum number of stones they can take is $s[n] - s[i] - dfs(i + x, max(m, x))$. That is to say, the number of stones that the current player can take is the number of all the remaining stones minus the number of stones that the opponent can take in the next round. We need to enumerate all $x$, and take the maximum value as the return value of the function $dfs(i, m)$.\n\nTo avoid repeated calculations, we can use memoization search.\n\nFinally, we return $dfs(0, 1)$ as the answer.\n\nThe time complexity is $O(n^3)$, and the space complexity is $O(n^2)$. Here, $n$ is the length of the array `piles`.", "2": "" }, "is_english": true, "time_complexity": "O(n^3)", "space_complexity": "O(n^2)" }, { "problem_id": 1141, "explanations": { "1": "我们查询出所有在 `2019-07-27` 且在 $30$ 天内的所有活动记录,然后按照日期分组,统计每天的去重活跃用户数。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1142, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1143, "explanations": { "1": "We define $f[i][j]$ as the length of the longest common subsequence of the first $i$ characters of $text1$ and the first $j$ characters of $text2$. Therefore, the answer is $f[m][n]$, where $m$ and $n$ are the lengths of $text1$ and $text2$, respectively.\n\nIf the $i$th character of $text1$ and the $j$th character of $text2$ are the same, then $f[i][j] = f[i - 1][j - 1] + 1$; if the $i$th character of $text1$ and the $j$th character of $text2$ are different, then $f[i][j] = max(f[i - 1][j], f[i][j - 1])$. The state transition equation is:\n\n$$\nf[i][j] =\n\\begin{cases}\nf[i - 1][j - 1] + 1, & \\textit{if } text1[i - 1] = text2[j - 1] \\\\\n\\max(f[i - 1][j], f[i][j - 1]), & \\textit{if } text1[i - 1] \\neq text2[j - 1]\n\\end{cases}\n$$\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the lengths of $text1$ and $text2$, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 1144, "explanations": { "1": "We can separately enumerate the even and odd positions as the elements \"smaller than adjacent elements\", and then calculate the required number of operations. The minimum of the two is taken.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1145, "explanations": { "1": "First, we use DFS to find the node where player 1's colored point $x$ is located, denoted as $node$.\n\nNext, we count the number of nodes in the left and right subtrees of $node$, denoted as $l$ and $r$ respectively, and the number of nodes in the direction of $node$'s parent node is $n - l - r - 1$. As long as $\\max(l, r, n - l - r - 1) > \\frac{n}{2}$, player 2 has a winning strategy.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the total number of nodes." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1146, "explanations": { "1": "We maintain an array of length `length`. Each element in the array is a list, which is used to store the value set each time and the corresponding snapshot ID.\n\nWhen the `set` method is called, we add the value and snapshot ID to the list at the corresponding index. The time complexity is $O(1)$.\n\nWhen the `snap` method is called, we first increment the snapshot ID, then return the snapshot ID minus one. The time complexity is $O(1)$.\n\nWhen the `get` method is called, we use binary search to find the first snapshot ID greater than `snap_id` at the corresponding position, and then return the previous value. If it cannot be found, return 0. The time complexity is $O(\\log n)$.\n\nThe space complexity is $O(n)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(n)" }, { "problem_id": 1147, "explanations": { "1": "We can start from both ends of the string, looking for the shortest, identical, and non-overlapping prefixes and suffixes:\n\n- If such prefixes and suffixes cannot be found, then the entire string is treated as a segmented palindrome, and the answer is incremented by $1$;\n- If such prefixes and suffixes are found, then this prefix and suffix are treated as a segmented palindrome, and the answer is incremented by $2$, then continue to find the prefixes and suffixes of the remaining string.\n\nThe proof of the above greedy strategy is as follows:\n\nSuppose there is a prefix $A_1$ and a suffix $A_2$ that meet the conditions, and there is a prefix $B_1$ and a suffix $B_4$ that meet the conditions. Since $A_1 = A_2$ and $B_1=B_4$, then $B_3=B_1=B_4=B_2$, and $C_1 = C_2$. Therefore, if we greedily split $B_1$ and $B_4$, then the remaining $C_1$ and $C_2$, and $B_2$ and $B_3$ can also be successfully split. Therefore, we should greedily choose the shortest identical prefix and suffix to split, so that in the remaining string, more segmented palindromes may be split.\n\n

\"\"

\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$ or $O(1)$. Here, $n$ is the length of the string.", "2": "**String hash** is to map a string of any length to a non-negative integer, and its collision probability is almost $0$. String hash is used to calculate the hash value of a string and quickly determine whether two strings are equal.\n\nTherefore, based on Solution 1, we can use the method of string hash to compare whether two strings are equal in $O(1)$ time.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 1148, "explanations": { "1": "我们利用 `WHERE` 子句来筛选出 `author_id` 和 `viewer_id` 相等的记录,然后利用 `DISTINCT` 来去重,最后按照 `id` 排序即可。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1149, "explanations": { "1": "我们将数据按照 `viewer_id` 和 `view_date` 分组,然后利用 `HAVING` 子句来筛选出浏览文章数大于 $1$ 的记录,最后按照 `id` 去重排序即可。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1150, "explanations": { "1": "We notice that the elements in the array $nums$ are non-decreasing, that is, the elements in the array $nums$ are monotonically increasing. Therefore, we can use the method of binary search to find the index $left$ of the first element in the array $nums$ that is greater than or equal to $target$, and the index $right$ of the first element in the array $nums$ that is greater than $target$. If $right - left > \\frac{n}{2}$, it means that the number of occurrences of the element $target$ in the array $nums$ exceeds half of the length of the array, so return $true$, otherwise return $false$.\n\nThe time complexity is $O(\\log n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the array $nums$.", "2": "In Solution 1, we used binary search twice to find the index $left$ of the first element in the array $nums$ that is greater than or equal to $target$, and the index $right$ of the first element in the array $nums$ that is greater than $target$. However, we can use binary search once to find the index $left$ of the first element in the array $nums$ that is greater than or equal to $target$, and then judge whether $nums[left + \\frac{n}{2}]$ is equal to $target$. If they are equal, it means that the number of occurrences of the element $target$ in the array $nums$ exceeds half of the length of the array, so return $true$, otherwise return $false$.\n\nThe time complexity is $O(\\log n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 1151, "explanations": { "1": "First, we count the number of $1$s in the array, denoted as $k$. Then we use a sliding window of size $k$, moving the right boundary of the window from left to right, and count the number of $1$s in the window, denoted as $t$. Each time we move the window, we update the value of $t$. Finally, when the right boundary of the window moves to the end of the array, the number of $1$s in the window is the maximum, denoted as $mx$. The final answer is $k - mx$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1152, "explanations": { "1": "First, we use a hash table $d$ to record the websites each user visits. Then we traverse $d$. For each user, we enumerate all the triplets they visited, count the occurrence of distinct triplets, and finally traverse all triplets, returning the one with the highest occurrence and the smallest lexicographic order.\n\nThe time complexity is $O(n^3)$, and the space complexity is $O(n^3)$. Here, $n$ is the length of `username`." }, "is_english": true, "time_complexity": "O(n^3)", "space_complexity": "O(n^3)" }, { "problem_id": 1153, "explanations": { "1": "First, we can check if `str1` and `str2` are equal. If they are, return `true` directly.\n\nThen we count the occurrence of each letter in `str2`. If the occurrence equals $26$, it means `str2` contains all lowercase letters. In this case, no matter how `str1` is transformed, it cannot become `str2`, so return `false` directly.\n\nOtherwise, we use an array or hash table `d` to record the letter each letter in `str1` is transformed to. We traverse the strings `str1` and `str2`. If a letter in `str1` has been transformed, the transformed letter must be the same as the corresponding letter in `str2`, otherwise return `false`.\n\nAfter the traversal, return `true`.\n\nThe time complexity is $O(n)$, and the space complexity is $O(C)$. Here, $n$ is the length of the string `str1`, and $C$ is the size of the character set. In this problem, $C = 26$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(C)" }, { "problem_id": 1154, "explanations": { "1": "According to the problem, the given date is in the Gregorian calendar, so we can directly calculate which day of the year it is.\n\nFirst, calculate the year, month, and day from the given date, denoted as $y$, $m$, $d$.\n\nThen, calculate the number of days in February of that year according to the leap year rules of the Gregorian calendar. There are $29$ days in February of a leap year and $28$ days in a non-leap year.\n\n> The leap year calculation rule is: the year can be divided by $400$, or the year can be divided by $4$ but not by $100$.\n\nFinally, calculate which day of the year it is according to the given date, that is, add up the number of days in each previous month, and then add the number of days in the current month.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 1155, "explanations": { "1": "We define $f[i][j]$ as the number of ways to get a sum of $j$ using $i$ dice. Then, we can obtain the following state transition equation:\n\n$$\nf[i][j] = \\sum_{h=1}^{\\min(j, k)} f[i-1][j-h]\n$$\n\nwhere $h$ represents the number of points on the $i$-th die.\n\nInitially, we have $f[0][0] = 1$, and the final answer is $f[n][target]$.\n\nThe time complexity is $O(n \\times k \\times target)$, and the space complexity is $O(n \\times target)$.\n\nWe notice that the state $f[i][j]$ only depends on $f[i-1][]$, so we can use a rolling array to optimize the space complexity to $O(target)$.", "2": "" }, "is_english": true, "time_complexity": "O(n \\times k \\times target)", "space_complexity": "O(n \\times target)" }, { "problem_id": 1156, "explanations": { "1": "First, we use a hash table or array $cnt$ to count the occurrence of each character in the string $text$.\n\nNext, we define a pointer $i$, initially $i = 0$. Each time, we set the pointer $j$ to $i$, and continuously move $j$ to the right until the character pointed by $j$ is different from the character pointed by $i$. At this time, we get a substring $text[i..j-1]$ of length $l = j - i$, where all characters are the same.\n\nThen we skip the character pointed by the pointer $j$, and continue to move the pointer $k$ to the right until the character pointed by $k$ is different from the character pointed by $i$. At this time, we get a substring $text[j+1..k-1]$ of length $r = k - j - 1$, where all characters are the same. So the longest single-character repeated substring we can get by at most one swap operation is $\\min(l + r + 1, cnt[text[i]])$. Next, we move the pointer $i$ to $j$ and continue to find the next substring. We take the maximum length of all substrings that meet the conditions.\n\nThe time complexity is $O(n)$, and the space complexity is $O(C)$. Here, $n$ is the length of the string, and $C$ is the size of the character set. In this problem, $C = 26$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(C)" }, { "problem_id": 1157, "explanations": { "1": "We notice that the problem requires us to find the possible majority element in a specific interval, so we consider using a segment tree to maintain the candidate majority element and its occurrence in each interval.\n\nWe define each node of the segment tree as `Node`, each node contains the following attributes:\n\n- `l`: The left endpoint of the node, the index starts from $1$.\n- `r`: The right endpoint of the node, the index starts from $1$.\n- `x`: The candidate majority element of the node.\n- `cnt`: The occurrence of the candidate majority element of the node.\n\nThe segment tree mainly has the following operations:\n\n- `build(u, l, r)`: Build the segment tree.\n- `pushup(u)`: Use the information of the child nodes to update the information of the parent node.\n- `query(u, l, r)`: Query the interval sum.\n\nIn the initialization method of the main function, we first create a segment tree, and use a hash table $d$ to record all indexes of each element in the array.\n\nIn the `query(left, right, threshold)` method, we directly call the `query` method of the segment tree to get the candidate majority element $x$. Then use binary search to find the first index $l$ in the array that is greater than or equal to $left$, and the first index $r$ that is greater than $right$. If $r - l \\ge threshold$, return $x$, otherwise return $-1$.\n\nIn terms of time complexity, the time complexity of the initialization method is $O(n)$, and the time complexity of the query method is $O(\\log n)$. The space complexity is $O(n)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1158, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1159, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1160, "explanations": { "1": "We can use an array $cnt$ of length $26$ to count the occurrence of each letter in the string $chars$.\n\nThen we traverse the string array $words$. For each string $w$, we use an array $wc$ of length $26$ to count the occurrence of each letter in the string $w$. If for each letter $c$, $wc[c] \\leq cnt[c]$, then we can spell the string $w$ with the letters in $chars$, otherwise we cannot spell the string $w$. If we can spell the string $w$, then we add the length of the string $w$ to the answer.\n\nAfter the traversal, we can get the answer.\n\nThe time complexity is $O(L)$, and the space complexity is $O(C)$. Here, $L$ is the sum of the lengths of all strings in the problem, and $C$ is the size of the character set. In this problem, $C = 26$." }, "is_english": true, "time_complexity": "O(L)", "space_complexity": "O(C)" }, { "problem_id": 1161, "explanations": { "1": "We use BFS to traverse level by level, calculating the sum of nodes at each level, and find the level with the maximum sum. If there are multiple levels with the maximum sum, return the smallest level number.\n\nSpecifically, we use a queue $q$ to store the nodes of the current level. During each traversal, we record the sum of nodes at the current level as $s$, then add all child nodes of the current level to the queue to prepare for the next level. We use variable $mx$ to record the current maximum sum, and variable $ans$ to record the corresponding level number. After calculating the sum of each level, if $s$ is greater than $mx$, we update $mx$ and $ans$. Finally, we return $ans$.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the number of nodes in the binary tree.", "2": "We can also use DFS to solve this problem. We use an array $s$ to store the sum of nodes at each level. The index of the array represents the level, and the value of the array represents the sum of nodes. We use DFS to traverse the binary tree, adding the value of each node to the sum of nodes at the corresponding level. Finally, we return the index corresponding to the maximum value in $s$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1162, "explanations": { "1": "We can add all land cells to the queue $q$. If the queue is empty, or the number of elements in the queue equals the number of cells in the grid, it means that the grid contains only land or ocean, so return $-1$.\n\nOtherwise, we start BFS from the land cells. Define the initial step count $ans=-1$.\n\nIn each round of search, we spread all cells in the queue in four directions. If a cell is an ocean cell, we mark it as a land cell and add it to the queue. After a round of spreading, we increase the step count by $1$. Repeat this process until the queue is empty.\n\nFinally, we return the step count $ans$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ is the side length of the grid." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 1163, "explanations": { "1": "We notice that if a substring starts from position $i$, then the largest substring with the largest dictionary order must be $s[i,..n-1]$, which is the longest suffix starting from position $i$. Therefore, we only need to find the largest suffix substring.\n\nWe use two pointers $i$ and $j$, where pointer $i$ points to the starting position of the current largest substring with the largest dictionary order, and pointer $j$ points to the starting position of the current substring being considered. In addition, we use a variable $k$ to record the current position being compared. Initially, $i = 0$, $j=1$, $k=0$.\n\nEach time, we compare $s[i+k]$ and $s[j+k]$:\n\nIf $s[i + k] = s[j + k]$, it means that $s[i,..i+k]$ and $s[j,..j+k]$ are the same, and we add $k$ by $1$ and continue to compare $s[i+k]$ and $s[j+k]$;\n\nIf $s[i + k] \\lt s[j + k]$, it means that the dictionary order of $s[j,..j+k]$ is larger. At this time, we update $i = i + k + 1$, and reset $k$ to $0$. If $i \\geq j$ at this time, we update pointer $j$ to $i + 1$, that is, $j = i + 1$. Here we skip all suffix substrings with $s[i,..,i+k]$ as the starting position, because their dictionary orders are smaller than the suffix substrings with $s[j,..,j+k]$ as the starting position.\n\nSimilarly, if $s[i + k] \\gt s[j + k]$, it means that the dictionary order of $s[i,..,i+k]$ is larger. At this time, we update $j = j + k + 1$ and reset $k$ to $0$. Here we skip all suffix substrings with $s[j,..,j+k]$ as the starting position, because their dictionary orders are smaller than the suffix substrings with $s[i,..,i+k]$ as the starting position.\n\nFinally, we return the suffix substring starting from $i$, that is, $s[i,..,n-1]$.\n\nThe time complexity is $O(n)$, where $n$ is the length of string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1164, "explanations": { "1": "We can use a subquery to find the price of the last price change for each product before the given date, and record it in the `P` table. Then, we can find all `product_id`s in the `T` table. Finally, we can left join the `T` table with the `P` table on `product_id` to get the final result.", "2": "" }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1165, "explanations": { "1": "We can use a hash table or an array $pos$ of length $26$ to store the position of each character on the keyboard, where $pos[c]$ represents the position of character $c$ on the keyboard.\n\nThen we traverse the string $word$, using a variable $i$ to record the current position of the finger, initially $i = 0$. Each time, we calculate the position $j$ of the current character $c$ on the keyboard, and increase the answer by $|i - j|$, then update $i$ to $j$. Continue to traverse the next character until the entire string $word$ is traversed.\n\nAfter traversing the string $word$, we can get the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(C)$. Here, $n$ is the length of the string $word$, and $C$ is the size of the character set. In this problem, $C = 26$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(C)" }, { "problem_id": 1166, "explanations": { "1": "We can use a trie to store the paths, where each node stores a value, representing the value of the path corresponding to the node.\n\nThe structure of the trie node is defined as follows:\n\n- `children`: Child nodes, stored in a hash table, where the key is the path of the child node, and the value is the reference to the child node.\n- `v`: The value of the path corresponding to the current node.\n\nThe methods of the trie are defined as follows:\n\n- `insert(w, v)`: Insert the path $w$ and set its corresponding value to $v$. If the path $w$ already exists or its parent path does not exist, return `false`, otherwise return `true`. The time complexity is $O(|w|)$, where $|w|$ is the length of the path $w$.\n- `search(w)`: Return the value corresponding to the path $w$. If the path $w$ does not exist, return $-1$. The time complexity is $O(|w|)$.\n\nThe total time complexity is $O(\\sum_{w \\in W}|w|)$, and the total space complexity is $O(\\sum_{w \\in W}|w|)$, where $W$ is the set of all inserted paths." }, "is_english": true, "time_complexity": "O(|w|)", "space_complexity": "O(\\sum_{w \\in W}|w|)" }, { "problem_id": 1167, "explanations": { "1": "We can use a greedy approach, each time choosing the shortest two sticks to connect, which ensures the minimum cost of connection.\n\nTherefore, we can use a priority queue (min heap) to maintain the current stick lengths. Each time, we take out two sticks from the priority queue to connect, then put the connected stick back into the priority queue, until there is only one stick left in the priority queue.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array `sticks`." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1168, "explanations": { "1": "We assume that there is a well with the number $0$. Then we can consider the connectivity between each house and the well $0$ as an edge, and the weight of each edge is the cost of building a well for that house. At the same time, we consider the connectivity between each house as an edge, and the weight of each edge is the cost of laying a pipe. In this way, we can transform this problem into finding the minimum spanning tree of an undirected graph.\n\nWe can use Kruskal's algorithm to find the minimum spanning tree of the undirected graph. First, we add an edge between the well $0$ and the house to the $pipes$ array, and then sort the $pipes$ array in ascending order of edge weights. Then, we traverse each edge. If this edge connects different connected components, we choose this edge and merge the corresponding connected components. If the current connected component is exactly $1$, then we have found the minimum spanning tree. The answer at this time is the current edge weight, and we return it.\n\nThe time complexity is $O((m + n) \\times \\log (m + n))$, and the space complexity is $O(m + n)$. Here, $m$ and $n$ are the lengths of the $pipes$ array and the $wells$ array, respectively.", "2": "" }, "is_english": true, "time_complexity": "O((m + n) \\times \\log (m + n))", "space_complexity": "O(m + n)" }, { "problem_id": 1169, "explanations": { "1": "We traverse the transaction list. For each transaction, if the amount is greater than 1000, or if the transaction has the same name but different cities and the time interval does not exceed 60 minutes, then add it to the answer.\n\nSpecifically, we use a hash table `d` to record each transaction, where the key is the transaction name, and the value is a list. Each element in the list is a tuple `(time, city, index)`, indicating that a transaction with the number `index` was conducted in the city `city` at the moment `time`. At the same time, we use a hash table `idx` to record the transaction number in the answer.\n\nWe traverse the transaction list. For each transaction, we first add it to the hash table `d`, and then judge whether its amount is greater than 1000. If so, add its number to the answer. Then we traverse the transactions in the hash table `d`. If the transaction names are the same but the cities are different and the time interval does not exceed 60 minutes, add its number to the answer.\n\nFinally, we traverse the transaction numbers in the answer and add the corresponding transactions to the answer.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ is the length of the transaction list." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 1170, "explanations": { "1": "First, according to the problem description, we implement a function $f(s)$, which returns the frequency of the smallest letter in the string $s$ in lexicographical order.\n\nNext, we calculate $f(w)$ for each string $w$ in $words$, sort them, and store them in an array $nums$.\n\nThen, we traverse each string $q$ in $queries$, and binary search in $nums$ for the first position $i$ that is greater than $f(q)$. Then, the elements at index $i$ and after in $nums$ all satisfy $f(q) < f(W)$, so the answer to the current query is $n - i$.\n\nThe time complexity is $O((n + q) \\times M)$, and the space complexity is $O(n)$. Here, $n$ and $q$ are the lengths of the arrays $words$ and $queries$ respectively, and $M$ is the maximum length of the strings." }, "is_english": true, "time_complexity": "O((n + q) \\times M)", "space_complexity": "O(n)" }, { "problem_id": 1171, "explanations": { "1": "If two prefix sums of the linked list are equal, it means that the sum of the continuous node sequence between the two prefix sums is $0$, so we can remove this part of the continuous nodes.\n\nWe first traverse the linked list and use a hash table $last$ to record the prefix sum and the corresponding linked list node. For the same prefix sum $s$, the later node overwrites the previous node.\n\nNext, we traverse the linked list again. If the current node $cur$ has a prefix sum $s$ that appears in $last$, it means that the sum of all nodes between $cur$ and $last[s]$ is $0$, so we directly modify the pointer of $cur$ to $last[s].next$, which removes this part of the continuous nodes with a sum of $0$. We continue to traverse and delete all continuous nodes with a sum of $0$.\n\nFinally, we return the head node of the linked list $dummy.next$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the linked list." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1172, "explanations": { "1": "We define the following data structures or variables:\n\n- `capacity`: The capacity of each stack;\n- `stacks`: Stack array, used to store all stacks, each with a maximum capacity of `capacity`;\n- `not_full`: Ordered set, used to store the indices of all non-full stacks in the stack array.\n\nFor the `push(val)` operation:\n\n- We first check if `not_full` is empty. If it is, it means there are no non-full stacks, so we need to create a new stack and push `val` into it. At this point, we check if the capacity `capacity` is greater than $1$. If it is, we add the index of this stack to `not_full`.\n- If `not_full` is not empty, it means there are non-full stacks. We take out the smallest index `index` from `not_full`, and push `val` into `stacks[index]`. At this point, if the capacity of `stacks[index]` equals `capacity`, we remove `index` from `not_full`.\n\nFor the `popAtStack(index)` operation:\n\n- We first check if `index` is within the index range of `stacks`. If it is not, we directly return $-1$. If `stacks[index]` is empty, we also directly return $-1$.\n- If `stacks[index]` is not empty, we pop the top element `val` from `stacks[index]`. If `index` equals the length of `stacks` minus $1$, it means `stacks[index]` is the last stack. If it is empty, we loop to remove the index of the last stack from `not_full`, and remove the last stack from the stack array `stacks`, until the last stack is not empty, or the stack array `stacks` is empty. Otherwise, if `stacks[index]` is not the last stack, we add `index` to `not_full`.\n- Finally, return `val`.\n\nFor the `pop()` operation:\n\n- We directly call `popAtStack(stacks.length - 1)`.\n\nThe time complexity is $(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the number of operations." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1173, "explanations": { "1": "We can use the `sum` function to count the number of instant orders, and then divide it by the total number of orders. Since the problem requires a percentage, we need to multiply by 100. Finally, we can use the `round` function to keep two decimal places." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1174, "explanations": { "1": "We can use a subquery to first find the first order of each user, and then calculate the proportion of instant orders.", "2": "We can use the `RANK()` window function to rank the orders of each user in ascending order by order date, and then filter out the orders with a rank of $1$, which are the first orders of each user. After that, we can calculate the proportion of instant orders." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1175, "explanations": { "1": "First, count the number of prime numbers within the range $[1,n]$, which we denote as $cnt$. Then, calculate the product of the factorial of $cnt$ and $n-cnt$ to get the answer, remember to perform the modulo operation.\n\nHere, we use the \"Sieve of Eratosthenes\" to count prime numbers.\n\nIf $x$ is a prime number, then multiples of $x$ greater than $x$, such as $2x$, $3x$, ... are definitely not prime numbers, so we can start from here.\n\nLet $primes[i]$ indicate whether the number $i$ is a prime number. If it is a prime number, it is $true$, otherwise it is $false$.\n\nWe sequentially traverse each number $i$ in the range $[2,n]$. If this number is a prime number, the number of prime numbers increases by $1$, and then all its multiples $j$ are marked as composite numbers (except for the prime number itself), that is, $primes[j]=false$. In this way, at the end of the run, we can know the number of prime numbers.\n\nThe time complexity is $O(n \\times \\log \\log n)$." }, "is_english": true, "time_complexity": "O(n \\times \\log \\log n)", "space_complexity": null }, { "problem_id": 1176, "explanations": { "1": "First, we preprocess a prefix sum array $s$ of length $n+1$, where $s[i]$ represents the total calories of the first $i$ days.\n\nThen we traverse the prefix sum array $s$. For each position $i$, we calculate $s[i+k]-s[i]$, which is the total calories for the consecutive $k$ days starting from the $i$th day. According to the problem description, for each $s[i+k]-s[i]$, we judge its value with $lower$ and $upper$, and update the answer accordingly.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the `calories` array.", "2": "We maintain a sliding window of length $k$, and the sum of the elements in the window is denoted as $s$. If $s \\lt lower$, the score decreases by $1$; if $s > upper$, the score increases by $1$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the `calories` array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1177, "explanations": { "1": "First, consider whether a substring can become a palindrome after at most $k$ replacements. Obviously, we need to count the number of times each character appears in the substring, which can be implemented through prefix sum. For characters that appear an even number of times, we do not need to replace them. For characters that appear an odd number of times, we need to replace them. The number of replacements is $\\lfloor \\frac{x}{2} \\rfloor$, where $x$ is the number of characters that appear an odd number of times. If $\\lfloor \\frac{x}{2} \\rfloor \\leq k$, then this substring can become a palindrome.\n\nTherefore, we define a prefix sum array $ss$, where $ss[i][j]$ represents the number of times character $j$ appears in the first $i$ characters of string $s$. Then for a substring $s[l..r]$, we can get the number of times character $j$ appears in the substring through $ss[r + 1][j] - ss[l][j]$. We traverse all queries. For each query $[l, r, k]$, we count the number of characters $x$ that appear an odd number of times in the substring $s[l..r]$. If $\\lfloor \\frac{x}{2} \\rfloor \\leq k$, then this substring can become a palindrome.\n\nThe time complexity is $O((n + m) \\times C)$, and the space complexity is $O(n \\times C)$. Here, $n$ and $m$ are the lengths of the string $s$ and the query array respectively; and $C$ is the size of the character set. In this problem, the character set is lowercase English letters, so $C = 26$." }, "is_english": true, "time_complexity": "O((n + m) \\times C)", "space_complexity": "O(n \\times C)" }, { "problem_id": 1178, "explanations": { "1": "According to the problem description, for each puzzle $p$ in the puzzle array $puzzles$, we need to count how many words $w$ contain the first letter of the puzzle $p$, and every letter in $w$ can be found in $p$.\n\nSince each repeated letter in a word only needs to be counted once, we can use the method of binary state compression to convert each word $w$ into a binary number $mask$, where the $i$th bit of $mask$ is $1$ if and only if the letter $i$ appears in the word $w$. We use a hash table $cnt$ to count the number of times each compressed state of all words appears.\n\nNext, we traverse the puzzle array $puzzles$. For each puzzle $p$, we note that its length is fixed at $7$, so we only need to enumerate the subsets of $p$. If the subset contains the first letter of $p$, then we look up its corresponding value in the hash table and add it to the current puzzle's answer.\n\nAfter the traversal, we can get the number of puzzle solutions corresponding to each puzzle in the puzzle array $puzzles$, and return it.\n\nThe time complexity is $O(m \\times |w| + n \\times 2^{|p|})$, and the space complexity is $O(m)$. Here, $m$ and $n$ are the lengths of the arrays $words$ and $puzzles$ respectively, and $|w|$ and $|p|$ are the maximum length of the words in the array $words$ and the length of the puzzles in the array $puzzles$, respectively." }, "is_english": true, "time_complexity": "O(m \\times |w| + n \\times 2^{|p|})", "space_complexity": "O(m)" }, { "problem_id": 1179, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1180, "explanations": { "1": "We can use two pointers, where pointer $i$ points to the start of the current substring, and pointer $j$ moves to the right to the first position that is different from $s[i]$. Then, $[i,..j-1]$ is a substring with $s[i]$ as the only character, and its length is $j-i$. Therefore, the number of substrings with $s[i]$ as the only character is $\\frac{(j-i+1)(j-i)}{2}$, which is added to the answer. Then, we set $i=j$ and continue to traverse until $i$ exceeds the range of string $s$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$.", "2": "" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1181, "explanations": { "1": "First, we traverse the `phrases` list, storing the first and last words of each phrase in the array $ps$, where $ps[i][0]$ and $ps[i][1]$ represent the first and last words of the $i$th phrase, respectively.\n\nNext, we enumerate all $(i, j)$, where $i, j \\in [0, n)$ and $i \\neq j$. If $ps[i][1] = ps[j][0]$, then we can concatenate the $i$th phrase and the $j$th phrase to get a new phrase $phrases[i] + phrases[j][len(ps[j][0]):]$, and add the new phrase to the hash table $s$.\n\nFinally, we convert the hash table $s$ into an array and sort it to get the answer.\n\nThe time complexity is $O(n^2 \\times m \\times (\\log n + \\log m))$, and the space complexity is $O(n^2 \\times m)$. Here, $n$ and $m$ represent the length of the `phrases` array and the average length of each phrase, respectively." }, "is_english": true, "time_complexity": "O(n^2 \\times m \\times (\\log n + \\log m))", "space_complexity": "O(n^2 \\times m)" }, { "problem_id": 1182, "explanations": { "1": "We can preprocess the distance from each position to the nearest color $1$, $2$, $3$ on the left, and the distance from each position to the nearest color $1$, $2$, $3$ on the right, and record them in the arrays $left$ and $right$. Initially, $left[0][0] = left[0][1] = left[0][2] = -\\infty$, and $right[n][0] = right[n][1] = right[n][2] = \\infty$, where $n$ is the length of the array `colors`.\n\nThen for each query $(i, c)$, the minimum distance is $d = \\min(i - left[i + 1][c - 1], right[i][c - 1] - i)$. If $d > n$, there is no solution, and the answer to this query is $-1$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array `colors`." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1183, "explanations": { "1": "For convenience, let's denote $x = sideLength$.\n\nConsider a $x \\times x$ square, we need to select at most $maxOnes$ points inside the square and set them to 1. Note that when the point at coordinate $(i, j)$ is selected, all points at coordinates $(i\\pm k_1 \\times x, j\\pm k_2 \\times x)$ can be equivalently set to 1. Therefore, we calculate the number of equivalent positions of the coordinate $(i, j)$ in the matrix, and select the top $maxOnes$ with the most quantities.\n\nThe time complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns of the matrix, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": null }, { "problem_id": 1184, "explanations": { "1": "We can first calculate the total distance $s$ that the bus travels, then simulate the bus's journey. Starting from the departure point, we move one stop to the right each time until we reach the destination, recording the travel distance $t$ during this process. Finally, we return the minimum value between $t$ and $s - t$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{distance}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1185, "explanations": { "1": "We can use Zeller's Congruence to calculate the day of the week. Zeller's Congruence is as follows:\n\n$$\nw = (\\left \\lfloor \\frac{c}{4} \\right \\rfloor - 2c + y + \\left \\lfloor \\frac{y}{4} \\right \\rfloor + \\left \\lfloor \\frac{13(m+1)}{5} \\right \\rfloor + d - 1) \\bmod 7\n$$\n\nWhere:\n\n- `w`: Day of the week (starting from Sunday)\n- `c`: First two digits of the year\n- `y`: Last two digits of the year\n- `m`: Month (the range of m is from 3 to 14, that is, in Zeller's Congruence, January and February of a certain year are considered as the 13th and 14th month of the previous year. For example, January 1, 2003 is considered as the 1st day of the 13th month of 2002)\n- `d`: Day\n- `⌊⌋`: Floor function (round down)\n- `mod`: Modulo operation\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$.", "2": "" }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 1186, "explanations": { "1": "We can preprocess the array $\\textit{arr}$ to find the maximum subarray sum ending and starting with each element, storing them in arrays $\\textit{left}$ and $\\textit{right}$, respectively.\n\nIf we do not delete any element, then the maximum subarray sum is the maximum value in $\\textit{left}[i]$ or $\\textit{right}[i]$; if we delete an element, we can enumerate each position $i$ in $[1..n-2]$, calculate the value of $\\textit{left}[i-1] + \\textit{right}[i+1]$, and take the maximum value.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{arr}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1187, "explanations": { "1": "We define $f[i]$ as the minimum number of operations to convert $arr1[0,..,i]$ into a strictly increasing array, and $arr1[i]$ is not replaced. Therefore, we set two sentinels $-\\infty$ and $\\infty$ at the beginning and end of $arr1$. The last number is definitely not replaced, so $f[n-1]$ is the answer. We initialize $f[0]=0$, and the rest $f[i]=\\infty$.\n\nNext, we sort the array $arr2$ and remove duplicates for easy binary search.\n\nFor $i=1,..,n-1$, we consider whether $arr1[i-1]$ is replaced. If $arr1[i-1] \\lt arr1[i]$, then $f[i]$ can be transferred from $f[i-1]$, that is, $f[i] = f[i-1]$. Then, we consider the case where $arr[i-1]$ is replaced. Obviously, $arr[i-1]$ should be replaced with a number as large as possible and less than $arr[i]$. We perform a binary search in the array $arr2$ and find the first index $j$ that is greater than or equal to $arr[i]$. Then we enumerate the number of replacements in the range $k \\in [1, min(i-1, j)]$. If $arr[i-k-1] \\lt arr2[j-k]$, then $f[i]$ can be transferred from $f[i-k-1]$, that is, $f[i] = \\min(f[i], f[i-k-1] + k)$.\n\nFinally, if $f[n-1] \\geq \\infty$, it means that it cannot be converted into a strictly increasing array, return $-1$, otherwise return $f[n-1]$.\n\nThe time complexity is $(n \\times (\\log m + \\min(m, n)))$, and the space complexity is $O(n)$. Here, $n$ is the length of $arr1$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1188, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1189, "explanations": { "1": "We count the frequency of each letter in the string `text`, and then divide the frequency of the letters 'o' and 'l' by 2, because the word `balloon` contains the letters 'o' and 'l' twice.\n\nNext, we traverse each letter in the word `balon`, and find the minimum frequency of each letter in the string `text`. This minimum frequency is the maximum number of times the word `balloon` can appear in the string `text`.\n\nThe time complexity is $O(n)$, and the space complexity is $O(C)$. Here, $n$ is the length of the string `text`, and $C$ is the size of the character set. In this problem, $C = 26$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(C)" }, { "problem_id": 1190, "explanations": { "1": "We can directly use a stack to simulate the reversal process.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$, where $n$ is the length of the string $s$.", "2": "We observe that, when traversing the string, each time we encounter `(` or `)`, we jump to the corresponding `)` or `(` and then reverse the direction of traversal to continue.\n\nTherefore, we can use an array $d$ to record the position of the corresponding other bracket for each `(` or `)`, i.e., $d[i]$ represents the position of the other bracket corresponding to the bracket at position $i$. We can directly use a stack to compute the array $d$.\n\nThen, we traverse the string from left to right. When encountering `(` or `)`, we jump to the corresponding position according to the array $d$, then reverse the direction and continue traversing until the entire string is traversed.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 1191, "explanations": { "1": "We denote the sum of all elements in the array $arr$ as $s$, the maximum prefix sum as $mxPre$, the minimum prefix sum as $miPre$, and the maximum subarray sum as $mxSub$.\n\nWe traverse the array $arr$. For each element $x$, we update $s = s + x$, $mxPre = \\max(mxPre, s)$, $miPre = \\min(miPre, s)$, $mxSub = \\max(mxSub, s - miPre)$.\n\nNext, we consider the value of $k$:\n\n- When $k = 1$, the answer is $mxSub$.\n- When $k \\ge 2$, if the maximum subarray spans two $arr$, then the answer is $mxPre + mxSuf$, where $mxSuf = s - miPre$.\n- When $k \\ge 2$ and $s > 0$, if the maximum subarray spans three $arr$, then the answer is $(k - 2) \\times s + mxPre + mxSuf$.\n\nFinally, we return the result of the answer modulo $10^9 + 7$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the array $arr$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1192, "explanations": { "1": "The \"critical connections\" in this problem can be considered as \"bridges\".\n\n\"Bridges\": In a connected undirected graph, if removing a certain edge makes the graph disconnected, then this edge can be considered as a \"bridge\".\n\nCorrespondingly, there is also the concept of \"articulation points\".\n\n\"Articulation Points\": In a connected undirected graph, if removing a certain point and all edges connected to it makes the graph disconnected, then this point can be considered as an \"articulation point\".\n\nThere is an algorithm called the Tarjan algorithm for finding \"bridges\" and \"articulation points\" in a graph. This algorithm uses a depth-first search (DFS) method that first recursively visits adjacent nodes and then visits the node itself. By recording the \"order of visit: DFN\" and updating the \"earliest backtrackable node: low\" when visiting the node itself after recursion ends, it can find the \"bridges\" and \"articulation points\" of the graph in $O(n)$ time. Also, this algorithm can be used to find strongly connected components in directed graphs." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1193, "explanations": { "1": "We can first group by month and country, and then use the `COUNT` and `SUM` functions to respectively calculate the number of transactions, the number of approved transactions, the total amount, and the total amount of approved transactions for each group." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1194, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1195, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1196, "explanations": { "1": "To maximize the number of apples, we should try to minimize the weight of the apples. Therefore, we can sort the weights of the apples, and then put them into the basket in ascending order until the weight of the basket exceeds $5000$. We then return the number of apples in the basket at this point.\n\nIf all the apples can be put into the basket, then we return the total number of apples.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the number of apples." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 1197, "explanations": { "1": "This problem can be solved using the BFS shortest path model. The search space for this problem is not large, so we can directly use the naive BFS. The solution below also provides the code for bidirectional BFS for reference.\n\nBidirectional BFS is a common optimization method for BFS. The main implementation ideas are as follows:\n\n1. Create two queues, q1 and q2, for \"start -> end\" and \"end -> start\" search directions, respectively.\n2. Create two hash maps, m1 and m2, to record the visited nodes and their corresponding expansion times (steps).\n3. During each search, prioritize the queue with fewer elements for search expansion. If a node visited from the other direction is found during the expansion, it means the shortest path has been found.\n4. If one of the queues is empty, it means that the search in the current direction cannot continue, indicating that the start and end points are not connected, and there is no need to continue the search.", "2": "" }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1198, "explanations": { "1": "We use an array $cnt$ of length $10001$ to count the frequency of each number. We sequentially traverse each number in the matrix and increment its frequency. When the frequency of a number equals the number of rows in the matrix, it means that this number appears in each row, and thus it is the smallest common element. We return this number.\n\nIf we do not find the smallest common element after the traversal, we return $-1$.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(10^4)$. Here, $m$ and $n$ are the number of rows and columns in the matrix, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(10^4)" }, { "problem_id": 1199, "explanations": { "1": "First, consider the case where there is only one block. In this case, there is no need to split the worker, just let him build the block directly. The time cost is $block[0]$.\n\nIf there are two blocks, you need to split the worker into two, and then let them build the blocks separately. The time cost is $split + \\max(block[0], block[1])$.\n\nIf there are more than two blocks, at each step you need to consider how many workers to split. This is not easy to handle with forward thinking.\n\nWe might as well use reverse thinking, not splitting workers, but merging blocks. We select any two blocks $i$, $j$ for merging. The time to build a new block is $split + \\max(block[i], block[j])$.\n\nIn order to let the blocks with long time consumption participate in the merge as little as possible, we can greedily select the two blocks with the smallest time consumption for merging each time. Therefore, we can maintain a min heap, take out the two smallest blocks for merging each time, until there is only one block left. The build time of the last remaining block is the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the number of blocks." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1200, "explanations": { "1": "According to the problem description, we need to find the minimum absolute difference between any two elements in the array $arr$. Therefore, we can first sort the array $arr$, then traverse the adjacent elements to get the minimum absolute difference $mi$.\n\nFinally, we traverse the adjacent elements again to find all pairs of elements where the minimum absolute difference equals $mi$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array $arr$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 1201, "explanations": { "1": "We can transform the problem into: find the smallest positive integer $x$ such that the number of ugly numbers less than or equal to $x$ is exactly $n$.\n\nFor a positive integer $x$, there are $\\left\\lfloor \\frac{x}{a} \\right\\rfloor$ numbers divisible by $a$, $\\left\\lfloor \\frac{x}{b} \\right\\rfloor$ numbers divisible by $b$, $\\left\\lfloor \\frac{x}{c} \\right\\rfloor$ numbers divisible by $c$, $\\left\\lfloor \\frac{x}{lcm(a, b)} \\right\\rfloor$ numbers divisible by both $a$ and $b$, $\\left\\lfloor \\frac{x}{lcm(a, c)} \\right\\rfloor$ numbers divisible by both $a$ and $c$, $\\left\\lfloor \\frac{x}{lcm(b, c)} \\right\\rfloor$ numbers divisible by both $b$ and $c$, and $\\left\\lfloor \\frac{x}{lcm(a, b, c)} \\right\\rfloor$ numbers divisible by $a$, $b$, and $c$ at the same time. According to the inclusion-exclusion principle, the number of ugly numbers less than or equal to $x$ is:\n\n$$\n\\left\\lfloor \\frac{x}{a} \\right\\rfloor + \\left\\lfloor \\frac{x}{b} \\right\\rfloor + \\left\\lfloor \\frac{x}{c} \\right\\rfloor - \\left\\lfloor \\frac{x}{lcm(a, b)} \\right\\rfloor - \\left\\lfloor \\frac{x}{lcm(a, c)} \\right\\rfloor - \\left\\lfloor \\frac{x}{lcm(b, c)} \\right\\rfloor + \\left\\lfloor \\frac{x}{lcm(a, b, c)} \\right\\rfloor\n$$\n\nWe can use binary search to find the smallest positive integer $x$ such that the number of ugly numbers less than or equal to $x$ is exactly $n$.\n\nDefine the left boundary of binary search as $l=1$ and the right boundary as $r=2 \\times 10^9$, where $2 \\times 10^9$ is the maximum value given by the problem. In each step of binary search, we find the middle number $mid$. If the number of ugly numbers less than or equal to $mid$ is greater than or equal to $n$, it means that the smallest positive integer $x$ falls in the interval $[l,mid]$, otherwise it falls in the interval $[mid+1,r]$. During the binary search process, we need to continuously update the number of ugly numbers less than or equal to $mid$ until we find the smallest positive integer $x$.\n\nThe time complexity is $O(\\log m)$, where $m = 2 \\times 10^9$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log m)", "space_complexity": "O(1)" }, { "problem_id": 1202, "explanations": { "1": "We notice that the index pairs have transitivity, i.e., if $a$ and $b$ can be swapped, and $b$ and $c$ can be swapped, then $a$ and $c$ can also be swapped. Therefore, we can consider using a union-find data structure to maintain the connectivity of these index pairs, and sort the characters belonging to the same connected component in lexicographical order.\n\nFinally, we traverse the string. For the character at the current position, we replace it with the smallest character in the connected component, then remove this character from the connected component, and continue to traverse the string.\n\nThe time complexity is $O(n \\times \\log n + m \\times \\alpha(m))$, and the space complexity is $O(n)$. Here, $n$ and $m$ are the length of the string and the number of index pairs, respectively, and $\\alpha$ is the inverse Ackermann function." }, "is_english": true, "time_complexity": "O(n \\times \\log n + m \\times \\alpha(m))", "space_complexity": "O(n)" }, { "problem_id": 1203, "explanations": { "1": "First, we traverse the array $group$. For each project, if it does not belong to any group, we create a new group for it with the ID $m$, and increment $m$. This ensures that all projects belong to some group. Then, we use an array $groupItems$ to record the projects contained in each group. The array index is the group ID, and the array value is the list of projects in the group.\n\nNext, we need to build the graph. For each project, we need to build two types of graphs: one for the projects and one for the groups. We traverse the array $group$. For the current project $i$, its group is $group[i]$. We traverse $beforeItems[i]$, and for each project $j$ in it, if $group[i] = group[j]$, it means that $i$ and $j$ belong to the same group. We add an edge $j \\to i$ in the project graph. Otherwise, it means that $i$ and $j$ belong to different groups. We add an edge $group[j] \\to group[i]$ in the group graph, and update the corresponding in-degree array.\n\nNext, we perform topological sorting on the group graph to get the sorted group list $groupOrder$. If the length of the sorted list is not equal to the total number of groups, it means that the sorting cannot be completed, so we return an empty list. Otherwise, we traverse $groupOrder$, and for each group $gi$, we perform topological sorting on the project list $groupItems[gi]$ to get the sorted project list $itemOrder$. If the length of the sorted list is not equal to the total number of projects in the group, it means that the sorting cannot be completed, so we return an empty list. Otherwise, we add the projects in $itemOrder$ to the answer array, and finally return this answer array.\n\nThe time complexity is $O(n + m)$, and the space complexity is $O(n + m)$. Here, $n$ and $m$ are the total number of projects and groups, respectively." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(n + m)" }, { "problem_id": 1204, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1205, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1206, "explanations": { "1": "The core idea of a skip list is to use multiple \"levels\" to store data, with each level acting as an index. Data starts from the bottom level linked list and gradually rises to higher levels, eventually forming a multi-level linked list structure. Each level's nodes only contain part of the data, allowing for jumps to reduce search time.\n\nIn this problem, we use a $\\textit{Node}$ class to represent the nodes of the skip list. Each node contains a $\\textit{val}$ field and a $\\textit{next}$ array. The length of the array is $\\textit{level}$, indicating the next node at each level. We use a $\\textit{Skiplist}$ class to implement the skip list operations.\n\nThe skip list contains a head node $\\textit{head}$ and the current maximum level $\\textit{level}$. The head node's value is set to $-1$ to mark the starting position of the list. We use a dynamic array $\\textit{next}$ to store pointers to successor nodes.\n\nFor the $\\textit{search}$ operation, we start from the highest level of the skip list and traverse downwards until we find the target node or determine that the target node does not exist. At each level, we use the $\\textit{find\\_closest}$ method to jump to the node closest to the target.\n\nFor the $\\textit{add}$ operation, we first randomly decide the level of the new node. Then, starting from the highest level, we find the node closest to the new value at each level and insert the new node at the appropriate position. If the level of the inserted node is greater than the current maximum level of the skip list, we need to update the level of the skip list.\n\nFor the $\\textit{erase}$ operation, similar to the search operation, we traverse each level of the skip list to find and delete the target node. When deleting a node, we need to update the $\\textit{next}$ pointers at each level. If the highest level of the skip list has no nodes, we need to decrease the level of the skip list.\n\nAdditionally, we define a $\\textit{random\\_level}$ method to randomly decide the level of the new node. This method generates a random number between $[1, \\textit{max\\_level}]$ until the generated random number is greater than or equal to $\\textit{p}$. We also have a $\\textit{find\\_closest}$ method to find the node closest to the target value at each level.\n\nThe time complexity of the above operations is $O(\\log n)$, where $n$ is the number of nodes in the skip list. The space complexity is $O(n)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(n)" }, { "problem_id": 1207, "explanations": { "1": "We use a hash table $cnt$ to count the frequency of each number in the array $arr$, and then use another hash table $vis$ to count the types of frequencies. Finally, we check whether the sizes of $cnt$ and $vis$ are equal.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $arr$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1208, "explanations": { "1": "We can create an array $f$ of length $n + 1$, where $f[i]$ represents the sum of the absolute differences of ASCII values between the first $i$ characters of string $s$ and the first $i$ characters of string $t$. Thus, we can calculate the sum of the absolute differences of ASCII values from the $i$-th character to the $j$-th character of string $s$ by $f[j + 1] - f[i]$, where $0 \\leq i \\leq j < n$.\n\nNote that the length has monotonicity, i.e., if there exists a substring of length $x$ that satisfies the condition, then a substring of length $x - 1$ must also satisfy the condition. Therefore, we can use binary search to find the maximum length.\n\nWe define a function $check(x)$, which indicates whether there exists a substring of length $x$ that satisfies the condition. In this function, we only need to enumerate all substrings of length $x$ and check whether they satisfy the condition. If there exists a substring that satisfies the condition, the function returns `true`, otherwise it returns `false`.\n\nNext, we define the left boundary $l$ of binary search as $0$ and the right boundary $r$ as $n$. In each step, we let $mid = \\lfloor \\frac{l + r + 1}{2} \\rfloor$. If the return value of $check(mid)$ is `true`, we update the left boundary to $mid$, otherwise we update the right boundary to $mid - 1$. After the binary search, the left boundary we get is the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of string $s$.", "2": "We can maintain two pointers $l$ and $r$, initially $l = r = 0$; maintain a variable $\\textit{cost}$, which represents the sum of the absolute values of the ASCII code differences in the index interval $[l,..r]$. In each step, we move $r$ to the right by one position, then update $\\textit{cost} = \\textit{cost} + |s[r] - t[r]|$. If $\\textit{cost} \\gt \\textit{maxCost}$, then we loop to move $l$ to the right by one position, and decrease the value of $\\textit{cost}$, until $\\textit{cost} \\leq \\textit{maxCost}$. Then we update the answer, that is, $\\textit{ans} = \\max(\\textit{ans}, r - l + 1)$.\n\nFinally, return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$.", "3": "In Solution 2, the interval maintained by the two pointers may become shorter or longer. Since the problem only requires the maximum length, we can maintain a monotonically increasing interval.\n\nSpecifically, we use two pointers $l$ and $r$ to point to the left and right endpoints of the interval, initially $l = r = 0$. In each step, we move $r$ to the right by one position, then update $\\textit{cost} = \\textit{cost} + |s[r] - t[r]|$. If $\\textit{cost} \\gt \\textit{maxCost}$, then we move $l$ to the right by one position, and decrease the value of $\\textit{cost}$.\n\nFinally, return $n - l$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$. Where $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1209, "explanations": { "1": "We can traverse the string $s$, maintaining a stack that stores the characters and their occurrence counts. When traversing to character $c$, if the character at the top of the stack is the same as $c$, we increment the count of the top element by one; otherwise, we push the character $c$ and count $1$ into the stack. When the count of the top element equals $k$, we pop the top element from the stack.\n\nAfter traversing the string $s$, the elements remaining in the stack form the final result. We can pop the elements from the stack one by one, concatenate them into a string, and that's our answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1210, "explanations": { "1": "The problem asks for the minimum number of moves for the snake to reach the target position from the starting position. We consider using Breadth-First Search (BFS) to solve it.\n\nWe define the following data structures or variables:\n\n- Queue $q$: Stores the current position of the snake. Each position is a tuple $(a, b)$, where $a$ represents the tail position of the snake, and $b$ represents the head position of the snake. Initially, we add the position $(0, 1)$ to the queue $q$. If we flatten the 2D maze into a 1D array, then the position $(0, 1)$ represents the two cells with indices $0$ and $1$ in the 1D array.\n- Target position $target$: The value is fixed at $(n^2 - 2, n^2 - 1)$, which is the last two cells of the last row of the 2D maze.\n- Array or set $vis$: Stores whether the current position state of the snake has been visited. Each state is a tuple $(a, status)$, where $a$ represents the tail position of the snake, and $status$ represents the current state of the snake, with values of $0$ or $1$, representing the horizontal and vertical states of the snake, respectively. Initially, add the state of the starting position $(0, 1)$ to the set $vis$.\n- Answer variable $ans$: Stores the number of moves for the snake to reach the target position from the starting position. Initially, it is $0$.\n\nWe use BFS to solve it. Each time we take a position from the queue $q$, we check whether the position is the target position $target$. If it is, we directly return the answer variable $ans$. If not, we add the next possible position of this position to the queue $q$ and add this position to $vis$. Note that the next position could be the horizontal or vertical state of the snake, and we need to judge them separately (see the following code comments). At the end of each round of search, the answer variable $ans$ increments by $1$.\n\nFinally, if the queue $q$ is empty, it means that it is impossible to reach the target position from the starting position, so return $-1$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ is the number of rows or columns of the 2D maze." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 1211, "explanations": { "1": "We can group the query results by `query_name`, and then use the `AVG` and `ROUND` functions to calculate `quality` and `poor_query_percentage`." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1212, "explanations": { "1": "We can join the `Teams` table and the `Matches` table using a left join, where the join condition is `team_id = host_team OR team_id = guest_team`, to obtain all the match information for each team.\n\nNext, we group by `team_id` and use a `CASE` expression to calculate the points for each team according to the following rules:\n\n- If the team is the host team and has more goals than the guest team, add $3$ points to the team's score.\n- If the team is the guest team and has more goals than the host team, add $3$ points to the team's score.\n- If the host team and the guest team have the same number of goals, add $1$ point to the team's score.\n\nFinally, we sort the result by points in descending order, and if the points are the same, we sort by `team_id` in ascending order." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1213, "explanations": { "1": "Traverse the three arrays, count the occurrence of each number, then traverse any one of the arrays. If the count of a number is $3$, add it to the result array.\n\nThe time complexity is $O(n)$, and the space complexity is $O(m)$. Here, $n$ and $m$ are the length of the array and the range of numbers in the array, respectively.", "2": "Traverse the first array. For each number, use binary search to find this number in the second and third arrays. If found in both, add this number to the result array.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(m)" }, { "problem_id": 1214, "explanations": { "1": "We perform in-order traversals on the two trees separately, obtaining two sorted arrays $nums[0]$ and $nums[1]$. Then we use a two-pointer method to determine whether there exist two numbers whose sum equals the target value. The two-pointer method is as follows:\n\nInitialize two pointers $i$ and $j$, pointing to the left boundary of array $nums[0]$ and the right boundary of array $nums[1]$ respectively;\n\nEach time, compare the sum $x = nums[0][i] + nums[1][j]$ with the target value. If $x = target$, return `true`; otherwise, if $x \\lt target$, move $i$ one step to the right; otherwise, if $x \\gt target$, move $j$ one step to the left.\n\nThe time complexity is $O(m + n)$, and the space complexity is $O(m + n)$. Here, $m$ and $n$ are the number of nodes in the two trees respectively." }, "is_english": true, "time_complexity": "O(m + n)", "space_complexity": "O(m + n)" }, { "problem_id": 1215, "explanations": { "1": "First, if $low$ is $0$, we need to add $0$ to the answer.\n\nNext, we create a queue $q$ and add $1 \\sim 9$ to the queue. Then, we repeatedly take out elements from the queue. Let the current element be $v$. If $v$ is greater than $high$, we stop searching. If $v$ is in the range $[low, high]$, we add $v$ to the answer. Then, we need to record the last digit of $v$ as $x$. If $x \\gt 0$, we add $v \\times 10 + x - 1$ to the queue. If $x \\lt 9$, we add $v \\times 10 + x + 1$ to the queue. Repeat the above steps until the queue is empty.\n\nThe time complexity is $O(10 \\times 2^{\\log M})$, and the space complexity is $O(2^{\\log M})$, where $M$ is the number of digits in $high$." }, "is_english": true, "time_complexity": "O(10 \\times 2^{\\log M})", "space_complexity": "O(2^{\\log M})" }, { "problem_id": 1216, "explanations": { "1": "The problem requires us to remove at most $k$ characters to make the remaining string a palindrome. This can be transformed into finding the longest palindromic subsequence.\n\nWe define $f[i][j]$ as the length of the longest palindromic subsequence in the substring $s[i..j]$. Initially, we have $f[i][i] = 1$ for all $i$, since each single character is a palindrome.\n\nIf $s[i] = s[j]$, then we have $f[i][j] = f[i+1][j-1] + 2$, since we can add both $s[i]$ and $s[j]$ to the longest palindromic subsequence of $s[i+1..j-1]$.\n\nIf $s[i] \\neq s[j]$, then we have $f[i][j] = \\max(f[i+1][j], f[i][j-1])$, since we need to remove either $s[i]$ or $s[j]$ to make the remaining substring a palindrome.\n\nFinally, we check whether there exists $f[i][j] + k \\geq n$, where $n$ is the length of the string $s$. If so, it means that we can remove at most $k$ characters to make the remaining string a palindrome.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 1217, "explanations": { "1": "Move all chips at even indices to position 0, and all chips at odd indices to position 1, all at a cost of 0. Then, choose the position (either 0 or 1) with fewer chips and move these chips to the other position. The minimum cost required is the smaller quantity of chips.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the number of chips." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1218, "explanations": { "1": "We can use a hash table $f$ to store the length of the longest arithmetic subsequence ending with $x$.\n\nTraverse the array $\\textit{arr}$, and for each element $x$, update $f[x]$ to be $f[x - \\textit{difference}] + 1$.\n\nAfter the traversal, return the maximum value in $f$ as the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{arr}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1219, "explanations": { "1": "We can enumerate each cell as the starting point, and then start a depth-first search from the starting point. During the search process, whenever we encounter a non-zero cell, we turn it into zero and continue the search. When we can no longer continue the search, we calculate the total amount of gold in the current path, then turn the current cell back into a non-zero cell, thus performing backtracking.\n\nThe time complexity is $O(m \\times n \\times 3^k)$, where $k$ is the maximum length of each path. Since each cell can only be visited once at most, the time complexity will not exceed $O(m \\times n \\times 3^k)$. The space complexity is $O(m \\times n)$." }, "is_english": true, "time_complexity": "O(m \\times n \\times 3^k)", "space_complexity": "O(m \\times n)" }, { "problem_id": 1220, "explanations": { "1": "Based on the problem description, we can list the possible subsequent vowels for each vowel:\n\n```bash\na [e]\ne [a|i]\ni [a|e|o|u]\no [i|u]\nu [a]\n```\n\nFrom this, we can deduce the possible preceding vowels for each vowel:\n\n```bash\n[e|i|u]\ta\n[a|i]\te\n[e|o]\ti\n[i]\to\n[i|o]\tu\n```\n\nWe define $f[i]$ as the number of strings of the current length ending with the $i$-th vowel. If the length is $1$, then $f[i]=1$.\n\nWhen the length is greater than $1$, we define $g[i]$ as the number of strings of the current length ending with the $i$-th vowel. Then $g[i]$ can be derived from $f$, that is:\n\n$$\ng[i]=\n\\begin{cases}\nf[1]+f[2]+f[4] & i=0 \\\\\nf[0]+f[2] & i=1 \\\\\nf[1]+f[3] & i=2 \\\\\nf[2] & i=3 \\\\\nf[2]+f[3] & i=4\n\\end{cases}\n$$\n\nThe final answer is $\\sum_{i=0}^{4}f[i]$. Note that the answer may be very large, so we need to take the modulus of $10^9+7$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(C)$. Here, $n$ is the length of the string, and $C$ is the number of vowels. In this problem, $C=5$.", "2": "The time complexity is $O(C^3 \\times \\log n)$, and the space complexity is $O(C^2)$. Here, $C$ is the number of vowels. In this problem, $C=5$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(C)" }, { "problem_id": 1221, "explanations": { "1": "We use a variable $l$ to maintain the current balance of the string, i.e., the value of $l$ is the number of 'L's minus the number of 'R's in the current string. When the value of $l$ is 0, we have found a balanced string.\n\nWe traverse the string $s$. When we traverse to the $i$-th character, if $s[i] = L$, then the value of $l$ is increased by 1, otherwise, the value of $l$ is decreased by 1. When the value of $l$ is 0, we increase the answer by 1.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1222, "explanations": { "1": "First, we store all the positions of the queens in a hash table or a two-dimensional array $s$.\n\nNext, starting from the position of the king, we search in the eight directions: up, down, left, right, upper left, upper right, lower left, and lower right. If there is a queen in a certain direction, we add its position to the answer and stop continuing to search in that direction.\n\nAfter the search is over, we return the answer.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. In this problem, $n = 8$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 1223, "explanations": { "1": "We can design a function $dfs(i, j, x)$ to represent the number of schemes starting from the $i$-th dice roll, with the current dice roll being $j$, and the number of consecutive times $j$ is rolled being $x$. The range of $j$ is $[1, 6]$, and the range of $x$ is $[1, rollMax[j - 1]]$. The answer is $dfs(0, 0, 0)$.\n\nThe calculation process of the function $dfs(i, j, x)$ is as follows:\n\n- If $i \\ge n$, it means that $n$ dice have been rolled, return $1$.\n- Otherwise, we enumerate the number $k$ rolled next time. If $k \\ne j$, we can directly roll $k$, and the number of consecutive times $j$ is rolled will be reset to $1$, so the number of schemes is $dfs(i + 1, k, 1)$. If $k = j$, we need to judge whether $x$ is less than $rollMax[j - 1]$. If it is less, we can continue to roll $j$, and the number of consecutive times $j$ is rolled will increase by $1$, so the number of schemes is $dfs(i + 1, j, x + 1)$. Finally, add all the scheme numbers to get the value of $dfs(i, j, x)$. Note that the answer may be very large, so we need to take the modulus of $10^9 + 7$.\n\nDuring the process, we can use memoization search to avoid repeated calculations.\n\nThe time complexity is $O(n \\times k^2 \\times M)$, and the space complexity is $O(n \\times k \\times M)$. Here, $k$ is the range of dice points, and $M$ is the maximum number of times a certain point can be rolled consecutively.", "2": "We can change the memoization search in Solution 1 to dynamic programming.\n\nDefine $f[i][j][x]$ as the number of schemes for the first $i$ dice rolls, with the $i$-th dice roll being $j$, and the number of consecutive times $j$ is rolled being $x$. Initially, $f[1][j][1] = 1$, where $1 \\leq j \\leq 6$. The answer is:\n\n$$\n\\sum_{j=1}^6 \\sum_{x=1}^{rollMax[j-1]} f[n][j][x]\n$$\n\nWe enumerate the last dice roll as $j$, and the number of consecutive times $j$ is rolled as $x$. The current dice roll can be $1, 2, \\cdots, 6$. If the current dice roll is $k$, there are two cases:\n\n- If $k \\neq j$, we can directly roll $k$, and the number of consecutive times $j$ is rolled will be reset to $1$. Therefore, the number of schemes $f[i][k][1]$ will increase by $f[i-1][j][x]$.\n- If $k = j$, we need to judge whether $x+1$ is less than or equal to $rollMax[j-1]$. If it is less than or equal to, we can continue to roll $j$, and the number of consecutive times $j$ is rolled will increase by $1$. Therefore, the number of schemes $f[i][j][x+1]$ will increase by $f[i-1][j][x]$.\n\nThe final answer is the sum of all $f[n][j][x]$.\n\nThe time complexity is $O(n \\times k^2 \\times M)$, and the space complexity is $O(n \\times k \\times M)$. Here, $k$ is the range of dice points, and $M$ is the maximum number of times a certain point can be rolled consecutively." }, "is_english": true, "time_complexity": "O(n \\times k^2 \\times M)", "space_complexity": "O(n \\times k \\times M)" }, { "problem_id": 1224, "explanations": { "1": "We use $cnt$ to record the number of times each element $v$ appears in $nums$, and $ccnt$ to record the number of times each count appears. The maximum number of times an element appears is represented by $mx$.\n\nWhile traversing $nums$:\n\n- If the maximum count $mx=1$, it means that each number in the current prefix appears $1$ time. If we delete any one of them, the remaining numbers will all have the same count.\n- If all numbers appear $mx$ and $mx-1$ times, and only one number appears $mx$ times, then we can delete one occurrence of the number that appears $mx$ times. The remaining numbers will all have a count of $mx-1$, which meets the condition.\n- If, except for one number, all other numbers appear $mx$ times, then we can delete the number that appears once. The remaining numbers will all have a count of $mx$, which meets the condition.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the $nums$ array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1225, "explanations": { "1": "We can merge the two tables into one table with a field `st` representing the status, where `failed` indicates failure and `succeeded` indicates success. Then, we can use a window function to group the records with the same status into one group, and calculate the difference between each date and its rank within the group as `pt`, which serves as the identifier for the same continuous status. Finally, we can group by `st` and `pt`, and calculate the minimum and maximum dates for each group, and sort by the minimum date." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1226, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1227, "explanations": { "1": "Let $f(n)$ represent the probability that the $n$th passenger will sit in their own seat when there are $n$ passengers boarding. Consider from the simplest case:\n\nWhen $n=1$, there is only 1 passenger and 1 seat, so the first passenger can only sit in the first seat, $f(1)=1$;\n\nWhen $n=2$, there are 2 seats, each seat has a probability of 0.5 to be chosen by the first passenger. After the first passenger chooses a seat, the second passenger can only choose the remaining seat, so the second passenger has a probability of 0.5 to sit in their own seat, $f(2)=0.5$.\n\nWhen $n>2$, how to calculate the value of $f(n)$? Consider the seat chosen by the first passenger, there are three cases.\n\n- The first passenger has a probability of $\\frac{1}{n}$ to choose the first seat, then all passengers can sit in their own seats, so the probability of the $n$th passenger sitting in their own seat is 1.0.\n\n- The first passenger has a probability of $\\frac{1}{n}$ to choose the $n$th seat, then the second to the $(n-1)$th passengers can sit in their own seats, the $n$th passenger can only sit in the first seat, so the probability of the $n$th passenger sitting in their own seat is 0.0.\n\n- The first passenger has a probability of $\\frac{n-2}{n}$ to choose the remaining seats, each seat has a probability of $\\frac{1}{n}$ to be chosen.\n Suppose the first passenger chooses the $i$th seat, where $2 \\le i \\le n-1$, then the second to the $(i-1)$th passengers can sit in their own seats, the seats of the $i$th to the $n$th passengers are uncertain, the $i$th passenger will randomly choose from the remaining $n-(i-1)=n-i+1$ seats (including the first seat and the $(i+1)$th to the $n$th seats). Since the number of remaining passengers and seats is $n-i+1$, and 1 passenger will randomly choose a seat, the problem size is reduced from $n$ to $n-i+1$.\n\nCombining the above three cases, we can get the recursive formula of $f(n)$:\n\n$$\n\\begin{aligned}\nf(n) &= \\frac{1}{n} \\times 1.0 + \\frac{1}{n} \\times 0.0 + \\frac{1}{n} \\times \\sum_{i=2}^{n-1} f(n-i+1) \\\\\n&= \\frac{1}{n}(1.0+\\sum_{i=2}^{n-1} f(n-i+1))\n\\end{aligned}\n$$\n\nIn the above recursive formula, there are $n-2$ values of $i$, since the number of values of $i$ must be a non-negative integer, so the above recursive formula only holds when $n-2 \\ge 0$ i.e., $n \\ge 2$.\n\nIf you directly use the above recursive formula to calculate the value of $f(n)$, the time complexity is $O(n^2)$, which cannot pass all test cases, so it needs to be optimized.\n\nReplace $n$ with $n-1$ in the above recursive formula, you can get the recursive formula:\n\n$$\nf(n-1) = \\frac{1}{n-1}(1.0+\\sum_{i=2}^{n-2} f(n-i))\n$$\n\nIn the above recursive formula, there are $n-3$ values of $i$, and the above recursive formula only holds when $n-3 \\ge 0$ i.e., $n \\ge 3$.\n\nWhen $n \\ge 3$, the above two recursive formulas can be written as follows:\n\n$$\n\\begin{aligned}\nn \\times f(n) &= 1.0+\\sum_{i=2}^{n-1} f(n-i+1) \\\\\n(n-1) \\times f(n-1) &= 1.0+\\sum_{i=2}^{n-2} f(n-i)\n\\end{aligned}\n$$\n\nSubtract the above two formulas:\n\n$$\n\\begin{aligned}\n&~~~~~ n \\times f(n) - (n-1) \\times f(n-1) \\\\\n&= (1.0+\\sum_{i=2}^{n-1} f(n-i+1)) - (1.0+\\sum_{i=2}^{n-2} f(n-i)) \\\\\n&= \\sum_{i=2}^{n-1} f(n-i+1) - \\sum_{i=2}^{n-2} f(n-i) \\\\\n&= f(2)+f(3)+...+f(n-1) - (f(2)+f(3)+...+f(n-2)) \\\\\n&= f(n-1)\n\\end{aligned}\n$$\n\nAfter simplification, we get the simplified recursive formula:\n\n$$\n\\begin{aligned}\nn \\times f(n) &= n \\times f(n-1) \\\\\nf(n) &= f(n-1)\n\\end{aligned}\n$$\n\nSince we know that $f(1)=1$ and $f(2)=0.5$, therefore when $n \\ge 3$, according to $f(n) = f(n-1)$, we know that for any positive integer $n$, $f(n)=0.5$. And since $f(2)=0.5$, therefore when $n \\ge 2$, for any positive integer $n$, $f(n)=0.5$.\n\nFrom this, we can get the result of $f(n)$:\n\n$$\nf(n) = \\begin{cases}\n1.0, & n = 1 \\\\\n0.5, & n \\ge 2\n\\end{cases}\n$$\n\nThe time complexity of this solution is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(1)" }, { "problem_id": 1228, "explanations": { "1": "The sum formula for an arithmetic series is $\\frac{(a_1 + a_n)n}{2}$, where $n$ is the number of terms in the arithmetic series, the first term is $a_1$, and the last term is $a_n$.\n\nSince the array given in the problem is an arithmetic series with one missing number, the number of terms in the array is $n + 1$, the first term is $a_1$, and the last term is $a_n$. Therefore, the sum of the array is $\\frac{(a_1 + a_n)(n + 1)}{2}$.\n\nThus, the missing number is $\\frac{(a_1 + a_n)(n + 1)}{2} - \\sum_{i = 0}^n a_i$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$.", "2": "Since the array given in the problem is an arithmetic series with one missing number, the first term is $a_1$, and the last term is $a_n$. The common difference $d$ is $\\frac{a_n - a_1}{n}$.\n\nTraverse the array, and if $a_i \\neq a_{i - 1} + d$, then return $a_{i - 1} + d$.\n\nIf the traversal completes without finding the missing number, it means all numbers in the array are equal. In this case, directly return the first number of the array.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1229, "explanations": { "1": "We can sort the free time intervals of both people, then use two pointers to traverse the two arrays and find the intersection of the free time intervals of both people. If the length of the intersection is greater than or equal to `duration`, return the start time of the intersection and the start time plus `duration`. Otherwise, if the end time of the first person's free time interval is less than the end time of the second person's free time interval, move the first person's pointer; otherwise, move the second person's pointer. Continue traversing until a suitable time interval is found or the traversal ends.\n\nThe time complexity is $O(m \\times \\log m + n \\times \\log n)$, and the space complexity is $O(\\log m + \\log n)$. Here, $m$ and $n$ are the lengths of the two arrays, respectively." }, "is_english": true, "time_complexity": "O(m \\times \\log m + n \\times \\log n)", "space_complexity": "O(\\log m + \\log n)" }, { "problem_id": 1230, "explanations": { "1": "Let $f[i][j]$ represent the probability of having $j$ coins facing up in the first $i$ coins, and initially $f[0][0]=1$. The answer is $f[n][target]$.\n\nConsider $f[i][j]$, where $i \\geq 1$. If the current coin is facing down, then $f[i][j] = (1 - p) \\times f[i - 1][j]$; If the current coin is facing up and $j \\gt 0$, then $f[i][j] = p \\times f[i - 1][j - 1]$. Therefore, the state transition equation is:\n\n$$\nf[i][j] = \\begin{cases}\n(1 - p) \\times f[i - 1][j], & j = 0 \\\\\n(1 - p) \\times f[i - 1][j] + p \\times f[i - 1][j - 1], & j \\gt 0\n\\end{cases}\n$$\n\nwhere $p$ represents the probability of the $i$-th coin facing up.\n\nWe note that the state $f[i][j]$ is only related to $f[i - 1][j]$ and $f[i - 1][j - 1]$, so we can optimize the two-dimensional space into one-dimensional space.\n\nThe time complexity is $O(n \\times target)$, and the space complexity is $O(target)$. Where $n$ is the number of coins.", "2": "" }, "is_english": true, "time_complexity": "O(n \\times target)", "space_complexity": "O(target)" }, { "problem_id": 1231, "explanations": { "1": "We notice that if we can eat a piece of chocolate with sweetness $x$, then we can also eat all chocolates with sweetness less than or equal to $x$. This shows monotonicity, therefore, we can use binary search to find the maximum $x$ that satisfies the condition.\n\nWe define the left boundary of the binary search as $l=0$, and the right boundary as $r=\\sum_{i=0}^{n-1} sweetness[i]$. Each time, we take the middle value $mid$ of $l$ and $r$, and then determine whether we can eat a piece of chocolate with sweetness $mid$. If we can, then we try to eat a piece of chocolate with greater sweetness, i.e., let $l=mid$; otherwise, we try to eat a piece of chocolate with smaller sweetness, i.e., let $r=mid-1$. After the binary search ends, we return $l$.\n\nThe key to the problem is how to determine whether we can eat a piece of chocolate with sweetness $x$. We can use a greedy approach, traverse the array from left to right, accumulate the current sweetness each time, when the accumulated sweetness is greater than or equal to $x$, the chocolate count $cnt$ is increased by $1$, and the accumulated sweetness is reset to zero. Finally, check whether $cnt$ is greater than $k$.\n\nThe time complexity is $O(n \\times \\log \\sum_{i=0}^{n-1} sweetness[i])$, and the space complexity is $O(1)$. Where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n \\times \\log \\sum_{i=0}^{n-1} sweetness[i])", "space_complexity": "O(1)" }, { "problem_id": 1232, "explanations": { "1": "The time complexity is $O(n)$, where $n$ is the length of the `coordinates` array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1233, "explanations": { "1": "First, we sort the array `folder` in lexicographical order, then traverse the array. For the current folder $f$ we are traversing, if its length is greater than or equal to the length of the last folder in the answer array, and its prefix includes the last folder in the answer array plus a `/`, then $f$ is a subfolder of the last folder in the answer array, and we don't need to add it to the answer array. Otherwise, we add $f$ to the answer array.\n\nAfter the traversal ends, the folders in the answer array are the answer required by the problem.\n\nThe time complexity is $O(n \\times \\log n \\times m)$, and the space complexity is $O(m)$. Where $n$ and $m$ are the length of the array `folder` and the maximum length of the strings in the array `folder`, respectively.", "2": "We can use a trie to store all the folders in the array `folder`. Each node of the trie contains a `children` field, used to store the child nodes of the current node, and a `fid` field, used to store the index of the folder corresponding to the current node in the array `folder`.\n\nFor each folder $f$ in the array `folder`, we first split $f$ into several substrings according to `/`, then start from the root node and add the substrings to the trie in turn. Next, we start from the root node to search the trie. If the `fid` field of the current node is not `-1`, it means that the folder corresponding to the current node is a folder in the answer array. We add it to the answer array and return. Otherwise, we recursively search all child nodes of the current node and finally return the answer array.\n\nThe time complexity is $O(n \\times m)$, and the space complexity is $O(n \\times m)$. Where $n$ and $m$ are the length of the array `folder` and the maximum length of the strings in the array `folder`, respectively." }, "is_english": true, "time_complexity": "O(n \\times \\log n \\times m)", "space_complexity": "O(m)" }, { "problem_id": 1234, "explanations": { "1": "First, we use a hash table or array `cnt` to count the number of each character in string $s$. If the count of all characters does not exceed $n/4$, then the string $s$ is balanced, and we directly return $0$.\n\nOtherwise, we use two pointers $j$ and $i$ to maintain the left and right boundaries of the window, initially $j = 0$.\n\nNext, we traverse the string $s$ from left to right. Each time we encounter a character, we decrease its count by $1$, then we check whether the current window meets the condition, that is, the count of characters outside the window does not exceed $n/4$. If the condition is met, we update the answer, then move the left boundary of the window to the right until the condition is not met.\n\nFinally, we return the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(C)$. Where $n$ is the length of the string $s$; and $C$ is the size of the character set, in this problem $C = 4$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(C)" }, { "problem_id": 1235, "explanations": { "1": "First, we sort the jobs by start time in ascending order, then design a function $dfs(i)$ to represent the maximum profit that can be obtained starting from the $i$-th job. The answer is $dfs(0)$.\n\nThe calculation process of function $dfs(i)$ is as follows:\n\nFor the $i$-th job, we can choose to do it or not. If we don't do it, the maximum profit is $dfs(i + 1)$; if we do it, we can use binary search to find the first job that starts after the end time of the $i$-th job, denoted as $j$, then the maximum profit is $profit[i] + dfs(j)$. We take the larger of the two. That is:\n\n$$\ndfs(i)=\\max(dfs(i+1),profit[i]+dfs(j))\n$$\n\nWhere $j$ is the smallest index that satisfies $startTime[j] \\ge endTime[i]$.\n\nIn this process, we can use memoization search to save the answer of each state to avoid repeated calculations.\n\nThe time complexity is $O(n \\times \\log n)$, where $n$ is the number of jobs.", "2": "We can also change the memoization search in Solution 1 to dynamic programming.\n\nFirst, sort the jobs, this time we sort by end time in ascending order, then define $dp[i]$, which represents the maximum profit that can be obtained from the first $i$ jobs. The answer is $dp[n]$. Initialize $dp[0]=0$.\n\nFor the $i$-th job, we can choose to do it or not. If we don't do it, the maximum profit is $dp[i]$; if we do it, we can use binary search to find the last job that ends before the start time of the $i$-th job, denoted as $j$, then the maximum profit is $profit[i] + dp[j]$. We take the larger of the two. That is:\n\n$$\ndp[i+1] = \\max(dp[i], profit[i] + dp[j])\n$$\n\nWhere $j$ is the largest index that satisfies $endTime[j] \\leq startTime[i]$.\n\nThe time complexity is $O(n \\times \\log n)$, where $n$ is the number of jobs.\n\nSimilar problems:\n\n- [2008. Maximum Earnings From Taxi](https://github.com/doocs/leetcode/blob/main/solution/2000-2099/2008.Maximum%20Earnings%20From%20Taxi/README.md)\n- [1751. Maximum Number of Events That Can Be Attended II](https://github.com/doocs/leetcode/blob/main/solution/1700-1799/1751.Maximum%20Number%20of%20Events%20That%20Can%20Be%20Attended%20II/README.md)" }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": null }, { "problem_id": 1236, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1237, "explanations": { "1": "According to the problem, we know that the function $f(x, y)$ is a monotonically increasing function. Therefore, we can enumerate $x$, and then binary search $y$ in $[1,...z]$ to make $f(x, y) = z$. If found, add $(x, y)$ to the answer.\n\nThe time complexity is $O(n \\log n)$, where $n$ is the value of $z$, and the space complexity is $O(1)$.", "2": "We can define two pointers $x$ and $y$, initially $x = 1$, $y = z$.\n\n- If $f(x, y) = z$, we add $(x, y)$ to the answer, then $x \\leftarrow x + 1$, $y \\leftarrow y - 1$;\n- If $f(x, y) \\lt z$, at this time for any $y' \\lt y$, we have $f(x, y') \\lt f(x, y) \\lt z$, so we cannot decrease $y$, we can only increase $x$, so $x \\leftarrow x + 1$;\n- If $f(x, y) \\gt z$, at this time for any $x' \\gt x$, we have $f(x', y) \\gt f(x, y) \\gt z$, so we cannot increase $x$, we can only decrease $y$, so $y \\leftarrow y - 1$.\n\nAfter the loop ends, return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the value of $z$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(1)" }, { "problem_id": 1238, "explanations": { "1": "We observe the arrangement in the problem, and find that in its binary representation, only one bit is different between any two (including the first and last) adjacent numbers. This kind of coding method is Gray code, which is a coding method we will encounter in engineering.\n\nThe rule for converting binary code to binary Gray code is to keep the highest bit of the binary code as the highest bit of the Gray code, and the second highest bit of the Gray code is the XOR of the highest bit and the second highest bit of the binary code. The rest of the Gray code is similar to the second highest bit.\n\nAssume a binary number is represented as $B_{n-1}B_{n-2}...B_2B_1B_0$, its Gray code representation is $G_{n-1}G_{n-2}...G_2G_1G_0$. The highest bit is kept, so $G_{n-1} = B_{n-1}$; and the other bits $G_i = B_{i+1} \\oplus B_{i}$, where $i=0,1,2..,n-2$.\n\nTherefore, for an integer $x$, we can use the function $gray(x)$ to get its Gray code:\n\n```java\nint gray(x) {\n return x ^ (x >> 1);\n}\n```\n\nWe can directly convert the integers $[0,..2^n - 1]$ into the corresponding Gray code array, then find the position of $start$ in the Gray code array, cut the Gray code array from this position, and then append the cut part to the front of the Gray code array to get the arrangement required by the problem.\n\nThe time complexity is $O(2^n)$, and the space complexity is $O(2^n)$. Where $n$ is the integer given in the problem.", "2": "Since $gray(0) = 0$, then $gray(0) \\oplus start = start$, and $gray(i)$ is only one binary bit different from $gray(i-1)$, so $gray(i) \\oplus start$ is also only one binary bit different from $gray(i-1) \\oplus start$.\n\nTherefore, we can also directly convert the integers $[0,..2^n - 1]$ into the corresponding $gray(i) \\oplus start$ to get the Gray code arrangement with $start$ as the first term.\n\nThe time complexity is $O(2^n)$, where $n$ is the integer given in the problem. Ignoring the space consumption of the answer, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(2^n)", "space_complexity": "O(2^n)" }, { "problem_id": 1239, "explanations": { "1": "Since the problem requires that the characters in the subsequence must not be repeated and all characters are lowercase letters, we can use a binary integer of length $26$ to represent a subsequence. The $i$-th bit being $1$ indicates that the subsequence contains the $i$-th character, and $0$ indicates that it does not contain the $i$-th character.\n\nWe can use an array $s$ to store the states of all subsequences that meet the conditions. Initially, $s$ contains only one element $0$.\n\nThen we traverse the array $\\textit{arr}$. For each string $t$, we use an integer $x$ to represent the state of $t$. Then we traverse the array $s$. For each state $y$, if $x$ and $y$ have no common characters, we add the union of $x$ and $y$ to $s$ and update the answer.\n\nFinally, we return the answer.\n\nThe time complexity is $O(2^n + L)$, and the space complexity is $O(2^n)$. Here, $n$ is the length of the string array, and $L$ is the sum of the lengths of all strings in the array." }, "is_english": true, "time_complexity": "O(2^n + L)", "space_complexity": "O(2^n)" }, { "problem_id": 1240, "explanations": { "1": "We can perform recursive backtracking by position, during which we use a variable $t$ to record the current number of tiles used.\n\n- If $j = m$, i.e., the $i$-th row has been completely filled, then we recurse to the next row, i.e., $(i + 1, 0)$.\n- If $i = n$, it means that all positions have been filled, we update the answer and return.\n- If the current position $(i, j)$ has been filled, then directly recurse to the next position $(i, j + 1)$.\n- Otherwise, we enumerate the maximum square side length $w$ that the current position $(i, j)$ can fill, and fill all positions from $(i, j)$ to $(i + w - 1, j + w - 1)$, then recurse to the next position $(i, j + w)$. When backtracking, we need to clear all positions from $(i, j)$ to $(i + w - 1, j + w - 1)$.\n\nSince each position only has two states: filled or not filled, we can use an integer to represent the current state. We use an integer array $filled$ of length $n$, where $filled[i]$ represents the state of the $i$-th row. If the $j$-th bit of $filled[i]$ is $1$, it means that the $i$-th row and the $j$-th column have been filled, otherwise it means not filled.", "2": "" }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1241, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1242, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1243, "explanations": { "1": "Simulate each day. For each element, if it is greater than its left and right neighbors, it decreases by 1, otherwise, it increases by 1. If the array no longer changes on a certain day, return that array.\n\nThe time complexity is $O(n \\times m)$, and the space complexity is $O(n)$. Where $n$ is the length of the array, and $m$ is the maximum value in the array." }, "is_english": true, "time_complexity": "O(n \\times m)", "space_complexity": "O(n)" }, { "problem_id": 1244, "explanations": { "1": "We use a hash table $d$ to record the scores of each player, and an ordered list $rank$ to record the scores of all players.\n\nWhen the `addScore` function is called, we first check if the player is in the hash table $d$. If not, we add their score to the ordered list $rank$. Otherwise, we first remove their score from the ordered list $rank$, then add their updated score to the ordered list $rank$, and finally update the score in the hash table $d$. The time complexity is $O(\\log n)$.\n\nWhen the `top` function is called, we directly return the sum of the first $K$ elements in the ordered list $rank$. The time complexity is $O(K \\times \\log n)$.\n\nWhen the `reset` function is called, we first remove the player from the hash table $d$, then remove their score from the ordered list $rank$. The time complexity is $O(\\log n)$.\n\nThe space complexity is $O(n)$, where $n$ is the number of players." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(n)" }, { "problem_id": 1245, "explanations": { "1": "First, we arbitrarily select a node and start a depth-first search (DFS) from this node to find the farthest node from it, denoted as node $a$. Then, we start another DFS from node $a$ to find the farthest node from node $a$, denoted as node $b$. It can be proven that the path between node $a$ and node $b$ is the diameter of the tree.\n\nTime complexity is $O(n)$, and space complexity is $O(n)$, where $n$ is the number of nodes.\n\nSimilar problems:\n\n- [1522. Diameter of N-Ary Tree 🔒](https://github.com/doocs/leetcode/blob/main/solution/1500-1599/1522.Diameter%20of%20N-Ary%20Tree/README_EN.md)" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1246, "explanations": { "1": "We define $f[i][j]$ as the minimum number of operations required to delete all numbers in the index range $[i,..j]$. Initially, $f[i][i] = 1$, which means that when there is only one number, one deletion operation is needed.\n\nFor $f[i][j]$, if $i + 1 = j$, i.e., there are only two numbers, if $arr[i]=arr[j]$, then $f[i][j] = 1$, otherwise $f[i][j] = 2$.\n\nFor the case of more than two numbers, if $arr[i]=arr[j]$, then $f[i][j]$ can be $f[i + 1][j - 1]$, or we can enumerate $k$ in the index range $[i,..j-1]$, take the minimum value of $f[i][k] + f[k + 1][j]$. Assign the minimum value to $f[i][j]$.\n\nThe answer is $f[0][n - 1]$.\n\nThe time complexity is $O(n^3)$, and the space complexity is $O(n^2)$. Where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n^3)", "space_complexity": "O(n^2)" }, { "problem_id": 1247, "explanations": { "1": "According to the problem description, both strings $s_1$ and $s_2$ contain only the characters $x$ and $y$, and they have the same length. Therefore, we can match the characters in $s_1$ and $s_2$ one by one, i.e., $s_1[i]$ and $s_2[i]$.\n\nIf $s_1[i] = s_2[i]$, no swap is needed, and we can skip to the next character. If $s_1[i] \\neq s_2[i]$, a swap is needed. We count the combinations of $s_1[i]$ and $s_2[i]$: if $s_1[i] = x$ and $s_2[i] = y$, we denote it as $xy$; if $s_1[i] = y$ and $s_2[i] = x$, we denote it as $yx$.\n\nIf $xy + yx$ is odd, it is impossible to complete the swaps, and we return $-1$. If $xy + yx$ is even, the number of swaps needed is $\\left \\lfloor \\frac{xy}{2} \\right \\rfloor + \\left \\lfloor \\frac{yx}{2} \\right \\rfloor + xy \\bmod{2} + yx \\bmod{2}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the strings $s_1$ and $s_2$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1248, "explanations": { "1": "The problem asks for the number of subarrays that contain exactly $k$ odd numbers. We can calculate the number of odd numbers $t$ in each prefix array and record it in an array or hash table $cnt$. For each prefix array, we only need to find the number of prefix arrays with $t-k$ odd numbers, which is the number of subarrays ending with the current prefix array.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1249, "explanations": { "1": "First, we scan from left to right and remove the extra right parentheses. Then, we scan from right to left and remove the extra left parentheses.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string $s$.\n\nSimilar problems:\n\n- [678. Valid Parenthesis String](https://github.com/doocs/leetcode/blob/main/solution/0600-0699/0678.Valid%20Parenthesis%20String/README_EN.md)\n- [2116. Check if a Parentheses String Can Be Valid](https://github.com/doocs/leetcode/blob/main/solution/2100-2199/2116.Check%20if%20a%20Parentheses%20String%20Can%20Be%20Valid/README_EN.md)" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1250, "explanations": { "1": "First, consider the situation where we select two numbers. If the selected numbers are $a$ and $b$, then according to the problem's requirements, we need to satisfy $a \\times x + b \\times y = 1$, where $x$ and $y$ are any integers.\n\nAccording to Bézout's Identity, if $a$ and $b$ are coprime, then the above equation definitely has a solution. In fact, Bézout's Identity can also be extended to the case of multiple numbers. That is, if $a_1, a_2, \\cdots, a_i$ are coprime, then $a_1 \\times x_1 + a_2 \\times x_2 + \\cdots + a_i \\times x_i = 1$ definitely has a solution, where $x_1, x_2, \\cdots, x_i$ are any integers.\n\nTherefore, we only need to determine whether there exist $i$ coprime numbers in the array `nums`. The necessary and sufficient condition for two numbers to be coprime is that their greatest common divisor is $1$. If there exist $i$ coprime numbers in the array `nums`, then the greatest common divisor of all numbers in the array `nums` is also $1$.\n\nSo we transform the problem into: determining whether the greatest common divisor of all numbers in the array `nums` is $1$. We can do this by traversing the array `nums` and finding the greatest common divisor of all numbers in the array `nums`.\n\nThe time complexity is $O(n + \\log m)$, and the space complexity is $O(1)$. Where $n$ is the length of the array `nums`, and $m$ is the maximum value in the array `nums`." }, "is_english": true, "time_complexity": "O(n + \\log m)", "space_complexity": "O(1)" }, { "problem_id": 1251, "explanations": { "1": "We can use a left join to join the `Prices` table and the `UnitsSold` table on `product_id`, and the condition that `purchase_date` is between `start_date` and `end_date`. Then, we can use `GROUP BY` to group by `product_id` for aggregation, and use the `AVG` function to calculate the average price. Note that if a product has no sales records, the `AVG` function will return `NULL`, so we can use the `IFNULL` function to convert it to $0$." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1252, "explanations": { "1": "We create a matrix $g$ to store the result of operations. For each pair $(r_i, c_i)$ in $\\textit{indices}$, we add $1$ to all numbers in the $r_i$-th row of the matrix and add $1$ to all elements in the $c_i$-th column.\n\nAfter the simulation ends, we traverse the matrix and count the number of odd numbers.\n\nThe time complexity is $O(k \\times (m + n) + m \\times n)$, and the space complexity is $O(m \\times n)$. Here, $k$ is the length of $\\textit{indices}$.", "2": "We can use a row array $\\textit{row}$ and a column array $\\textit{col}$ to record the number of times each row and column is incremented. For each pair $(r_i, c_i)$ in $\\textit{indices}$, we add $1$ to $\\textit{row}[r_i]$ and $\\textit{col}[c_i]$ respectively.\n\nAfter the operations are completed, the count at position $(i, j)$ can be calculated as $\\textit{row}[i] + \\textit{col}[j]$. We traverse the matrix and count the number of odd numbers.\n\nThe time complexity is $O(k + m \\times n)$, and the space complexity is $O(m + n)$. Here, $k$ is the length of $\\textit{indices}$.", "3": "We notice that a number at position $(i, j)$ in the matrix will be odd only when exactly one of $\\textit{row}[i]$ and $\\textit{col}[j]$ is odd and the other is even.\n\nWe count the number of odd numbers in $\\textit{row}$, denoted as $\\textit{cnt1}$, and the number of odd numbers in $\\textit{col}$, denoted as $\\textit{cnt2}$. Therefore, the final count of odd numbers is $\\textit{cnt1} \\times (n - \\textit{cnt2}) + \\textit{cnt2} \\times (m - \\textit{cnt1})$.\n\nThe time complexity is $O(k + m + n)$, and the space complexity is $O(m + n)$. Here, $k$ is the length of $\\textit{indices}$." }, "is_english": true, "time_complexity": "O(k \\times (m + n) + m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 1253, "explanations": { "1": "First, we create an answer array $ans$, where $ans[0]$ and $ans[1]$ represent the first and second rows of the matrix, respectively.\n\nNext, we traverse the array $colsum$ from left to right. For the current element $colsum[j]$, we have the following cases:\n\n- If $colsum[j] = 2$, then we set both $ans[0][j]$ and $ans[1][j]$ to $1$. In this case, both $upper$ and $lower$ are reduced by $1$.\n- If $colsum[j] = 1$, then we set either $ans[0][j]$ or $ans[1][j]$ to $1$. If $upper \\gt lower$, then we prefer to set $ans[0][j]$ to $1$; otherwise, we prefer to set $ans[1][j]$ to $1$. In this case, either $upper$ or $lower$ is reduced by $1$.\n- If $colsum[j] = 0$, then we set both $ans[0][j]$ and $ans[1][j]$ to $0$.\n- If $upper \\lt 0$ or $lower \\lt 0$, then it is impossible to construct a matrix that meets the requirements, and we return an empty array.\n\nAt the end of the traversal, if both $upper$ and $lower$ are $0$, then we return $ans$; otherwise, we return an empty array.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $colsum$. Ignoring the space consumption of the answer array, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1254, "explanations": { "1": "We traverse the matrix, and for each piece of land, we perform a depth-first search to find all the land connected to it. Then we check if there is any land on the boundary. If there is, it is not a closed island; otherwise, it is a closed island, and we increment the answer by one.\n\nFinally, we return the answer.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Where $m$ and $n$ are the number of rows and columns in the matrix, respectively.", "2": "We can use a union-find set to maintain each piece of connected land.\n\nWe traverse the matrix, if the current position is on the boundary, we connect it with the virtual node $m \\times n$. If the current position is land, we connect it with the land below and to the right.\n\nThen, we traverse the matrix again, for each piece of land, if its root node is itself, we increment the answer by one.\n\nFinally, we return the answer.\n\nThe time complexity is $O(m \\times n \\times \\alpha(m \\times n))$, and the space complexity is $O(m \\times n)$. Where $m$ and $n$ are the number of rows and columns in the matrix, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 1255, "explanations": { "1": "Given the small data range in the problem, we can use binary enumeration to enumerate all word combinations for the given word list. Then, we check whether each word combination meets the requirements of the problem. If it does, we calculate its score and finally take the word combination with the highest score.\n\nFirst, we use a hash table or array $cnt$ to record the number of occurrences of each letter in the alphabet $letters$.\n\nNext, we use binary enumeration to enumerate all word combinations. Each bit in the binary represents whether each word in the word list is selected. If the $i$th bit is $1$, it means the $i$th word is selected; otherwise, the $i$th word is not selected.\n\nThen, we count the number of occurrences of each letter in the current word combination and record it in the hash table or array $cur$. If the number of occurrences of each letter in $cur$ is not greater than the corresponding letter in $cnt$, it means the current word combination meets the requirements of the problem. We calculate the score of the current word combination and take the word combination with the highest score.\n\nThe time complexity is $(2^n \\times n \\times M)$, and the space complexity is $O(C)$. Where $n$ and $M$ are the number of words in the word set and the maximum length of the word, respectively; and $C$ is the number of letters in the alphabet, in this problem, $C=26$." }, "is_english": true, "time_complexity": "O(C)", "space_complexity": "O(C)" }, { "problem_id": 1256, "explanations": { "1": "We add one to $num$, then convert it to a binary string and remove the highest bit $1$.\n\nThe time complexity is $O(\\log n)$, and the space complexity is $O(\\log n)$. Where $n$ is the size of $num$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 1257, "explanations": { "1": "We can use a hash table $\\textit{g}$ to store the parent region of each region. Then, starting from $\\textit{region1}$, we keep moving upwards to find all its parent regions until the root region, and store these regions in the set $\\textit{s}$. Next, starting from $\\textit{region2}$, we keep moving upwards to find the first region that is in the set $\\textit{s}$, which is the smallest common region.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the region list $\\textit{regions}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1258, "explanations": { "1": "We can notice that the synonyms in the problem are transitive, i.e., if `a` and `b` are synonyms, and `b` and `c` are synonyms, then `a` and `c` are also synonyms. Therefore, we can use a union-find set to find the connected components of synonyms, where all the words in each connected component are synonyms and are sorted in lexicographical order.\n\nNext, we split the string `text` into a word array `sentence` by spaces. For each word `sentence[i]`, if it is a synonym, we replace it with all the words in the connected component, otherwise, we do not replace it. In this way, we can get all the sentences. This can be implemented by DFS search.\n\nWe design a function $dfs(i)$, which represents starting from the $i$th word of `sentence`, replacing it with all the words in the connected component, and then recursively processing the following words.\n\nIf $i$ is greater than or equal to the length of `sentence`, it means that we have processed all the words, and at this time, we add the current sentence to the answer array. Otherwise, if `sentence[i]` is not a synonym, we do not replace it, directly add it to the current sentence, and then recursively process the following words. Otherwise, we replace `sentence[i]` with all the words in the connected component, and also recursively process the following words.\n\nFinally, return the answer array.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$. Where $n$ is the number of words." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 1259, "explanations": { "1": "We design a function $dfs(i)$, which represents the number of handshake schemes for $i$ people. The answer is $dfs(n)$.\n\nThe execution logic of the function $dfs(i)$ is as follows:\n\n- If $i \\lt 2$, then there is only one handshake scheme, which is not to shake hands, so return $1$.\n- Otherwise, we can enumerate who the first person shakes hands with. Let the number of remaining people on the left be $l$, and the number of people on the right be $r=i-l-2$. Then we have $dfs(i)= \\sum_{l=0}^{i-1} dfs(l) \\times dfs(r)$.\n\nTo avoid repeated calculations, we use the method of memoization search.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$. Where $n$ is the size of $numPeople$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 1260, "explanations": { "1": "According to the problem description, if we flatten the 2D array into a 1D array, then each shift operation is to move the elements in the array one position to the right, with the last element moving to the first position of the array.\n\nTherefore, we can flatten the 2D array into a 1D array, then calculate the final position $idx = (x, y)$ of each element, and update the answer array `ans[x][y] = grid[i][j]`.\n\nThe time complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns in the `grid` array, respectively. We need to traverse the `grid` array once to calculate the final position of each element. Ignoring the space consumption of the answer array, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(1)" }, { "problem_id": 1261, "explanations": { "1": "First, we traverse the binary tree using DFS, restore the node values to their original values, and store all node values in a hash table. Then, when searching, we only need to check if the target value exists in the hash table.\n\nIn terms of time complexity, it takes $O(n)$ time to traverse the binary tree during initialization, and $O(1)$ time to check if the target value exists in the hash table during search. The space complexity is $O(n)$, where $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": null, "space_complexity": "O(n)" }, { "problem_id": 1262, "explanations": { "1": "We define $f[i][j]$ as the maximum sum of several numbers selected from the first $i$ numbers, such that the sum modulo $3$ equals $j$. Initially, $f[0][0]=0$, and the rest are $-\\infty$.\n\nFor $f[i][j]$, we can consider the state of the $i$th number $x$:\n\n- If we do not select $x$, then $f[i][j]=f[i-1][j]$;\n- If we select $x$, then $f[i][j]=f[i-1][(j-x \\bmod 3 + 3)\\bmod 3]+x$.\n\nTherefore, we can get the state transition equation:\n\n$$\nf[i][j]=\\max\\{f[i-1][j],f[i-1][(j-x \\bmod 3 + 3)\\bmod 3]+x\\}\n$$\n\nThe final answer is $f[n][0]$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $nums$.\n\nNote that the value of $f[i][j]$ is only related to $f[i-1][j]$ and $f[i-1][(j-x \\bmod 3 + 3)\\bmod 3]$, so we can use a rolling array to optimize the space complexity, reducing the space complexity to $O(1)$.", "2": "" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1263, "explanations": { "1": "We consider the player's position and the box's position as a state, i.e., $(s_i, s_j, b_i, b_j)$, where $(s_i, s_j)$ is the player's position, and $(b_i, b_j)$ is the box's position. In the code implementation, we define a function $f(i, j)$, which maps the two-dimensional coordinates $(i, j)$ to a one-dimensional state number, i.e., $f(i, j) = i \\times n + j$, where $n$ is the number of columns in the grid. So the player and the box's state is $(f(s_i, s_j), f(b_i, b_j))$.\n\nFirst, we traverse the grid to find the initial positions of the player and the box, denoted as $(s_i, s_j)$ and $(b_i, b_j)$.\n\nThen, we define a double-ended queue $q$, where each element is a triplet $(f(s_i, s_j), f(b_i, b_j), d)$, indicating that the player is at $(s_i, s_j)$, the box is at $(b_i, b_j)$, and $d$ pushes have been made. Initially, we add $(f(s_i, s_j), f(b_i, b_j), 0)$ to the queue $q$.\n\nAdditionally, we use a two-dimensional array $vis$ to record whether each state has been visited. Initially, $vis[f(s_i, s_j), f(b_i, b_j)]$ is marked as visited.\n\nNext, we start the breadth-first search.\n\nIn each step of the search, we take out the queue head element $(f(s_i, s_j), f(b_i, b_j), d)$, and check whether $grid[b_i][b_j] = 'T'$ is satisfied. If it is, it means the box has been pushed to the target position, and now $d$ can be returned as the answer.\n\nOtherwise, we enumerate the player's next move direction. The player's new position is denoted as $(s_x, s_y)$. If $(s_x, s_y)$ is a valid position, we judge whether $(s_x, s_y)$ is the same as the box's position $(b_i, b_j)$:\n\n- If they are the same, it means the player has reached the box's position and pushed the box forward by one step. The box's new position is $(b_x, b_y)$. If $(b_x, b_y)$ is a valid position, and the state $(f(s_x, s_y), f(b_x, b_y))$ has not been visited, then we add $(f(s_x, s_y), f(b_x, b_y), d + 1)$ to the end of the queue $q$, and mark $vis[f(s_x, s_y), f(b_x, b_y)]$ as visited.\n- If they are different, it means the player has not pushed the box. Then we only need to judge whether the state $(f(s_x, s_y), f(b_i, b_j))$ has been visited. If it has not been visited, then we add $(f(s_x, s_y), f(b_i, b_j), d)$ to the head of the queue $q$, and mark $vis[f(s_x, s_y), f(b_i, b_j)]$ as visited.\n\nWe continue the breadth-first search until the queue is empty.\n\n> Note, if the box is pushed, the push count $d$ needs to be incremented by $1$, and the new state is added to the end of the queue $q$. If the box is not pushed, the push count $d$ remains unchanged, and the new state is added to the head of the queue $q$.\n\nFinally, if no valid push scheme is found, then return $-1$.\n\nThe time complexity is $O(m^2 \\times n^2)$, and the space complexity is $O(m^2 \\times n^2)$. Where $m$ and $n$ are the number of rows and columns in the grid, respectively." }, "is_english": true, "time_complexity": "O(m^2 \\times n^2)", "space_complexity": "O(m^2 \\times n^2)" }, { "problem_id": 1264, "explanations": { "1": "First, we query all users who are friends with `user_id = 1` and record them in the `T` table. Then, we query all pages that users in the `T` table like, and finally exclude the pages that `user_id = 1` likes.", "2": "" }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1265, "explanations": { "1": "We can use recursion to implement reverse printing of a linked list. In the function, we check whether the current node is null. If it is not null, we get the next node, then recursively call the function itself, and finally print the value of the current node.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the linked list." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1266, "explanations": { "1": "For two points $p_1=(x_1, y_1)$ and $p_2=(x_2, y_2)$, the distances moved in the horizontal and vertical directions are $d_x = |x_1 - x_2|$ and $d_y = |y_1 - y_2|$ respectively.\n\nIf $d_x \\ge d_y$, we move diagonally for $d_y$ steps, then move horizontally for $d_x - d_y$ steps; if $d_x < d_y$, we move diagonally for $d_x$ steps, then move vertically for $d_y - d_x$ steps. Therefore, the shortest distance between two points is $\\max(d_x, d_y)$.\n\nWe can iterate through all pairs of points, calculate the shortest distance between each pair, and sum them up.\n\nThe time complexity is $O(n)$, where $n$ is the number of points. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1267, "explanations": { "1": "We can count the number of servers in each row and each column, then traverse each server. If the number of servers in the current server's row or column exceeds $1$, it means the current server meets the condition, and we increment the result by $1$.\n\nAfter the traversal, we return the result.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m + n)$. Where $m$ and $n$ are the number of rows and columns in the matrix, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m + n)" }, { "problem_id": 1268, "explanations": { "1": "The problem requires that after each letter of the input `searchWord`, recommend up to three products from the `products` array that have the same prefix as `searchWord`. If there are more than three products with the same prefix that can be recommended, return the three with the smallest lexicographic order.\n\nTo find products with the same prefix, we can use a trie; to return the three products with the smallest lexicographic order, we can first sort the `products` array, and then store the indices of the sorted array in the trie.\n\nEach node of the trie maintains the following information:\n\n- `children`: This is an array of length $26$, used to store the child nodes of the current node. `children[i]` represents the node whose character is `i + 'a'` among the child nodes of the current node.\n- `v`: This is an array, used to store the indices of the characters in the `products` array among the child nodes of the current node, storing up to three indices.\n\nDuring the search, we start from the root node of the trie, find the index array corresponding to each prefix, and store it in the result array. Finally, we only need to map each index in the index array to the `products` array.\n\nThe time complexity is $O(L \\times \\log n + m)$, and the space complexity is $O(L)$. Where $L$ is the sum of the lengths of all strings in the `products` array, and $n$ and $m$ are the lengths of the `products` array and `searchWord`, respectively." }, "is_english": true, "time_complexity": "O(L \\times \\log n + m)", "space_complexity": "O(L)" }, { "problem_id": 1269, "explanations": { "1": "We observe the data range of the problem and find that $steps$ does not exceed $500$, which means that we can only go to the right for up to $500$ steps.\n\nWe can design a function $dfs(i, j)$, which represents the number of schemes when we are currently at position $i$ and the remaining steps are $j$. So the answer is $dfs(0, steps)$.\n\nThe execution process of the function $dfs(i, j)$ is as follows:\n\n1. If $i \\gt j$ or $i \\geq arrLen$ or $i \\lt 0$ or $j \\lt 0$, then return $0$.\n1. If $i = 0$ and $j = 0$, then the pointer has stopped in place and there are no remaining steps, so return $1$.\n1. Otherwise, we can choose to move one step to the left, one step to the right, or stay still, so return $dfs(i - 1, j - 1) + dfs(i + 1, j - 1) + dfs(i, j - 1)$. Note the modulo operation of the answer.\n\nDuring the process, we can use memoization search to avoid repeated calculations.\n\nThe time complexity is $O(steps \\times steps)$, and the space complexity is $O(steps \\times steps)$. Where $steps$ is the number of steps given in the problem." }, "is_english": true, "time_complexity": "O(steps \\times steps)", "space_complexity": "O(steps \\times steps)" }, { "problem_id": 1270, "explanations": { "1": "We can use two joins to find all employees who report directly or indirectly to the company CEO.\n\nSpecifically, we first use a join to find the `manager_id` of the superior manager for each `manager_id`, and then use another join to find the `manager_id` of the higher-level manager. Finally, if the `manager_id` of the higher-level manager is $1$ and the `employee_id` of the employee is not $1$, it means that the employee reports directly or indirectly to the company CEO." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1271, "explanations": { "1": "Convert the number to a hexadecimal string, then traverse the string, convert the number $0$ to the letter $O$, and the number $1$ to the letter $I$. Finally, check whether the converted string is valid.\n\nThe time complexity is $O(\\log n)$, where $n$ is the size of the decimal number represented by $num$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": null }, { "problem_id": 1272, "explanations": { "1": "We denote the interval to be removed as $[x, y)$. We traverse the interval list, and for each interval $[a, b)$, there are three cases:\n\n- $a \\geq y$ or $b \\leq x$, which means that this interval does not intersect with the interval to be removed. We directly add this interval to the answer.\n- $a \\lt x$, $b \\gt y$, which means that this interval intersects with the interval to be removed. We split this interval into two intervals and add them to the answer.\n- $a \\geq x$, $b \\leq y$, which means that this interval is completely covered by the interval to be removed. We do not add it to the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the interval list. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1273, "explanations": { "1": "First, we convert the tree into a graph $g$, where $g[i]$ represents all the child nodes of node $i$.\n\nThen we design a function $dfs(i)$, which represents the number of nodes and the sum of the weights in the subtree rooted at node $i$. The answer is $dfs(0)[1]$.\n\nIn this function, we recursively calculate the number of nodes and the sum of the weights in the subtree rooted at each child node $j$, and then accumulate these values. If the accumulated value is zero, we set the number of nodes in this subtree to zero. Finally, we return the number of nodes and the sum of the weights in the subtree rooted at node $i$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in the tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1274, "explanations": { "1": "Since there are at most $10$ ships in the rectangle, we can divide the rectangle into four sub-rectangles, calculate the number of ships in each sub-rectangle, and then add the number of ships in the four sub-rectangles. If there are no ships in a sub-rectangle, then there is no need to continue dividing.\n\nThe time complexity is $O(C \\times \\log \\max(m, n))$, and the space complexity is $O(\\log \\max(m, n))$. Where $C$ is the number of ships, and $m$ and $n$ are the length and width of the rectangle, respectively." }, "is_english": true, "time_complexity": "O(C \\times \\log \\max(m, n))", "space_complexity": "O(\\log \\max(m, n))" }, { "problem_id": 1275, "explanations": { "1": "Since all `moves` are valid, that is, there is no situation where a person continues to play after someone has won. Therefore, we only need to determine whether the last player to move can win.\n\nWe use an array `cnt` of length $8$ to record the number of moves in rows, columns, and diagonals. Where $cnt[0, 1, 2]$ represent the number of moves in the $0, 1, 2$ rows respectively, and $cnt[3, 4, 5]$ represent the number of moves in the $0, 1, 2$ columns respectively. Additionally, $cnt[6]$ and $cnt[7]$ represent the number of moves on the two diagonals respectively. During the game, if a player makes $3$ moves in a row, column, or diagonal, that player wins.\n\nIf the last player to move does not win, then we determine whether the board is full. If it is full, it is a draw; otherwise, the game is not over yet.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of `moves`." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1276, "explanations": { "1": "We set the number of Jumbo Burgers as $x$ and the number of Small Burgers as $y$, then we have:\n\n$$\n\\begin{aligned}\n4x + 2y &= tomatoSlices \\\\\nx + y &= cheeseSlices\n\\end{aligned}\n$$\n\nTransforming the above two equations, we can get:\n\n$$\n\\begin{aligned}\ny = (4 \\times cheeseSlices - tomatoSlices) / 2 \\\\\nx = cheeseSlices - y\n\\end{aligned}\n$$\n\nWhere $x$ and $y$ must be non-negative integers.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 1277, "explanations": { "1": "We define $f[i][j]$ as the side length of the square submatrix with $(i,j)$ as the bottom-right corner. Initially $f[i][j] = 0$, and the answer is $\\sum_{i,j} f[i][j]$.\n\nConsider how to perform state transition for $f[i][j]$.\n\n- When $\\text{matrix}[i][j] = 0$, we have $f[i][j] = 0$.\n- When $\\text{matrix}[i][j] = 1$, the value of state $f[i][j]$ depends on the values of the three positions above, left, and top-left:\n - If $i = 0$ or $j = 0$, then $f[i][j] = 1$.\n - Otherwise $f[i][j] = \\min(f[i-1][j-1], f[i-1][j], f[i][j-1]) + 1$.\n\nThe answer is $\\sum_{i,j} f[i][j]$.\n\nTime complexity $O(m \\times n)$, space complexity $O(m \\times n)$. Where $m$ and $n$ are the number of rows and columns of the matrix respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 1278, "explanations": { "1": "We define $f[i][j]$ to represent the minimum number of changes needed to partition the first $i$ characters of the string $s$ into $j$ palindromic substrings. We assume the index $i$ starts from 1, and the answer is $f[n][k]$.\n\nFor $f[i][j]$, we can enumerate the position $h$ of the last character of the $(j-1)$-th palindromic substring. Then $f[i][j]$ is equal to the minimum value of $f[h][j-1] + g[h][i-1]$, where $g[h][i-1]$ represents the minimum number of changes needed to turn the substring $s[h..i-1]$ into a palindrome (this part can be preprocessed with a time complexity of $O(n^2)$).\n\nThe time complexity is $O(n^2 \\times k)$, and the space complexity is $O(n \\times (n + k))$. Where $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n \\times (n + k))" }, { "problem_id": 1279, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1280, "explanations": { "1": "We can first join the `Students` table and the `Subjects` table to obtain all combinations of students and subjects, and then join the `Examinations` table with the condition of `student_id` and `subject_name`. This way, we can get the number of times each student has taken each subject's test. Finally, we can group by `student_id` and `subject_name` to count the number of times each student has taken each subject's test." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1281, "explanations": { "1": "We use two variables $x$ and $y$ to record the product of the digits and the sum of the digits respectively. At the beginning, $x=1,y=0$.\n\nWhen $n \\gt 0$, each time we take the $mod$ of $n$ by $10$ to get the current digit $v$, and continue the next loop by dividing $n$ by $10$. In each loop, we update $x = x \\times v$, $y = y + v$.\n\nFinally, we return $x - y$.\n\nThe time complexity is $O(\\log n)$, where $n$ is the given integer. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 1282, "explanations": { "1": "We use a hash table $g$ to store which people are in each group size $groupSize$. Then we partition each group size into $k$ equal parts, with each part containing $groupSize$ people.\n\nSince the range of $n$ in the problem is small, we can also directly create an array of size $n+1$ to store the data, which is more efficient.\n\nTime complexity is $O(n)$, and space complexity is $O(n)$. Here, $n$ is the length of $groupSizes$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1283, "explanations": { "1": "Notice that for number $v$, if the sum of results of dividing each number in $nums$ by $v$ is less than or equal to $threshold$, then all values greater than $v$ satisfy the condition. There is a monotonicity, so we can use binary search to find the smallest $v$ that satisfies the condition.\n\nWe define the left boundary of the binary search $l=1$, $r=\\max(nums)$. Each time we take $mid=(l+r)/2$, calculate the sum of the results of dividing each number in $nums$ by $mid$ $s$, if $s$ is less than or equal to $threshold$, then it means that $mid$ satisfies the condition, we will update $r$ to $mid$, otherwise we will update $l$ to $mid+1$.\n\nFinally, return $l$.\n\nThe time complexity is $O(n \\times \\log M)$, where $n$ is the length of the array $nums$ and $M$ is the maximum value in the array $nums$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(1)" }, { "problem_id": 1284, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1285, "explanations": { "1": "We need to find a way to group a continuous sequence of logs into the same group, and then aggregate each group to obtain the start and end logs of each group.\n\nThere are two ways to implement grouping:\n\n1. By calculating the difference between each log and the previous log, if the difference is $1$, then the two logs are continuous, and we set $delta$ to $0$, otherwise we set it to $1$. Then we take the prefix sum of $delta$ to obtain the grouping identifier for each row.\n2. By calculating the difference between the current log and its row number, we obtain the grouping identifier for each row.", "2": "" }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1286, "explanations": { "1": "我们通过 $DFS$ 枚举,预处理生成所有长度为 $combinationLength$ 的字符串,存放到 $cs$ 数组中。", "2": "我们看个例子,对于 $abcd$,若 $combinationLength$ 为 2,则 $cs$ 就是 $ab, ac, ad, bc, bd, cd, ...$。\n\n对应的二进制数为:\n\n```\n1100\n1010\n1001\n0110\n0101\n0011\n...\n```\n\n观察到上述规律后,我们依次按照二进制编码从大到小的规律,将所有字符串依次求出。\n\n所谓的长度 $combinationLength$,只需要满足二进制编码中 $1$ 的个数满足要求即可。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1287, "explanations": { "1": "We traverse the array $\\textit{arr}$ from the beginning. For each element $\\textit{arr}[i]$, we check if $\\textit{arr}[i]$ is equal to $\\textit{arr}[i + \\left\\lfloor \\frac{n}{4} \\right\\rfloor]$, where $n$ is the length of the array. If they are equal, then $\\textit{arr}[i]$ is the element we are looking for, and we return it directly.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{arr}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1288, "explanations": { "1": "We can sort the intervals in ascending order by their left endpoints, and if the left endpoints are the same, sort them in descending order by their right endpoints.\n\nAfter sorting, we can traverse the intervals. If the right endpoint of the current interval is greater than the previous right endpoint, it means the current interval is not covered, and we increment the answer by one.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the number of intervals." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 1289, "explanations": { "1": "We define $f[i][j]$ to represent the minimum sum of the first $i$ rows, with the last number in the $j$-th column. The state transition equation is:\n\n$$\nf[i][j] = \\min_{k \\neq j} f[i - 1][k] + grid[i - 1][j]\n$$\n\nwhere $k$ represents the column of the number in the $(i - 1)$-th row, and the number in the $i$-th row and $j$-th column is $grid[i - 1][j]$.\n\nThe final answer is the minimum value in $f[n]$.\n\nThe time complexity is $O(n^3)$, and the space complexity is $O(n^2)$. Here, $n$ is the number of rows in the matrix.\n\nWe note that the state $f[i][j]$ only depends on $f[i - 1][k]$, so we can use a rolling array to optimize the space complexity to $O(n)$." }, "is_english": true, "time_complexity": "O(n^3)", "space_complexity": "O(n^2)" }, { "problem_id": 1290, "explanations": { "1": "We use a variable $\\textit{ans}$ to record the current decimal value, with an initial value of $0$.\n\nTraverse the linked list. For each node, left-shift $\\textit{ans}$ by one bit, then perform a bitwise OR with the current node's value. After traversal, $\\textit{ans}$ is the decimal value.\n\nThe time complexity is $O(n)$, where $n$ is the length of the linked list. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1291, "explanations": { "1": "我们可以枚举数字的第一位 $i$,然后枚举数字的最后一位 $j$,那么这个数字就是 $i,i+1,\\cdots,j$ 这 $j-i+1$ 个数字组成的。我们可以通过不断地将数字乘以 $10$ 并加上下一个数字 $j+1$ 来得到下一个数字,如果数字在 $[low, high]$ 的范围内,我们就将它加入答案中。\n\n枚举结束后,我们将答案数组排序并返回即可。\n\n时间复杂度近似 $O(1)$,空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 1292, "explanations": { "1": "We can precompute a 2D prefix sum array $s$, where $s[i + 1][j + 1]$ represents the sum of elements in the matrix $mat$ from $(0, 0)$ to $(i, j)$. With this, we can calculate the sum of elements in any square region in $O(1)$ time.\n\nNext, we can use binary search to find the maximum side length. We enumerate the side length $k$ of the square, and then iterate through all possible top-left positions $(i, j)$ of the square. We can calculate the sum of elements $v$ for the square. If $v \\leq threshold$, it indicates that there exists a square region with side length $k$ whose sum is less than or equal to the threshold; otherwise, no such square exists for the current $k$.\n\nThe time complexity is $O(m \\times n \\times \\log \\min(m, n))$, and the space complexity is $O(m \\times n)$." }, "is_english": true, "time_complexity": "O(m \\times n \\times \\log \\min(m, n))", "space_complexity": "O(m \\times n)" }, { "problem_id": 1293, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1294, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1295, "explanations": { "1": "We traverse each element $x$ in the array $\\textit{nums}$. For the current element $x$, we directly convert it to a string and then check if its length is even. If it is, we increment the answer by one.\n\nAfter the traversal is complete, we return the answer.\n\nThe time complexity is $O(n \\times \\log M)$, and the space complexity is $O(\\log M)$. Here, $n$ is the length of the array $\\textit{nums}$, and $M$ is the maximum value of the elements in the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(\\log M)" }, { "problem_id": 1296, "explanations": { "1": "First, we check if the length of the array $\\textit{nums}$ is divisible by $\\textit{k}$. If it is not divisible, it means the array cannot be divided into subarrays of length $\\textit{k}$, and we return $\\text{false}$ directly.\n\nNext, we use a hash table $\\textit{cnt}$ to count the occurrences of each number in the array $\\textit{nums}$, and then we sort the array $\\textit{nums}$.\n\nAfter sorting, we iterate through the array $\\textit{nums}$, and for each number $x$, if $\\textit{cnt}[x]$ is not $0$, we enumerate each number $y$ from $x$ to $x + \\textit{k} - 1$. If $\\textit{cnt}[y]$ is $0$, it means we cannot divide the array into subarrays of length $\\textit{k}$, and we return $\\text{false}$ directly. Otherwise, we decrement $\\textit{cnt}[y]$ by $1$.\n\nAfter the loop, if no issues were encountered, it means we can divide the array into subarrays of length $\\textit{k}$, and we return $\\text{true}$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$.", "2": "Similar to Solution 1, we first check if the length of the array $\\textit{nums}$ is divisible by $\\textit{k}$. If it is not divisible, it means the array cannot be divided into subarrays of length $\\textit{k}$, and we return $\\text{false}$ directly.\n\nNext, we use an ordered set $\\textit{sd}$ to count the occurrences of each number in the array $\\textit{nums}$.\n\nThen, we repeatedly extract the smallest value $x$ from the ordered set and enumerate each number $y$ from $x$ to $x + \\textit{k} - 1$. If these numbers all appear in the ordered set with non-zero occurrences, we decrement their occurrence count by $1$. If the occurrence count becomes $0$ after the decrement, we remove the number from the ordered set; otherwise, it means we cannot divide the array into subarrays of length $\\textit{k}$, and we return $\\text{false}$.\n\nIf we can successfully divide the array into subarrays of length $\\textit{k}$, we return $\\text{true}$ after completing the traversal.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1297, "explanations": { "1": "According to the problem description, if a long string meets the condition, then its substring of length $\\textit{minSize}$ must also meet the condition. Therefore, we only need to enumerate all substrings of length $\\textit{minSize}$ in $s$, then use a hash table to record the occurrence frequency of all substrings, and find the maximum frequency as the answer.\n\nThe time complexity is $O(n \\times m)$, and the space complexity is $O(n \\times m)$. Here, $n$ and $m$ are the lengths of the string $s$ and $\\textit{minSize}$, respectively. In this problem, $m$ does not exceed $26$.", "2": "We can use a sliding window to maintain the number of distinct letters in the current substring, while using string hashing to efficiently calculate the hash value of substrings, thereby avoiding using strings as hash table keys and improving performance.\n\nSpecifically, we define a $\\textit{Hashing}$ class to preprocess the prefix hash values and power values of the string $s$, so that we can calculate the hash value of any substring in $O(1)$ time.\n\nThen, we use a sliding window to traverse the string $s$, maintaining the number of distinct letters in the current window. When the window size reaches $\\textit{minSize}$, we calculate the hash value of the current substring and update its occurrence count. Next, we slide the window one position to the right and update the letter frequencies and the count of distinct letters.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n \\times m)", "space_complexity": "O(n \\times m)" }, { "problem_id": 1298, "explanations": { "1": "The problem gives a set of boxes, each of which may have a state (open/closed), candies, keys, and other boxes inside. Our goal is to use the initially given boxes to open as many more boxes as possible and collect the candies inside. We can unlock new boxes by obtaining keys, and get more resources through boxes nested inside other boxes.\n\nWe use BFS to simulate the entire exploration process.\n\nWe use a queue $q$ to represent the currently accessible and **already opened** boxes; two sets, $\\textit{has}$ and $\\textit{took}$, are used to record **all boxes we own** and **boxes we have already processed**, to avoid duplicates.\n\nInitially, add all $\\textit{initialBoxes}$ to $\\textit{has}$. If an initial box is open, immediately add it to the queue $\\textit{q}$ and accumulate its candies.\n\nThen perform BFS, taking boxes out of $\\textit{q}$ one by one:\n\n- Obtain the keys in the box $\\textit{keys[box]}$ and add any boxes that can be unlocked to the queue;\n- Collect other boxes contained in the box $\\textit{containedBoxes[box]}$. If a contained box is open and has not been processed, process it immediately;\n\nEach box is processed at most once, and candies are accumulated once. Finally, return the total number of candies $\\textit{ans}$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the total number of boxes." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1299, "explanations": { "1": "We use a variable $mx$ to record the maximum value to the right of the current position, initially $mx = -1$.\n\nThen we traverse the array from right to left. For each position $i$, we denote the current value as $x$, update the current position's value to $mx$, and then update $mx = \\max(mx, x)$.\n\nFinally, return the original array.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1300, "explanations": { "1": "We notice that the problem requires changing all values greater than `value` to `value` and then summing them up. Therefore, we can consider sorting the array `arr` first, and then calculating the prefix sum array $s$, where $s[i]$ represents the sum of the first $i$ elements of the array.\n\nNext, we can enumerate all `value` values from smallest to largest. For each `value`, we can use binary search to find the index $i$ of the first element in the array that is greater than `value`. At this point, the number of elements in the array greater than `value` is $n - i$, so the number of elements in the array less than or equal to `value` is $i$. The sum of the elements in the array less than or equal to `value` is $s[i]$, and the sum of the elements in the array greater than `value` is $(n - i) \\times value$. Therefore, the sum of all elements in the array is $s[i] + (n - i) \\times \\textit{value}$. If the absolute difference between $s[i] + (n - i) \\times \\textit{value}$ and `target` is less than the current minimum difference `diff`, update `diff` and `ans`.\n\nAfter enumerating all `value` values, we can get the final answer `ans`.\n\nTime complexity $O(n \\times \\log n)$, space complexity $O(n)$. Where $n$ is the length of the array `arr`." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1301, "explanations": { "1": "We define $f[i][j]$ to represent the maximum score from the starting point $(n - 1, n - 1)$ to $(i, j)$, and $g[i][j]$ to represent the number of ways to achieve the maximum score from the starting point $(n - 1, n - 1)$ to $(i, j)$. Initially, $f[n - 1][n - 1] = 0$ and $g[n - 1][n - 1] = 1$. The other positions of $f[i][j]$ are all $-1$, and $g[i][j]$ are all $0$.\n\nFor the current position $(i, j)$, it can be transferred from three positions: $(i + 1, j)$, $(i, j + 1)$, and $(i + 1, j + 1)$. Therefore, we can enumerate these three positions to update the values of $f[i][j]$ and $g[i][j]$. If the current position $(i, j)$ has an obstacle, or the current position is the starting point, or other positions are out of bounds, no update is performed. Otherwise, if another position $(x, y)$ satisfies $f[x][y] \\gt f[i][j]$, then we update $f[i][j] = f[x][y]$ and $g[i][j] = g[x][y]$. If $f[x][y] = f[i][j]$, then we update $g[i][j] = g[i][j] + g[x][y]$. Finally, if the current position $(i, j)$ is reachable and is a number, we update $f[i][j] = f[i][j] + board[i][j]$.\n\nFinally, if $f[0][0] \\lt 0$, it means there is no path to reach the endpoint, return $[0, 0]$. Otherwise, return $[f[0][0], g[0][0]]$. Note that the result needs to be taken modulo $10^9 + 7$.\n\nTime complexity $O(n^2)$, space complexity $O(n^2)$. Where $n$ is the side length of the array." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 1302, "explanations": { "1": "We can use breadth-first search (BFS) to traverse the binary tree level by level, and calculate the sum of the node values at each level. After completing the traversal, return the sum of the node values at the last level.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the tree.", "2": "We can use depth-first search (DFS) to recursively traverse the binary tree while keeping track of the current node's depth, the maximum depth, and the sum of the deepest leaf nodes. When visiting the current node, if the current node's depth equals the maximum depth, add the current node's value to the sum of the deepest leaf nodes. If the current node's depth is greater than the maximum depth, update the maximum depth to the current node's depth and update the sum of the deepest leaf nodes to the current node's value.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1303, "explanations": { "1": "We can first count the number of people in each team and record it in the `T` table. Then, we can use an equi-join to join the `Employee` table and the `T` table based on `team_id`, and obtain the total number of people in each team.", "2": "We can also use a left join to join the `Employee` table with itself based on `team_id`, and then group by `employee_id` to count the total number of people in each team that the employee belongs to." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1304, "explanations": { "1": "We can start from $1$ and alternately add positive and negative numbers to the result array. We repeat this process $\\frac{n}{2}$ times. If $n$ is odd, we add $0$ to the result array at the end.\n\nThe time complexity is $O(n)$, where $n$ is the given integer. Ignoring the space used for the answer, the space complexity is $O(1)$.", "2": "We can also add all integers from $1$ to $n-1$ to the result array, and finally add the opposite of the sum of the first $n-1$ integers, which is $-\\frac{n(n-1)}{2}$, to the result array.\n\nThe time complexity is $O(n)$, where $n$ is the given integer. Ignoring the space used for the answer, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1305, "explanations": { "1": "Since both trees are binary search trees, we can obtain the node value sequences $\\textit{a}$ and $\\textit{b}$ of the two trees through in-order traversal. Then, we use two pointers to merge the two sorted arrays to get the final answer.\n\nThe time complexity is $O(n+m)$, and the space complexity is $O(n+m)$. Here, $n$ and $m$ are the number of nodes in the two trees, respectively." }, "is_english": true, "time_complexity": "O(n+m)", "space_complexity": "O(n+m)" }, { "problem_id": 1306, "explanations": { "1": "We can use BFS to determine whether we can reach the index with a value of $0$.\n\nDefine a queue $q$ to store the currently reachable indices. Initially, enqueue the $start$ index.\n\nWhen the queue is not empty, take out the front index $i$ of the queue. If $arr[i] = 0$, return `true`. Otherwise, mark the index $i$ as visited. If $i + arr[i]$ and $i - arr[i]$ are within the array range and have not been visited, enqueue them and continue searching.\n\nFinally, if the queue is empty, it means that we cannot reach the index with a value of $0$, so return `false`.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1307, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1308, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1309, "explanations": { "1": "We can directly simulate the process.\n\nTraverse the string $s$. For the current index $i$, if $i + 2 < n$ and $s[i + 2]$ is `#`, then convert the substring formed by $s[i]$ and $s[i + 1]$ to an integer, add the ASCII value of `a` minus 1, convert it to a character, add it to the result array, and increment $i$ by 3. Otherwise, convert $s[i]$ to an integer, add the ASCII value of `a` minus 1, convert it to a character, add it to the result array, and increment $i$ by 1.\n\nFinally, convert the result array to a string and return it.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1310, "explanations": { "1": "We can use a prefix XOR array $s$ of length $n+1$ to store the prefix XOR results of the array $\\textit{arr}$, where $s[i] = s[i-1] \\oplus \\textit{arr}[i-1]$. That is, $s[i]$ represents the XOR result of the first $i$ elements of $\\textit{arr}$.\n\nFor a query $[l, r]$, we can obtain:\n\n$$\n\\begin{aligned}\n\\textit{arr}[l] \\oplus \\textit{arr}[l+1] \\oplus \\cdots \\oplus \\textit{arr}[r] &= (\\textit{arr}[0] \\oplus \\textit{arr}[1] \\oplus \\cdots \\oplus \\textit{arr}[l-1]) \\oplus (\\textit{arr}[0] \\oplus \\textit{arr}[1] \\oplus \\cdots \\oplus \\textit{arr}[r]) \\\\\n&= s[l] \\oplus s[r+1]\n\\end{aligned}\n$$\n\nTime complexity is $O(n+m)$, and space complexity is $O(n)$. Here, $n$ and $m$ are the lengths of the array $\\textit{arr}$ and the query array $\\textit{queries}$, respectively." }, "is_english": true, "time_complexity": "O(n+m)", "space_complexity": "O(n)" }, { "problem_id": 1311, "explanations": { "1": "We can use the Breadth-First Search (BFS) method to start from $\\textit{id}$ and find all friends at a distance of $\\textit{level}$, then count the videos watched by these friends.\n\nSpecifically, we can use a queue $\\textit{q}$ to store the friends at the current level. Initially, add $\\textit{id}$ to the queue $\\textit{q}$. Use a hash table or a boolean array $\\textit{vis}$ to record the friends that have already been visited. Then, perform $\\textit{level}$ iterations, in each iteration dequeue all friends from the queue and enqueue their friends until all friends at distance $\\textit{level}$ are found.\n\nNext, we use a hash table $\\textit{cnt}$ to count the videos watched by these friends and their frequencies. Finally, sort the key-value pairs in the hash table in ascending order by frequency, and if frequencies are the same, sort by video name in ascending order. Return the sorted list of video names.\n\nTime complexity is $O(n + m + v \\times \\log v)$, and space complexity is $O(n + v)$. Here, $n$ and $m$ are the lengths of the arrays $\\textit{watchedVideos}$ and $\\textit{friends}$, respectively, and $v$ is the total number of videos watched by all friends." }, "is_english": true, "time_complexity": "O(n + m + v \\times \\log v)", "space_complexity": "O(n + v)" }, { "problem_id": 1312, "explanations": { "1": "我们设计一个函数 $dfs(i, j)$,表示将字符串 $s[i..j]$ 变成回文串所需要的最少操作次数。那么答案就是 $dfs(0, n - 1)$。\n\n函数 $dfs(i, j)$ 的计算过程如下:\n\n如果 $i \\geq j$,此时无需插入任何字符,我们直接返回 $0$。\n\n否则,我们判断 $s[i]$ 与 $s[j]$ 是否相等,如果 $s[i]=s[j]$,那么我们只需要将 $s[i+1..j-1]$ 变成回文串,那么我们返回 $dfs(i + 1, j - 1)$。否则,我们可以在 $s[i]$ 的左侧或者 $s[j]$ 的右侧插入一个与另一侧相同的字符,那么 $dfs(i, j) = \\min(dfs(i + 1, j), dfs(i, j - 1)) + 1$。\n\n为了避免重复计算,我们可以使用记忆化搜索,即使用哈希表或者数组来存储已经计算过的函数值。\n\n最后,我们返回 $dfs(0, n - 1)$ 即可。\n\n时间复杂度 $O(n^2)$,空间复杂度 $O(n^2)$。其中 $n$ 为字符串 $s$ 的长度。", "2": "我们定义 $f[i][j]$ 表示将字符串 $s[i..j]$ 变成回文串所需要的最少操作次数。初始时 $f[i][j]=0$,答案即为 $f[0][n-1]$。\n\n对于 $f[i][j]$,如果 $s[i]=s[j]$,那么我们只需要将 $s[i+1..j-1]$ 变成回文串,因此 $f[i][j]=f[i+1][j-1]$。否则,我们可以在 $s[i]$ 的左侧或者 $s[j]$ 的右侧插入一个与另一侧相同的字符,那么 $f[i][j]=\\min(f[i+1][j],f[i][j-1])+1$。\n\n综上,我们可以得到状态转移方程:\n\n$$\nf[i][j]=\\left\\{\\begin{array}{ll}f[i+1][j-1], & s[i]=s[j]\\\\ \\min(f[i+1][j],f[i][j-1])+1, & s[i]\\neq s[j]\\end{array}\\right.\n$$\n\n在枚举时,我们可以有两种枚举的方式:\n\n1. 从大到小枚举 $i$,从小到大枚举 $j$,这样可以保证在计算状态 $f[i][j]$ 时,状态 $f[i+1][j-1]$ 和 $f[i][j-1]$ 都已经计算过了;\n1. 从小到大枚举区间长度 $k$,然后枚举区间的左端点 $i$,那么可以得到右端点 $j=i+k-1$,这样也可以保证在计算较大区间 $f[i][j]$ 时,较小区间 $f[i+1][j]$ 和 $f[i][j-1]$ 都已经计算过了。\n\n时间复杂度 $O(n^2)$,空间复杂度 $O(n^2)$。其中 $n$ 为字符串 $s$ 的长度。\n\n相似题目:\n\n- [1039. 多边形三角剖分的最低得分](https://github.com/doocs/leetcode/blob/main/solution/1000-1099/1039.Minimum%20Score%20Triangulation%20of%20Polygon/README.md)", "3": "" }, "is_english": false, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 1313, "explanations": { "1": "We can directly simulate the process described in the problem. Traverse the array $\\textit{nums}$ from left to right, each time taking out two numbers $\\textit{freq}$ and $\\textit{val}$, then repeat $\\textit{val}$ $\\textit{freq}$ times, and add these $\\textit{freq}$ $\\textit{val}$s to the answer array.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. We only need to traverse the array $\\textit{nums}$ once. Ignoring the space consumption of the answer array, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1314, "explanations": { "1": "This problem is a template for two-dimensional prefix sum.\n\nWe define $s[i][j]$ as the sum of the elements in the first $i$ rows and the first $j$ columns of the matrix $mat$. The calculation formula for $s[i][j]$ is:\n\n$$\ns[i][j] = s[i-1][j] + s[i][j-1] - s[i-1][j-1] + mat[i-1][j-1]\n$$\n\nIn this way, we can quickly calculate the sum of elements in any rectangular area through the $s$ array.\n\nFor a rectangular area with the upper left coordinate $(x_1, y_1)$ and the lower right coordinate $(x_2, y_2)$, we can calculate the sum of its elements through the $s$ array:\n\n$$\ns[x_2+1][y_2+1] - s[x_1][y_2+1] - s[x_2+1][y_1] + s[x_1][y_1]\n$$\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Where $m$ and $n$ are the number of rows and columns in the matrix, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 1315, "explanations": { "1": "We design a function $dfs(root, x)$, which represents the sum of the values of the nodes that meet the conditions in the subtree with $root$ as the root node and $x$ as the value of the parent node of $root$. The answer is $dfs(root, 1)$.\n\nThe execution process of the function $dfs(root, x)$ is as follows:\n\n- If $root$ is null, return $0$.\n- Otherwise, we recursively calculate the answers of the left and right subtrees of $root$, that is, $dfs(root.left, root.val)$ and $dfs(root.right, root.val)$, and add them to the answer. If $x$ is even, we check whether the left and right children of $root$ exist. If they exist, we add their values to the answer.\n- Finally, return the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1316, "explanations": { "1": "**字符串哈希**是把一个任意长度的字符串映射成一个非负整数,并且其冲突的概率几乎为 0。字符串哈希用于计算字符串哈希值,快速判断两个字符串是否相等。\n\n取一固定值 BASE,把字符串看作是 BASE 进制数,并分配一个大于 0 的数值,代表每种字符。一般来说,我们分配的数值都远小于 BASE。例如,对于小写字母构成的字符串,可以令 a=1, b=2, ..., z=26。取一固定值 MOD,求出该 BASE 进制对 M 的余数,作为该字符串的 hash 值。\n\n一般来说,取 BASE=131 或者 BASE=13331,此时 hash 值产生的冲突概率极低。只要两个字符串 hash 值相同,我们就认为两个字符串是相等的。通常 MOD 取 2^64,C++ 里,可以直接使用 unsigned long long 类型存储这个 hash 值,在计算时不处理算术溢出问题,产生溢出时相当于自动对 2^64 取模,这样可以避免低效取模运算。\n\n除了在极特殊构造的数据上,上述 hash 算法很难产生冲突,一般情况下上述 hash 算法完全可以出现在题目的标准答案中。我们还可以多取一些恰当的 BASE 和 MOD 的值(例如大质数),多进行几组 hash 运算,当结果都相同时才认为原字符串相等,就更加难以构造出使这个 hash 产生错误的数据。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1317, "explanations": { "1": "Starting from $1$, we enumerate $a$, then $b = n - a$. For each $a$ and $b$, we convert them to strings and concatenate them, then check if they contain the character '0'. If they do not contain '0', we have found the answer and return $[a, b]$.\n\nThe time complexity is $O(n \\times \\log n)$, where $n$ is the integer given in the problem. The space complexity is $O(\\log n)$.", "2": "In Solution 1, we converted $a$ and $b$ into strings and concatenated them, then checked if they contained the character '0'. Here, we can use a function $f(x)$ to check whether $x$ contains the character '0', and then directly enumerate $a$, checking whether both $a$ and $b = n - a$ do not contain the character '0'. If they do not, we have found the answer and return $[a, b]$.\n\nThe time complexity is $O(n \\times \\log n)$, where $n$ is the integer given in the problem. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 1318, "explanations": { "1": "We can enumerate each bit of the binary representation of $a$, $b$, and $c$, denoted as $x$, $y$, and $z$ respectively. If the bitwise OR operation result of $x$ and $y$ is different from $z$, we then check if both $x$ and $y$ are $1$. If so, we need to flip twice, otherwise, we only need to flip once. We accumulate all the required flip times.\n\nThe time complexity is $O(\\log M)$, where $M$ is the maximum value of the numbers in the problem. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log M)", "space_complexity": "O(1)" }, { "problem_id": 1319, "explanations": { "1": "We can use a union-find data structure to maintain the connectivity between computers. Traverse all connections, and for each connection $(a, b)$, if $a$ and $b$ are already connected, then this connection is redundant, and we increment the count of redundant connections. Otherwise, we connect $a$ and $b$, and decrement the number of connected components.\n\nFinally, if the number of connected components minus one is greater than the number of redundant connections, it means we cannot connect all computers, so we return -1. Otherwise, we return the number of connected components minus one.\n\nThe time complexity is $O(m \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ and $m$ are the number of computers and the number of connections, respectively." }, "is_english": true, "time_complexity": "O(m \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1320, "explanations": { "1": "We define $f[i][j][k]$ to represent the minimum distance after typing $\\textit{word}[i]$, with finger 1 at position $j$ and finger 2 at position $k$. Here, positions $j$ and $k$ represent the numbers corresponding to the letters, ranging from $[0,..25]$. Initially, $f[i][j][k] = \\infty$.\n\nWe implement a function $\\textit{dist}(a, b)$ to represent the distance between positions $a$ and $b$, i.e., $\\textit{dist}(a, b) = |\\frac{a}{6} - \\frac{b}{6}| + |a \\bmod 6 - b \\bmod 6|$.\n\nNext, we consider typing $\\textit{word}[0]$, i.e., the case with only one letter. There are two choices:\n\n- Finger 1 is at the position of $\\textit{word}[0]$, and finger 2 is at any position. In this case, $f[0][\\textit{word}[0]][k] = 0$, where $k \\in [0,..25]$.\n- Finger 2 is at the position of $\\textit{word}[0]$, and finger 1 is at any position. In this case, $f[0][k][\\textit{word}[0]] = 0$, where $k \\in [0,..25]$.\n\nThen we consider typing $\\textit{word}[1,..n-1]$. Let the positions of the previous letter and the current letter be $a$ and $b$, respectively. Next, we discuss the following cases:\n\nIf the current finger 1 is at position $b$, we enumerate the position $j$ of finger 2. If the previous position $a$ was also the position of finger 1, then $f[i][b][j] = \\min(f[i][b][j], f[i-1][a][j] + \\textit{dist}(a, b))$. If the position of finger 2 is the same as the previous position $a$, i.e., $j = a$, then we enumerate the position $k$ of finger 1 in the previous position. In this case, $f[i][b][j] = \\min(f[i][b][j], f[i-1][k][a] + \\textit{dist}(k, b))$.\n\nSimilarly, if the current finger 2 is at position $b$, we enumerate the position $j$ of finger 1. If the previous position $a$ was also the position of finger 2, then $f[i][j][b] = \\min(f[i][j][b], f[i-1][j][a] + \\textit{dist}(a, b))$. If the position of finger 1 is the same as the previous position $a$, i.e., $j = a$, then we enumerate the position $k$ of finger 2 in the previous position. In this case, $f[i][j][b] = \\min(f[i][j][b], f[i-1][a][k] + \\textit{dist}(k, b))$.\n\nFinally, we enumerate the positions of finger 1 and finger 2 at the last position and take the minimum value as the answer.\n\nThe time complexity is $O(n \\times |\\Sigma|^2)$, and the space complexity is $O(n \\times |\\Sigma|^2)$. Here, $n$ is the length of the string $\\textit{word}$, and $|\\Sigma|$ is the size of the alphabet, which is $26$ in this problem." }, "is_english": true, "time_complexity": "O(n \\times |\\Sigma|^2)", "space_complexity": "O(n \\times |\\Sigma|^2)" }, { "problem_id": 1321, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1322, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1323, "explanations": { "1": "We convert the number to a string, then traverse the string from left to right to find the first occurrence of $6$, replace it with $9$, and then return the integer corresponding to the converted string.\n\nTime complexity $O(\\log \\textit{num})$, space complexity $O(\\log \\textit{num})$. Where $\\textit{num}$ is the given integer." }, "is_english": true, "time_complexity": "O(\\log \\textit{num})", "space_complexity": "O(\\log \\textit{num})" }, { "problem_id": 1324, "explanations": { "1": "我们先将字符串 $s$ 按空格分割成单词数组 $words$,然后遍历单词数组,找出最长的单词长度 $n$。\n\n接下来我们从第 $1$ 到第 $n$ 个字符,分别从单词数组中取出对应的字符,如果当前单词长度不足,则用空格补齐,放到一个字符串 $t$ 中。最后将 $t$ 去掉末尾的空格,加入答案数组中即可。\n\n时间复杂度 $O(m)$,空间复杂度 $O(m)$。其中 $m$ 为字符串 $s$ 的长度。" }, "is_english": false, "time_complexity": "O(m)", "space_complexity": "O(m)" }, { "problem_id": 1325, "explanations": { "1": "我们先判断 $root$ 节点是否为空,若为空,则返回空。\n\n否则,递归地处理 $root$ 的左右子树,即调用 `root.left = removeLeafNodes(root.left, target)` 和 `root.right = removeLeafNodes(root.right, target)`。\n\n然后判断 $root$ 节点是否为叶子节点,即判断 $root.left$ 和 $root.right$ 是否为空,且 $root.val$ 是否等于 $target$。若是,则返回空,否则返回 $root$。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉树的节点个数。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1326, "explanations": { "1": "We note that for all taps that can cover a certain left endpoint, choosing the tap that can cover the farthest right endpoint is optimal.\n\nTherefore, we can preprocess the array $ranges$. For the $i$-th tap, it can cover the left endpoint $l = \\max(0, i - ranges[i])$ and the right endpoint $r = i + ranges[i]$. We calculate the position of the tap that can cover the left endpoint $l$ with the farthest right endpoint and record it in the array $last[i]$.\n\nThen we define the following three variables:\n\n- Variable $ans$ represents the final answer, i.e., the minimum number of taps;\n- Variable $mx$ represents the farthest right endpoint that can currently be covered;\n- Variable $pre$ represents the farthest right endpoint covered by the previous tap.\n\nWe traverse all positions in the range $[0, \\ldots, n-1]$. For the current position $i$, we use $last[i]$ to update $mx$, i.e., $mx = \\max(mx, last[i])$.\n\n- If $mx \\leq i$, it means the next position cannot be covered, so we return $-1$.\n- If $pre = i$, it means a new subinterval needs to be used, so we increment $ans$ by $1$ and update $pre = mx$.\n\nAfter the traversal, we return $ans$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the garden.\n\nSimilar problems:\n\n- [45. Jump Game II](https://github.com/doocs/leetcode/blob/main/solution/0000-0099/0045.Jump%20Game%20II/README.md)\n- [55. Jump Game](https://github.com/doocs/leetcode/blob/main/solution/0000-0099/0055.Jump%20Game/README.md)\n- [1024. Video Stitching](https://github.com/doocs/leetcode/blob/main/solution/1000-1099/1024.Video%20Stitching/README.md)" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1327, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1328, "explanations": { "1": "First, we check if the length of the string is $1$. If it is, we directly return an empty string.\n\nOtherwise, we traverse the first half of the string from left to right, find the first character that is not `'a'`, and change it to `'a'`. If no such character exists, we change the last character to `'b'`.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1329, "explanations": { "1": "We can treat each diagonal of the matrix as an array, sort these arrays, and then fill the sorted elements back into the original matrix.\n\nSpecifically, we denote the number of rows in the matrix as $m$ and the number of columns as $n$. Since any two elements $(i_1, j_1)$ and $(i_2, j_2)$ on the same diagonal satisfy $j_1 - i_1 = j_2 - i_2$, we can determine each diagonal based on the value of $j - i$. To ensure the value is positive, we add an offset $m$, that is, $m - i + j$.\n\nFinally, we fill the sorted elements of each diagonal back into the original matrix.\n\nThe time complexity is $O(m \\times n \\times \\log \\min(m, n))$, and the space complexity is $O(m \\times n)$. Where $m$ and $n$ are the number of rows and columns in the matrix, respectively." }, "is_english": true, "time_complexity": "O(m \\times n \\times \\log \\min(m, n))", "space_complexity": "O(m \\times n)" }, { "problem_id": 1330, "explanations": { "1": "According to the problem description, we need to find the maximum value of the array $\\sum_{i=0}^{n-2} |a_i - a_{i+1}|$ when reversing a subarray once.\n\nNext, we discuss the following cases:\n\n1. Do not reverse the subarray.\n2. Reverse the subarray, and the subarray \"includes\" the first element.\n3. Reverse the subarray, and the subarray \"includes\" the last element.\n4. Reverse the subarray, and the subarray \"does not include\" the first and last elements.\n\nLet $s$ be the array value when the subarray is not reversed, then $s = \\sum_{i=0}^{n-2} |a_i - a_{i+1}|$. We can initialize the answer $ans$ to $s$.\n\nIf we reverse the subarray and the subarray includes the first element, we can enumerate the last element $a_i$ of the reversed subarray, where $0 \\leq i < n-1$. In this case, $ans = \\max(ans, s + |a_0 - a_{i+1}| - |a_i - a_{i+1}|)$.\n\n

\"\"

\n\nSimilarly, if we reverse the subarray and the subarray includes the last element, we can enumerate the first element $a_{i+1}$ of the reversed subarray, where $0 \\leq i < n-1$. In this case, $ans = \\max(ans, s + |a_{n-1} - a_i| - |a_i - a_{i+1}|)$.\n\n

\"\"

\n\nIf we reverse the subarray and the subarray does not include the first and last elements, we consider any two adjacent elements in the array as a point pair $(x, y)$. Let the first element of the reversed subarray be $y_1$, and its left adjacent element be $x_1$; let the last element of the reversed subarray be $x_2$, and its right adjacent element be $y_2$.\n\n

\"\"

\n\nAt this time, compared to not reversing the subarray, the change in the array value is $|x_1 - x_2| + |y_1 - y_2| - |x_1 - y_1| - |x_2 - y_2|$, where the first two terms can be expressed as:\n\n$$\n\\left | x_1 - x_2 \\right | + \\left | y_1 - y_2 \\right | = \\max \\begin{cases} (x_1 + y_1) - (x_2 + y_2) \\\\ (x_1 - y_1) - (x_2 - y_2) \\\\ (-x_1 + y_1) - (-x_2 + y_2) \\\\ (-x_1 - y_1) - (-x_2 - y_2) \\end{cases}\n$$\n\nThen the change in the array value is:\n\n$$\n\\left | x_1 - x_2 \\right | + \\left | y_1 - y_2 \\right | - \\left | x_1 - y_1 \\right | - \\left | x_2 - y_2 \\right | = \\max \\begin{cases} (x_1 + y_1) - \\left |x_1 - y_1 \\right | - \\left ( (x_2 + y_2) + \\left |x_2 - y_2 \\right | \\right ) \\\\ (x_1 - y_1) - \\left |x_1 - y_1 \\right | - \\left ( (x_2 - y_2) + \\left |x_2 - y_2 \\right | \\right ) \\\\ (-x_1 + y_1) - \\left |x_1 - y_1 \\right | - \\left ( (-x_2 + y_2) + \\left |x_2 - y_2 \\right | \\right ) \\\\ (-x_1 - y_1) - \\left |x_1 - y_1 \\right | - \\left ( (-x_2 - y_2) + \\left |x_2 - y_2 \\right | \\right ) \\end{cases}\n$$\n\nTherefore, we only need to find the maximum value $mx$ of $k_1 \\times x + k_2 \\times y$, where $k_1, k_2 \\in \\{-1, 1\\}$, and the corresponding minimum value $mi$ of $|x - y|$. Then the maximum change in the array value is $mx - mi$. The answer is $ans = \\max(ans, s + \\max(0, mx - mi))$.\n\nIn the code implementation, we define an array of length 5, $dirs=[1, -1, -1, 1, 1]$. Each time we take two adjacent elements of the array as the values of $k_1$ and $k_2$, which can cover all cases of $k_1, k_2 \\in \\{-1, 1\\}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$.\n\nSimilar problems:\n\n- [1131. Maximum of Absolute Value Expression](https://github.com/doocs/leetcode/blob/main/solution/1100-1199/1131.Maximum%20of%20Absolute%20Value%20Expression/README_EN.md)" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1331, "explanations": { "1": "First, we copy an array $t$, then sort and deduplicate it to obtain an array of length $m$ that is strictly monotonically increasing.\n\nNext, we traverse the original array $arr$. For each element $x$ in the array, we use binary search to find the position of $x$ in $t$. The position plus one is the rank of $x$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $arr$.", "2": "" }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1332, "explanations": { "1": "如果字符串 $s$ 本身是个回文串,那么只需要删除 $1$ 次。\n\n如果字符串 $s$ 不是个回文串,那么先删除所有的 `'a'`,再删除所有的 `'b'`,总共需要删除 $2$ 次。\n\n时间复杂度 $O(n)$,其中 $n$ 是字符串 $s$ 的长度。空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1333, "explanations": { "1": "我们先将数组 `restaurants` 按照 `rating` 和 `id` 两个维度进行排序,然后再按照题目给定的条件进行筛选即可。\n\n时间复杂度 $O(n \\times \\log n)$,空间复杂度 $O(\\log n)$。其中 $n$ 是数组 `restaurants` 的长度。" }, "is_english": false, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 1334, "explanations": { "1": "我们可以枚举每个城市 $i$ 作为起点,使用 Dijkstra 算法求出从 $i$ 到其他城市的最短距离,然后统计距离不超过阈值的城市个数,最后取最小的个数且编号最大的城市。\n\n时间复杂度 $O(n^3)$,空间复杂度 $O(n^2)$。其中 $n$ 为城市个数。", "2": "我们定义 $g[i][j]$ 表示城市 $i$ 到城市 $j$ 的最短距离,初始时 $g[i][j] = \\infty$, $g[i][i] = 0$,然后我们遍历所有边,对于每条边 $(f, t, w)$,我们令 $g[f][t] = g[t][f] = w$。\n\n接下来,我们用 Floyd 算法求出任意两点之间的最短距离。具体地,我们先枚举中间点 $k$,再枚举起点 $i$ 和终点 $j$,如果 $g[i][k] + g[k][j] \\lt g[i][j]$,那么我们就用更短的距离 $g[i][k] + g[k][j]$ 更新 $g[i][j]$。\n\n最后,我们枚举每个城市 $i$ 作为起点,统计距离不超过阈值的城市个数,最后取最小的个数且编号最大的城市。\n\n时间复杂度 $O(n^3)$,空间复杂度 $O(n^2)$。其中 $n$ 为城市个数。" }, "is_english": false, "time_complexity": "O(n^3)", "space_complexity": "O(n^2)" }, { "problem_id": 1335, "explanations": { "1": "We define $f[i][j]$ as the minimum difficulty to finish the first $i$ jobs within $j$ days. Initially $f[0][0] = 0$, and all other $f[i][j]$ are $\\infty$.\n\nFor the $j$-th day, we can choose to finish jobs $[k,..i]$ on this day. Therefore, we have the following state transition equation:\n\n$$\nf[i][j] = \\min_{k \\in [1,i]} \\{f[k-1][j-1] + \\max_{k \\leq t \\leq i} \\{jobDifficulty[t]\\}\\}\n$$\n\nThe final answer is $f[n][d]$.\n\nThe time complexity is $O(n^2 \\times d)$, and the space complexity is $O(n \\times d)$. Here $n$ and $d$ are the number of jobs and the number of days respectively." }, "is_english": true, "time_complexity": "O(n^2 \\times d)", "space_complexity": "O(n \\times d)" }, { "problem_id": 1336, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1337, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1338, "explanations": { "1": "We can use a hash table or an array $\\textit{cnt}$ to count the occurrences of each number in the array $\\textit{arr}$. Then, we sort the numbers in $\\textit{cnt}$ in descending order. We traverse $\\textit{cnt}$ from largest to smallest, adding the current number $x$ to the answer and adding $x$ to $m$. If $m \\geq \\frac{n}{2}$, we return the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{arr}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1339, "explanations": { "1": "We can solve this problem with two DFS traversals.\n\nIn the first traversal, we use a $\\text{sum}(\\text{root})$ function to recursively calculate the sum of all nodes in the entire tree, denoted as $s$.\n\nIn the second traversal, we use a $\\text{dfs}(\\text{root})$ function to recursively traverse each node and calculate the sum of nodes in the subtree rooted at the current node, denoted as $t$. After splitting at the current node and its parent, the sums of the two subtrees are $t$ and $s - t$ respectively, and their product is $t \\times (s - t)$. We traverse all nodes to find the maximum product, which is the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1340, "explanations": { "1": "我们设计一个函数 $dfs(i)$,表示从下标 $i$ 开始跳跃能够访问的最大下标数。我们可以枚举 $i$ 的所有合法的跳跃目标 $j$,即 $i - d \\leq j \\leq i + d$,并且 $arr[i] \\gt arr[j]$。对于每个合法的 $j$,我们可以递归地计算 $dfs(j)$,并取其中的最大值。最终的答案即为所有 $i$ 的 $dfs(i)$ 的最大值。\n\n我们可以使用记忆化搜索来优化这个过程,即使用一个数组 $f$ 记录每个下标的 $dfs$ 值,避免重复计算。\n\n时间复杂度 $O(n \\times d)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $arr$ 的长度。", "2": "我们可以将数组 $arr$ 中的每个元素 $x$ 与其下标 $i$ 组成一个元组 $(x, i)$,并将这些元组按照 $x$ 从小到大排序。\n\n接下来定义 $f[i]$ 表示从下标 $i$ 开始跳跃能够访问的最大下标数。初始时 $f[i] = 1$,即每个下标都可以单独作为一次跳跃。\n\n我们可以按照元组 $(x, i)$ 的顺序枚举 $i$,并枚举 $i$ 的所有合法的跳跃目标 $j$,即 $i - d \\leq j \\leq i + d$,并且 $arr[i] \\gt arr[j]$。对于每个合法的 $j$,我们可以更新 $f[i]$ 的值,即 $f[i] = \\max(f[i], 1 + f[j])$。\n\n最终的答案即为 $\\max_{0 \\leq i \\lt n} f[i]$。\n\n时间复杂度 $O(n \\log n + n \\times d)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $arr$ 的长度。" }, "is_english": false, "time_complexity": "O(n \\times d)", "space_complexity": "O(n)" }, { "problem_id": 1341, "explanations": { "1": "分别查询两个结果,然后使用 `union all` 合并结果集。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1342, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1343, "explanations": { "1": "We can multiply `threshold` by $k$, so that we can directly compare the sum within the window with `threshold`.\n\nWe maintain a sliding window of length $k$, and for each window, we calculate the sum $s$. If $s$ is greater than or equal to `threshold`, we increment the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array `arr`. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1344, "explanations": { "1": "时针每小时移动 30 度,每分钟移动 0.5 度。分针每分钟移动 6 度。如果指针之间的夹角大于 180 度,则取其与 360 度的差值,以确保获得最小的夹角。\n\n时间复杂度 $O(1)$,空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 1345, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1346, "explanations": { "1": "We define a hash table $s$ to record the elements that have been visited.\n\nTraverse the array $arr$. For each element $x$, if either double of $x$ or half of $x$ is in the hash table $s$, then return `true`. Otherwise, add $x$ to the hash table $s$.\n\nIf no element satisfying the condition is found after the traversal, return `false`.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $arr$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1347, "explanations": { "1": "We can use a hash table or an array $\\textit{cnt}$ to count the occurrences of each character in the string $\\textit{s}$. Then, we traverse the string $\\textit{t}$. For each character, we decrement its count in $\\textit{cnt}$. If the decremented value is less than $0$, it means that this character appears more times in the string $\\textit{t}$ than in the string $\\textit{s}$. In this case, we need to replace this character and increment the answer by one.\n\nAfter the traversal, we return the answer.\n\nThe time complexity is $O(m + n)$, and the space complexity is $O(|\\Sigma|)$, where $m$ and $n$ are the lengths of the strings $\\textit{s}$ and $\\textit{t}$, respectively, and $|\\Sigma|$ is the size of the character set. In this problem, the character set consists of lowercase letters, so $|\\Sigma| = 26$." }, "is_english": true, "time_complexity": "O(m + n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 1348, "explanations": { "1": "我们用哈希表 `data` 记录每个用户的推文时间,用有序列表记录每个用户的所有推文时间。\n\n对于 `recordTweet` 操作,我们将推文时间加入到用户的推文时间列表中。\n\n对于 `getTweetCountsPerFrequency` 操作,我们先计算出时间间隔 `f`,然后遍历用户的推文时间列表,统计每个时间间隔内的推文数量。\n\n时间复杂度,对于 `recordTweet` 操作,总的时间复杂度 $O(n \\times \\log n)$;对于 `getTweetCountsPerFrequency` 操作,总的时间复杂度 $O(q \\times (t + \\log n))$。其中 $n$, $q$ 和 $t$ 分别表示插入的推文数量,查询的次数和时间间隔的长度。" }, "is_english": false, "time_complexity": "O(n \\times \\log n)", "space_complexity": null }, { "problem_id": 1349, "explanations": { "1": "We notice that each seat has two states: selectable and non-selectable. Therefore, we can use a binary number to represent the seat state of each row, where $1$ represents selectable, and $0$ represents non-selectable. For example, for the first row in Example 1, we can represent it as $010010$. Therefore, we convert the initial seats into a one-dimensional array $ss$, where $ss[i]$ represents the seat state of the $i$th row.\n\nNext, we design a function $dfs(seat, i)$, which represents the maximum number of students that can be accommodated starting from the $i$th row, and the seat state of the current row is $seat$.\n\nWe can enumerate all the seat selection states $mask$ of the $i$th row, and judge whether $mask$ meets the following conditions:\n\n- The state $mask$ cannot select seats outside of $seat$;\n- The state $mask$ cannot select adjacent seats.\n\nIf the conditions are met, we calculate the number of seats selected in the current row $cnt$. If it is the last row, update the return value of the function, that is, $ans = \\max(ans, cnt)$. Otherwise, we continue to recursively solve the maximum number of the next row. The seat state of the next row is $nxt = ss[i + 1]$, and we need to exclude the left and right sides of the selected seats in the current row. Then we recursively solve the maximum number of the next row, that is, $ans = \\max(ans, cnt + dfs(nxt, i + 1))$.\n\nFinally, we return $ans$ as the return value of the function.\n\nTo avoid repeated calculations, we can use memoization search to save the return value of the function $dfs(seat, i)$ in a two-dimensional array $f$, where $f[seat][i]$ represents the maximum number of students that can be accommodated starting from the $i$th row, and the seat state of the current row is $seat$.\n\nThe time complexity is $O(4^n \\times n \\times m)$, and the space complexity is $O(2^n \\times m)$. Where $m$ and $n$ are the number of rows and columns of the seats, respectively." }, "is_english": true, "time_complexity": "O(4^n \\times n \\times m)", "space_complexity": "O(2^n \\times m)" }, { "problem_id": 1350, "explanations": { "1": "We can directly use a subquery to find all students who are not in the `Departments` table.", "2": "We can also use a left join to join the `Students` table with the `Departments` table on the condition of `Students.department_id = Departments.id`, and then filter out the students whose `Departments.id` is `NULL`." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1351, "explanations": { "1": "Since the matrix is sorted in non-strictly decreasing order both row-wise and column-wise, we can start traversing from the bottom-left corner of the matrix. Let the current position be $(i, j)$.\n\nIf the element at the current position is greater than or equal to $0$, it means all preceding elements in that row are also greater than or equal to $0$. Therefore, we move the column index $j$ one position to the right, i.e., $j = j + 1$.\n\nIf the element at the current position is less than $0$, it means the current element and all elements to its right in that row are negative. Therefore, we can add $n - j$ to the count of negative numbers (where $n$ is the number of columns in the matrix), and then move the row index $i$ one position upward, i.e., $i = i - 1$.\n\nWe repeat the above process until the row index $i$ is less than $0$ or the column index $j$ is greater than or equal to $n$. Finally, the count of negative numbers is the answer.\n\nThe time complexity is $O(m + n)$, where $m$ and $n$ are the number of rows and columns of the matrix, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m + n)", "space_complexity": "O(1)" }, { "problem_id": 1352, "explanations": { "1": "We initialize an array $s$, where $s[i]$ represents the product of the first $i$ numbers.\n\nWhen calling `add(num)`, we judge whether `num` is $0$. If it is, we set $s$ to `[1]`. Otherwise, we multiply the last element of $s$ by `num` and add the result to the end of $s$.\n\nWhen calling `getProduct(k)`, we now judge whether the length of $s$ is less than or equal to $k$. If it is, we return $0$. Otherwise, we return the last element of $s$ divided by the $k + 1$th element from the end of $s$. That is, $s[-1] / s[-k - 1]$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(n)$. Where $n$ is the number of times `add` is called." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(n)" }, { "problem_id": 1353, "explanations": { "1": "We use a hash table $\\textit{g}$ to record the start and end times of each event. The key is the start time of the event, and the value is a list containing the end times of all events that start at that time. Two variables, $\\textit{l}$ and $\\textit{r}$, are used to record the minimum start time and the maximum end time among all events.\n\nFor each time point $s$ from $\\textit{l}$ to $\\textit{r}$ in increasing order, we perform the following steps:\n\n1. Remove from the priority queue all events whose end time is less than the current time $s$.\n2. Add the end times of all events that start at the current time $s$ to the priority queue.\n3. If the priority queue is not empty, take out the event with the earliest end time, increment the answer count, and remove this event from the priority queue.\n\nIn this way, we ensure that at each time point $s$, we always attend the event that ends the earliest, thus maximizing the number of events attended.\n\nThe time complexity is $O(M \\times \\log n)$, and the space complexity is $O(n)$, where $M$ is the maximum end time and $n$ is the number of events." }, "is_english": true, "time_complexity": "O(M \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1354, "explanations": { "1": "We observe that if we start constructing the target array $\\textit{target}$ from the array $\\textit{arr}$ in a forward manner, it is difficult to determine which index $i$ to choose each time, making the problem quite complex. However, if we construct in reverse starting from the array $\\textit{target}$, each construction step must select the largest element in the current array, which ensures that each construction is unique, making the problem relatively simple.\n\nTherefore, we can use a priority queue (max heap) to store the elements of array $\\textit{target}$, and use a variable $s$ to record the sum of all elements in array $\\textit{target}$. Each time we extract the maximum element $mx$ from the priority queue and calculate the sum $t$ of all elements in the current array except $mx$. If $t \\lt 1$ or $mx - t \\lt 1$, it means the target array $\\textit{target}$ cannot be constructed, and we return `false`. Otherwise, we calculate $mx \\bmod t$. If $mx \\bmod t = 0$, we set $x = t$; otherwise, we set $x = mx \\bmod t$. We add $x$ to the priority queue and update the value of $s$. We repeat this process until all elements in the priority queue become $1$, at which point we return `true`.\n\nThe time complexity is $O(n \\log n)$ and the space complexity is $O(n)$, where $n$ is the length of array $\\textit{target}$." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1355, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1356, "explanations": { "1": "We sort the array $arr$ according to the requirements of the problem, that is, sort in ascending order according to the number of $1$s in the binary representation. If there are multiple numbers with the same number of $1$s in the binary representation, they must be sorted in ascending order by numerical value.\n\nThe time complexity is $O(n \\log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $arr$." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1357, "explanations": { "1": "Use a hash table $d$ to store the product ID and price, then traverse the product ID and quantity, calculate the total price, and then calculate the price after discount based on the discount.\n\nThe time complexity of initialization is $O(n)$, where $n$ is the number of products. The time complexity of the `getBill` function is $O(m)$, where $m$ is the number of products purchased. The space complexity is $O(n)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1358, "explanations": { "1": "We use an array $d$ of length $3$ to record the most recent occurrence of the three characters, initially all set to $-1$.\n\nWe traverse the string $s$. For the current position $i$, we first update $d[s[i]]=i$, then the number of valid strings is $\\min(d[0], d[1], d[2]) + 1$, which is accumulated to the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1359, "explanations": { "1": "We define $f[i]$ as the number of all valid pickup/delivery sequences for $i$ orders. Initially, $f[1] = 1$.\n\nWe can choose any of these $i$ orders as the last delivery order $D_i$, then its pickup order $P_i$ can be at any position in the previous $2 \\times i - 1$, and the number of pickup/delivery sequences for the remaining $i - 1$ orders is $f[i - 1]$, so $f[i]$ can be expressed as:\n\n$$\nf[i] = i \\times (2 \\times i - 1) \\times f[i - 1]\n$$\n\nThe final answer is $f[n]$.\n\nWe notice that the value of $f[i]$ is only related to $f[i - 1]$, so we can use a variable instead of an array to reduce the space complexity.\n\nThe time complexity is $O(n)$, where $n$ is the number of orders. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1360, "explanations": { "1": "First, we define a function `isLeapYear(year)` to determine whether the given year `year` is a leap year. If it is a leap year, return `true`, otherwise return `false`.\n\nNext, we define another function `daysInMonth(year, month)` to calculate the total number of days in the given year `year` and month `month`. We can use an array `days` to store the number of days in each month, where `days[1]` represents the number of days in February. If it is a leap year, it is $29$ days, otherwise it is $28$ days.\n\nThen, we define another function `calcDays(date)` to calculate the number of days from the given date `date` to `1971-01-01`. We can use `date.split(\"-\")` to split the date `date` into year `year`, month `month`, and day `day` by `-`. Then we can use a loop to calculate the total number of days from `1971` to `year`, then calculate the total number of days from January to `month`, and finally add `day` days.\n\nFinally, we only need to return the absolute value of `calcDays(date1) - calcDays(date2)`.\n\nThe time complexity is $O(y + m)$, where $y$ represents the number of years from the given date to `1971-01-01`, and $m$ represents the number of months of the given date. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(y + m)", "space_complexity": "O(1)" }, { "problem_id": 1361, "explanations": { "1": "We can traverse each node $i$ and its corresponding left and right children $l$, $r$, using an array $vis$ to record whether the node has a parent:\n\n- If the child node already has a parent, it means there are multiple fathers, which does not meet the condition, so we return `false` directly.\n- If the child node and the parent node are already in the same connected component, it means a cycle will be formed, which does not meet the condition, so we return `false` directly.\n- Otherwise, we perform a union operation, set the corresponding position of the $vis$ array to `true`, and decrease the number of connected components by $1$.\n\nAfter the traversal, we check whether the number of connected components in the union-find set is $1$. If it is, we return `true`, otherwise, we return `false`.\n\nThe time complexity is $O(n \\times \\alpha(n))$, and the space complexity is $O(n)$. Where $n$ is the number of nodes, and $\\alpha(n)$ is the inverse Ackermann function, which is less than $5$." }, "is_english": true, "time_complexity": "O(n \\times \\alpha(n))", "space_complexity": "O(n)" }, { "problem_id": 1362, "explanations": { "1": "We design a function $f(x)$ that returns two numbers whose product equals $x$ and the absolute difference between these two numbers is the smallest. We can start enumerating $i$ from $\\sqrt{x}$. If $x$ can be divided by $i$, then $\\frac{x}{i}$ is another factor. At this point, we have found two factors whose product equals $x$. We can return them directly. Otherwise, we decrease the value of $i$ and continue to enumerate.\n\nNext, we only need to calculate $f(num + 1)$ and $f(num + 2)$ respectively, and then compare the return values of the two functions. We return the one with the smaller absolute difference.\n\nThe time complexity is $O(\\sqrt{num})$, and the space complexity is $O(1)$. Where $num$ is the given integer." }, "is_english": true, "time_complexity": "O(\\sqrt{num})", "space_complexity": "O(1)" }, { "problem_id": 1363, "explanations": { "1": "We define $f[i][j]$ as the maximum length of selecting several numbers from the first $i$ numbers, so that the sum of the selected numbers modulo $3$ equals $j$. To make the selected numbers as large as possible, we need to select as many numbers as possible, so we need to make $f[i][j]$ as large as possible. We initialize $f[0][0] = 0$, and the rest of $f[0][j] = -\\infty$.\n\nConsider how $f[i][j]$ transitions. We can choose not to select the $i$-th number, in which case $f[i][j] = f[i - 1][j]$; we can also choose to select the $i$-th number, in which case $f[i][j] = f[i - 1][(j - x_i \\bmod 3 + 3) \\bmod 3] + 1$, where $x_i$ represents the value of the $i$-th number. Therefore, we have the following state transition equation:\n\n$$\nf[i][j] = \\max \\{ f[i - 1][j], f[i - 1][(j - x_i \\bmod 3 + 3) \\bmod 3] + 1 \\}\n$$\n\nIf $f[n][0] \\le 0$, then we cannot select any number, so the answer string is empty. Otherwise, we can backtrack through the $f$ array to find out the selected numbers.\n\nDefine $i = n$, $j = 0$, start backtracking from $f[i][j]$, let $k = (j - x_i \\bmod 3 + 3) \\bmod 3$, if $f[i - 1][k] + 1 = f[i][j]$, then we have selected the $i$-th number, otherwise we have not selected the $i$-th number. If we have selected the $i$-th number, then we update $j$ to $k$, otherwise we keep $j$ unchanged. To make the number of the same length as large as possible, we should prefer to select larger numbers, so we should sort the array first.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1364, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1365, "explanations": { "1": "We can make a copy of the array $nums$, denoted as $arr$, and then sort $arr$ in ascending order.\n\nNext, for each element $x$ in $nums$, we can use binary search to find the index $j$ of the first element that is greater than or equal to $x$. Then $j$ is the number of elements that are smaller than $x$. We can store $j$ in the answer array.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $nums$.", "2": "We notice that the range of elements in the array $nums$ is $[0, 100]$. Therefore, we can use the counting sort method to first count the number of each element in the array $nums$. Then we calculate the prefix sum of the counting array. Finally, we traverse the array $nums$. For each element $x$, we directly add the value of the element at index $x$ in the counting array to the answer array.\n\nThe time complexity is $O(n + M)$, and the space complexity is $O(M)$. Where $n$ and $M$ are the length and the maximum value of the array $nums$, respectively." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1366, "explanations": { "1": "For each candidate, we can count the number of votes they receive at each rank, then compare the vote counts for different ranks in order. If the vote counts are the same, we compare the letters.\n\nThe time complexity is $O(n \\times m + m^2 \\times \\log m)$, and the space complexity is $O(m^2)$. Here, $n$ is the length of $\\textit{votes}$, and $m$ is the number of candidates, i.e., the length of $\\textit{votes}[0]$." }, "is_english": true, "time_complexity": "O(n \\times m + m^2 \\times \\log m)", "space_complexity": "O(m^2)" }, { "problem_id": 1367, "explanations": { "1": "We design a recursive function $dfs(head, root)$, which indicates whether the linked list $head$ corresponds to a subpath on the path starting with $root$ in the binary tree. The logic of the function $dfs(head, root)$ is as follows:\n\n- If the linked list $head$ is empty, it means that the linked list has been traversed, return `true`;\n- If the binary tree $root$ is empty, it means that the binary tree has been traversed, but the linked list has not been traversed yet, return `false`;\n- If the value of the binary tree $root$ is not equal to the value of the linked list $head$, return `false`;\n- Otherwise, return $dfs(head.next, root.left)$ or $dfs(head.next, root.right)$.\n\nIn the main function, we call $dfs(head, root)$ for each node of the binary tree. As long as one returns `true`, it means that the linked list is a subpath of the binary tree, return `true`; if all nodes return `false`, it means that the linked list is not a subpath of the binary tree, return `false`.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 1368, "explanations": { "1": "This problem is essentially a shortest path model, but what we are looking for is the minimum number of direction changes.\n\nIn an undirected graph where the edge weights are only 0 and 1, we can use a double-ended queue for BFS. The principle is that when the weight of the point that can be expanded currently is 0, it is added to the front of the queue; when the weight is 1, it is added to the end of the queue.\n\n> If the weight of an edge is 0, then the weight of the newly expanded node is the same as the weight of the current queue head node. Obviously, it can be used as the starting point for the next expansion." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1369, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1370, "explanations": { "1": "First, we use a hash table or an array $cnt$ of length $26$ to count the number of occurrences of each character in the string $s$.\n\nThen, we enumerate the letters $[a,...,z]$. For the current enumerated letter $c$, if $cnt[c] > 0$, we append the letter $c$ to the end of the answer string and decrease $cnt[c]$ by one. We repeat this step until $cnt[c] = 0$. Then we enumerate the letters $[z,...,a]$ in reverse order and perform similar operations. If the length of the answer string equals the length of $s$, then we have completed all the concatenation operations.\n\nThe time complexity is $O(n \\times |\\Sigma|)$, and the space complexity is $O(|\\Sigma|)$. Where $n$ is the length of the string $s$, and $\\Sigma$ is the character set. In this problem, the character set is all lowercase letters, so $|\\Sigma| = 26$." }, "is_english": true, "time_complexity": "O(n \\times |\\Sigma|)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 1371, "explanations": { "1": "According to the problem description, if we use a number to represent the parity of the occurrences of each vowel in a prefix of the string $\\textit{s}$, then when two prefixes have the same number, the substring between these two prefixes is a valid substring.\n\nWe can use the lower five bits of a binary number to represent the parity of the five vowels, where the $i$-th bit being $1$ means the vowel appears an odd number of times in the substring, and $0$ means it appears an even number of times.\n\nWe use $\\textit{mask}$ to represent this binary number and use an array or hash table $\\textit{d}$ to record the first occurrence of each $\\textit{mask}$. Initially, we set $\\textit{d}[0] = -1$, indicating that the start position of the empty string is $-1$.\n\nWe traverse the string $\\textit{s}$, and if we encounter a vowel, we toggle the corresponding bit in $\\textit{mask}$. Next, we check if $\\textit{mask}$ has appeared before. If it has, we have found a valid substring, and its length is the current position minus the last occurrence of $\\textit{mask}$. Otherwise, we store the current position of $\\textit{mask}$ in $\\textit{d}$.\n\nAfter traversing the string, we will have found the longest valid substring.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $\\textit{s}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1372, "explanations": { "1": "时间复杂度 $O(n)$,其中 $n$ 是树中节点的个数。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": null }, { "problem_id": 1373, "explanations": { "1": "To determine whether a tree is a binary search tree, it needs to meet the following four conditions:\n\n- The left subtree is a binary search tree;\n- The right subtree is a binary search tree;\n- The maximum value of the left subtree is less than the value of the root node;\n- The minimum value of the right subtree is greater than the value of the root node.\n\nTherefore, we design a function $dfs(root)$, the return value of the function is a quadruple $(bst, mi, mx, s)$, where:\n\n- The number $bst$ indicates whether the tree with $root$ as the root is a binary search tree. If it is a binary search tree, then $bst = 1$; otherwise $bst = 0$;\n- The number $mi$ represents the minimum value of the tree with $root$ as the root;\n- The number $mx$ represents the maximum value of the tree with $root$ as the root;\n- The number $s$ represents the sum of all nodes of the tree with $root$ as the root.\n\nThe execution logic of the function $dfs(root)$ is as follows:\n\nIf $root$ is an empty node, return $(1, +\\infty, -\\infty, 0)$, indicating that the empty tree is a binary search tree, the minimum value and maximum value are positive infinity and negative infinity respectively, and the sum of nodes is $0$.\n\nOtherwise, recursively calculate the left subtree and right subtree of $root$, and get $(lbst, lmi, lmx, ls)$ and $(rbst, rmi, rmx, rs)$ respectively, then judge whether the $root$ node meets the conditions of the binary search tree.\n\nIf $lbst = 1$ and $rbst = 1$ and $lmx < root.val < rmi$, then the tree with $root$ as the root is a binary search tree, and the sum of nodes $s= ls + rs + root.val$. We update the answer $ans = \\max(ans, s)$, and return $(1, \\min(lmi, root.val), \\max(rmx, root.val), s)$.\n\nOtherwise, the tree with $root$ as the root is not a binary search tree, we return $(0, 0, 0, 0)$.\n\nWe call $dfs(root)$ in the main function. After execution, the answer is $ans$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1374, "explanations": { "1": "If $n$ is odd, then we can directly construct a string with $n$ `'a'` characters.\n\nIf $n$ is even, then we can construct a string with $n-1$ `'a'` characters and $1$ `'b'` character.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1375, "explanations": { "1": "We can traverse the array $flips$, keeping track of the maximum value $mx$ of the elements we have traversed so far. If $mx$ equals the current index $i$ we are traversing, it means that the first $i$ elements have all been flipped, i.e., the prefix is consistent, and we increment the answer.\n\nAfter the traversal is finished, we return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $flips$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1376, "explanations": { "1": "We first build an adjacent list $g$ according to the $manager$ array, where $g[i]$ represents all direct subordinates of employee $i$.\n\nNext, we design a function $dfs(i)$, which means the time required for employee $i$ to notify all his subordinates (including direct subordinates and indirect subordinates), and then the answer is $dfs(headID)$.\n\nIn function $dfs(i)$, we need to traverse all direct subordinates $j$ of $i$. For each subordinate, employee $i$ needs to notify him, which takes $informTime[i]$ time, and his subordinates need to notify their subordinates, which takes $dfs(j)$ time. We take the maximum value of $informTime[i] + dfs(j)$ as the return value of function $dfs(i)$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of employees." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1377, "explanations": { "1": "First, based on the undirected tree edges given in the problem, we construct an adjacency list $g$, where $g[u]$ represents all adjacent vertices of vertex $u$.\n\nThen, we define the following data structures:\n\n- Queue $q$, used to store the vertices and their probabilities for each round of search. Initially, $q = [(1, 1.0)]$, indicating that the probability of the frog being at vertex $1$ is $1.0$;\n- Array $vis$, used to record whether each vertex has been visited. Initially, $vis[1] = true$, and all other elements are $false$.\n\nNext, we start the breadth-first search.\n\nIn each round of search, we take out the head element $(u, p)$ of the queue, where $u$ and $p$ represent the current vertex and its probability, respectively. The number of unvisited adjacent vertices of the current vertex $u$ is denoted as $cnt$.\n\n- If $u = target$, it means that the frog has reached the target vertex. At this time, we judge whether the frog reaches the target vertex in $t$ seconds, or it reaches the target vertex in less than $t$ seconds but cannot jump to other vertices (i.e., $t=0$ or $cnt=0$). If so, return $p$, otherwise return $0$.\n- If $u \\neq target$, we evenly distribute the probability $p$ to all unvisited adjacent vertices of $u$, then add these vertices to the queue $q$, and mark these vertices as visited.\n\nAt the end of a round of search, we decrease $t$ by $1$, and then continue the next round of search until the queue is empty or $t \\lt 0$." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1378, "explanations": { "1": "我们可以使用 `LEFT JOIN` 来连接 `Employees` 和 `EmployeeUNI` 表,然后使用 `SELECT` 语句来选择 `unique_id` 和 `name` 列。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1379, "explanations": { "1": "We design a function $dfs(root1, root2)$, which performs DFS traversal simultaneously in trees $root1$ and $root2$. When traversing to a node, if this node happens to be $target$, then we return the corresponding node in $root2$. Otherwise, we recursively search for $target$ in the left and right subtrees of $root1$ and $root2$, and return the result that is not empty.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in the tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1380, "explanations": { "1": "We can use two arrays $rows$ and $cols$ to record the minimum value of each row and the maximum value of each column in the matrix. Then, we traverse each element in the matrix, checking whether this element is the minimum value of its row and the maximum value of its column. If it is, then this element is a lucky number, and we add it to the answer array.\n\nAfter the traversal is finished, we return the answer array.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m + n)$. Where $m$ and $n$ are the number of rows and columns in the matrix, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m + n)" }, { "problem_id": 1381, "explanations": { "1": "We can use an array $stk$ to simulate the stack, and an integer $i$ to represent the position of the next element to be pushed into the stack. In addition, we need another array $add$ to record the cumulative increment value at each position.\n\nWhen calling $push(x)$, if $i < maxSize$, we put $x$ into $stk[i]$ and increment $i$ by one.\n\nWhen calling $pop()$, if $i \\leq 0$, it means the stack is empty, so we return $-1$. Otherwise, we decrement $i$ by one, and the answer is $stk[i] + add[i]$. Then we add $add[i]$ to $add[i - 1]$, and set $add[i]$ to zero. Finally, we return the answer.\n\nWhen calling $increment(k, val)$, if $i > 0$, we add $val$ to $add[\\min(i, k) - 1]$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(n)$. Where $n$ is the maximum capacity of the stack." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(n)" }, { "problem_id": 1382, "explanations": { "1": "Since the original tree is a binary search tree, we can save the result of the in-order traversal in an array $nums$. Then we design a function $build(i, j)$, which is used to construct a balanced binary search tree within the index range $[i, j]$ in $nums$. The answer is $build(0, |nums| - 1)$.\n\nThe execution logic of the function $build(i, j)$ is as follows:\n\n- If $i > j$, then the balanced binary search tree is empty, return an empty node;\n- Otherwise, we take $mid = (i + j) / 2$ as the root node, then recursively build the left and right subtrees, and return the root node.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in the binary search tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1383, "explanations": { "1": "本题是求“速度和”与“效率最小值”乘积的最大值。变量有两个,我们可以从大到小枚举 `efficiency[i]` 作为效率最小值,在所有效率大于等于 `efficiency[i]` 的工程师中选取不超过 $k-1$ 个,让他们速度和最大。\n\n时间复杂度 $O(n\\log n)$。\n\n相似题目:\n\n- [857. 雇佣 K 名工人的最低成本](https://github.com/doocs/leetcode/blob/main/solution/0800-0899/0857.Minimum%20Cost%20to%20Hire%20K%20Workers/README.md)" }, "is_english": false, "time_complexity": "O(n\\log n)", "space_complexity": null }, { "problem_id": 1384, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1385, "explanations": { "1": "We can first sort the array $\\textit{arr2}$, and then for each element $x$ in the array $\\textit{arr1}$, use binary search to find the first element in the array $\\textit{arr2}$ that is greater than or equal to $x - d$. If such an element exists and is less than or equal to $x + d$, it does not meet the distance requirement. Otherwise, it meets the distance requirement. We count the number of elements that meet the distance requirement, which is the answer.\n\nThe time complexity is $O((m + n) \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $m$ and $n$ are the lengths of the arrays $\\textit{arr1}$ and $\\textit{arr2}$, respectively." }, "is_english": true, "time_complexity": "O((m + n) \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 1386, "explanations": { "1": "We use a hash table $d$ to store all the reserved seats, where the key is the row number, and the value is the state of the reserved seats in that row, i.e., a binary number. The $j$-th bit being $1$ means the $j$-th seat is reserved, and $0$ means the $j$-th seat is not reserved.\n\nWe traverse $reservedSeats$, for each seat $(i, j)$, we add the state of the $j$-th seat (corresponding to the $10-j$ bit in the lower bits) to $d[i]$.\n\nFor rows that do not appear in the hash table $d$, we can arrange $2$ families arbitrarily, so the initial answer is $(n - len(d)) \\times 2$.\n\nNext, we traverse the state of each row in the hash table. For each row, we try to arrange the situations $1234, 5678, 3456$ in turn. If a situation can be arranged, we add $1$ to the answer.\n\nAfter the traversal, we get the final answer.\n\nThe time complexity is $O(m)$, and the space complexity is $O(m)$. Where $m$ is the length of $reservedSeats$." }, "is_english": true, "time_complexity": "O(m)", "space_complexity": "O(m)" }, { "problem_id": 1387, "explanations": { "1": "First, we define a function $\\textit{f}(x)$, which represents the number of steps required to transform the number $x$ into $1$, i.e., the power value of the number $x$.\n\nThen, we sort all the numbers in the interval $[\\textit{lo}, \\textit{hi}]$ in ascending order based on their power values. If the power values are the same, we sort them in ascending order based on the numbers themselves.\n\nFinally, we return the $k$-th number in the sorted list.\n\nThe time complexity is $O(n \\times \\log n \\times M)$, and the space complexity is $O(n)$. Here, $n$ is the number of numbers in the interval $[\\textit{lo}, \\textit{hi}]$, and $M$ is the maximum value of $f(x)$, which is at most $178$ in this problem." }, "is_english": true, "time_complexity": "O(n \\times \\log n \\times M)", "space_complexity": "O(n)" }, { "problem_id": 1388, "explanations": { "1": "We can transform this problem into: In a circular array of length $3n$, select $n$ non-adjacent numbers so that the sum of these $n$ numbers is maximized.\n\nThe proof is as follows:\n\n- When $n = 1$, we can choose any number in the array.\n- When $n > 1$, there must exist a number such that there are two consecutive numbers on one side of it that have not been selected, and at least one number on the other side has not been selected. Therefore, we can remove this number and the numbers on both sides of it from the array, and then the remaining $3(n - 1)$ numbers form a new circular array. The problem scale is reduced to selecting $n - 1$ non-adjacent numbers in a circular array of length $3(n - 1)$, so that the sum of these $n - 1$ numbers is maximized.\n\nTherefore, the problem we need to solve can be transformed into: In a circular array of length $3n$, select $n$ non-adjacent numbers so that the sum of these $n$ numbers is maximized.\n\nIn a circular array, if the first number is selected, the last number cannot be selected. If the last number is selected, the first number cannot be selected. Therefore, we can split the circular array into two arrays, one is without the first number, and the other is without the last number. Then solve the maximum value of these two arrays separately, and finally take the larger of the two maximum values.\n\nWe use a function $g(nums)$, which represents the maximum sum of selecting $n$ non-adjacent numbers in the array $nums$. Then our goal is to find the larger value between $g(slices)$ and $g(slices[1:])$.\n\nThe solution method of function $g(nums)$ is as follows:\n\nWe denote the length of array $nums$ as $m$, and define $f[i][j]$ as the maximum sum of selecting $j$ non-adjacent numbers in the first $i$ numbers of array $nums$.\n\nConsider $f[i][j]$, if we do not select the $i$-th number, then $f[i][j] = f[i - 1][j]$. If we select the $i$-th number, then $f[i][j] = f[i - 2][j - 1] + nums[i - 1]$. Therefore, we can get the state transition equation:\n\n$$\nf[i][j] = \\max(f[i - 1][j], f[i - 2][j - 1] + nums[i - 1])\n$$\n\nFinally, return $f[m][n]$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Where $n$ is the length of the array $slices$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 1389, "explanations": { "1": "We create a list $target$ to store the target array. Since the problem guarantees that the insertion position always exists, we can directly insert in the given order into the corresponding position.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$. Where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 1390, "explanations": { "1": "We can perform factor decomposition on each number. If the number of factors is $4$, then this number meets the requirements of the problem, and we can add its factors to the answer.\n\nThe time complexity is $O(n \\times \\sqrt{n})$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\sqrt{n})", "space_complexity": "O(1)" }, { "problem_id": 1391, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1392, "explanations": { "1": "**String Hashing** is a method to map a string of any length to a non-negative integer, with the probability of collision being almost zero. String hashing is used to calculate the hash value of a string, which allows for quick determination of whether two strings are equal.\n\nWe choose a fixed value BASE, and consider the string as a number in BASE radix, assigning a value greater than 0 to represent each character. Generally, the values we assign are much smaller than BASE. For example, for strings composed of lowercase letters, we can assign a=1, b=2, ..., z=26. We choose a fixed value MOD, and calculate the remainder of the BASE radix number divided by MOD, which is used as the hash value of the string.\n\nGenerally, we choose BASE=131 or BASE=13331, at which point the probability of hash value collision is extremely low. As long as the hash values of two strings are the same, we consider the two strings to be equal. Usually, MOD is chosen as $2^{64}$. In C++, we can directly use the unsigned long long type to store this hash value. When calculating, we do not handle arithmetic overflow. When overflow occurs, it is equivalent to automatically taking the modulus of $2^{64}$, which can avoid inefficient modulus operations.\n\nExcept for extremely specially constructed data, the above hash algorithm is unlikely to produce collisions. In general, the above hash algorithm can appear in the standard answers of the problem. We can also choose some appropriate values of BASE and MOD (such as large prime numbers), and perform several groups of hash operations. Only when the results are all the same do we consider the original strings to be equal, making it even more difficult to construct data that causes this hash to produce errors.", "2": "According to the problem description, we need to find the longest happy prefix of a string, which is the longest prefix of the string that is also a suffix of the string. We can use the KMP algorithm to solve this problem.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1393, "explanations": { "1": "We use `GROUP BY` to group the buy and sell operations of the same stock, and then use `SUM(IF())` to calculate the capital gains and losses of each stock." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1394, "explanations": { "1": "We can use a hash table or an array $\\textit{cnt}$ to count the occurrences of each number in $\\textit{arr}$. Then, we iterate through $\\textit{cnt}$ to find the largest $x$ such that $\\textit{cnt}[x] = x$. If there is no such $x$, return $-1$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the $\\textit{arr}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1395, "explanations": { "1": "We can enumerate each element $rating[i]$ in the array $rating$ as the middle element, then count the number of elements $l$ that are smaller than it on the left, and the number of elements $r$ that are larger than it on the right. The number of combat units with this element as the middle element is $l \\times r + (i - l) \\times (n - i - 1 - r)$. We can add this to the answer.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(1)$. Where $n$ is the length of the array $rating$.", "2": "We can use two binary indexed trees to maintain the number of elements $l$ that are smaller than each element on the left in the array $rating$, and the number of elements $r$ that are larger than it on the right. Then count the number of combat units with this element as the middle element as $l \\times r + (i - l) \\times (n - i - 1 - r)$, and add this to the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $rating$.", "3": "" }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(1)" }, { "problem_id": 1396, "explanations": { "1": "We use two hash tables to store data:\n\n- `ts`: Stores the passenger's id, check-in time, and check-in station. The key is the passenger's id, and the value is a tuple `(t, stationName)`.\n- `d`: Stores the passenger's check-in station, check-out station, travel time, and number of trips. The key is a tuple `(startStation, endStation)`, and the value is a tuple `(totalTime, count)`.\n\nWhen a passenger checks in, we store the passenger's id, check-in time, and check-in station in `ts`, i.e., `ts[id] = (t, stationName)`.\n\nWhen a passenger checks out, we retrieve the passenger's check-in time and station `(t0, station)` from `ts`, then calculate the passenger's travel time $t - t_0$, and store the passenger's travel time and number of trips in `d`.\n\nWhen we want to calculate a passenger's average travel time, we retrieve the passenger's total travel time and number of trips `(totalTime, count)` from `d`, then calculate the average travel time as $totalTime / count$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(n)$. Where $n$ is the number of passengers." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(n)" }, { "problem_id": 1397, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1398, "explanations": { "1": "We can use `LEFT JOIN` to join the `Customers` table and the `Orders` table, then group them by `customer_id`, and finally filter out the customers who have purchased products A and B but not product C." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1399, "explanations": { "1": "We note that the number does not exceed $10^4$, so the sum of the digits also does not exceed $9 \\times 4 = 36$. Therefore, we can use a hash table or an array of length $40$, denoted as $cnt$, to count the number of each sum of digits, and use a variable $mx$ to represent the maximum count of the sum of digits.\n\nWe enumerate each number in $[1,..n]$, calculate its sum of digits $s$, then increment $cnt[s]$ by $1$. If $mx < cnt[s]$, we update $mx = cnt[s]$ and set $ans$ to $1$. If $mx = cnt[s]$, we increment $ans$ by $1$.\n\nFinally, we return $ans$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$, where $n$ is the given number." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 1400, "explanations": { "1": "First, we check if the length of string $s$ is less than $k$. If it is, we cannot construct $k$ palindrome strings, so we can directly return `false`.\n\nOtherwise, we use a hash table or an array $cnt$ to count the occurrences of each character in string $s$. Finally, we only need to count the number of characters $x$ that appear an odd number of times in $cnt$. If $x$ is greater than $k$, we cannot construct $k$ palindrome strings, so we return `false`; otherwise, we return `true`.\n\nThe time complexity is $O(n)$, and the space complexity is $O(C)$. Where $n$ is the length of string $s$, and $C$ is the size of the character set, here $C=26$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(C)" }, { "problem_id": 1401, "explanations": { "1": "For a point $(x, y)$, its shortest distance to the center of the circle $(xCenter, yCenter)$ is $\\sqrt{(x - xCenter)^2 + (y - yCenter)^2}$. If this distance is less than or equal to the radius $radius$, then this point is within the circle (including the boundary).\n\nFor points within the rectangle (including the boundary), their x-coordinates $x$ satisfy $x_1 \\leq x \\leq x_2$, and their y-coordinates $y$ satisfy $y_1 \\leq y \\leq y_2$. To determine whether the circle and rectangle overlap, we need to find a point $(x, y)$ within the rectangle such that $a = |x - xCenter|$ and $b = |y - yCenter|$ are minimized. If $a^2 + b^2 \\leq radius^2$, then the circle and rectangle overlap.\n\nTherefore, the problem is transformed into finding the minimum value of $a = |x - xCenter|$ when $x \\in [x_1, x_2]$, and the minimum value of $b = |y - yCenter|$ when $y \\in [y_1, y_2]$.\n\nFor $x \\in [x_1, x_2]$:\n\n- If $x_1 \\leq xCenter \\leq x_2$, then the minimum value of $|x - xCenter|$ is $0$;\n- If $xCenter < x_1$, then the minimum value of $|x - xCenter|$ is $x_1 - xCenter$;\n- If $xCenter > x_2$, then the minimum value of $|x - xCenter|$ is $xCenter - x_2$.\n\nSimilarly, we can find the minimum value of $|y - yCenter|$ when $y \\in [y_1, y_2]$. We can use a function $f(i, j, k)$ to handle the above situations.\n\nThat is, $a = f(x_1, x_2, xCenter)$, $b = f(y_1, y_2, yCenter)$. If $a^2 + b^2 \\leq radius^2$, then the circle and rectangle overlap." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1402, "explanations": { "1": "Suppose we only choose one dish, then we should choose the dish with the highest satisfaction $s_0$, and check whether $s_0$ is greater than 0. If $s_0 \\leq 0$, then we don't cook any dishes, otherwise, we cook this dish, and the total satisfaction is $s_0$.\n\nIf we choose two dishes, then we should choose the two dishes with the highest satisfaction $s_0$ and $s_1$, and the satisfaction is $s_1 + 2 \\times s_0$. At this time, we need to ensure that the satisfaction after the selection is greater than the satisfaction before the selection, that is, $s_1 + 2 \\times s_0 > s_0$, which means as long as $s_1 + s_0 > 0$, we can choose these two dishes.\n\nBy analogy, we can find a rule, that is, we should choose the $k$ dishes with the highest satisfaction, and ensure that the sum of the satisfaction of the first $k$ dishes is greater than $0$.\n\nIn implementation, we can first sort the satisfaction of all dishes, and then start choosing from the dish with the highest satisfaction. Each time we add the satisfaction of the current dish, if the result of the addition is less than or equal to $0$, then we no longer choose the dishes behind, otherwise, we choose this dish.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 1403, "explanations": { "1": "We can first sort the array $nums$ in descending order, then add the elements to the array from largest to smallest. After each addition, we check whether the sum of the current elements is greater than the sum of the remaining elements. If it is, we return the current array.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Where $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 1404, "explanations": { "1": "We simulate operations $1$ and $2$, while maintaining a carry $\\textit{carry}$ to indicate whether there is a current carry. Initially, $\\textit{carry} = \\text{false}$.\n\nWe traverse the string $s$ from the end toward the beginning:\n\n- If $\\textit{carry}$ is $\\text{true}$, the current bit $c$ needs to be incremented by $1$. If $c$ is $0$, it becomes $1$ after adding $1$, and $\\textit{carry}$ becomes $\\text{false}$; if $c$ is $1$, it becomes $0$ after adding $1$, and $\\textit{carry}$ remains $\\text{true}$.\n- If $c$ is $1$, we need to perform operation $1$, i.e., add $1$, and $\\textit{carry}$ becomes $\\text{true}$.\n- At this point $c$ is $0$, so we need to perform operation $2$, i.e., divide by $2$.\n\nAfter the traversal, if $\\textit{carry}$ is still $\\text{true}$, we need to perform operation $1$ one more time.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1405, "explanations": { "1": "The greedy strategy is to prioritize the selection of characters with the most remaining occurrences. By using a priority queue or sorting, we ensure that the character selected each time is the one with the most remaining occurrences (to avoid having three consecutive identical characters, in some cases, we need to select the character with the second most remaining occurrences)." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1406, "explanations": { "1": "We design a function $dfs(i)$, which represents the maximum score difference that the current player can obtain when playing the game in the range $[i, n)$. If $dfs(0) > 0$, it means that the first player Alice can win; if $dfs(0) < 0$, it means that the second player Bob can win; otherwise, it means that the two players tie.\n\nThe execution logic of the function $dfs(i)$ is as follows:\n\n- If $i \\geq n$, it means that there are no stones to take now, so we can directly return $0$;\n- Otherwise, we enumerate that the current player takes the first $j+1$ piles of stones, where $j \\in \\{0, 1, 2\\}$. Then the score difference that the other player can get in the next round is $dfs(i + j + 1)$, so the score difference that the current player can get is $\\sum_{k=i}^{i+j} stoneValue[k] - dfs(i + j + 1)$. We want to maximize the score difference of the current player, so we can use the $\\max$ function to get the maximum score difference, that is:\n\n$$\ndfs(i) = \\max_{j \\in \\{0, 1, 2\\}} \\left\\{\\sum_{k=i}^{i+j} stoneValue[k] - dfs(i + j + 1)\\right\\}\n$$\n\nTo prevent repeated calculations, we can use memoization search.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of piles of stones." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1407, "explanations": { "1": "We can use a left join to join the `Users` table with the `Rides` table on the condition of user id, and then group by user id to calculate the travel distance for each user. Note that if a user has no travel records, the travel distance is $0$." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1408, "explanations": { "1": "We directly enumerate all strings $words[i]$, and check whether it is a substring of other strings. If it is, we add it to the answer.\n\nThe time complexity is $O(n^3)$, and the space complexity is $O(n)$. Where $n$ is the length of the string array." }, "is_english": true, "time_complexity": "O(n^3)", "space_complexity": "O(n)" }, { "problem_id": 1409, "explanations": { "1": "The problem's data scale is not large, so we can directly simulate it.", "2": "The Binary Indexed Tree (BIT), also known as the Fenwick Tree, efficiently supports the following two operations:\n\n1. **Point Update** `update(x, delta)`: Adds a value `delta` to the element at position `x` in the sequence.\n2. **Prefix Sum Query** `query(x)`: Queries the sum of the sequence over the interval `[1,...,x]`, i.e., the prefix sum at position `x`.\n\nBoth operations have a time complexity of $O(\\log n)$.\n\nThe fundamental functionality of the Binary Indexed Tree is to count the number of elements smaller than a given element `x`. This comparison is abstract and can refer to size, coordinate, mass, etc.\n\nFor example, given the array `a[5] = {2, 5, 3, 4, 1}`, the task is to compute `b[i] = the number of elements to the left of position i that are less than or equal to a[i]`. For this example, `b[5] = {0, 1, 1, 2, 0}`.\n\nThe solution is to traverse the array, first calculating `query(a[i])` for each position, and then updating the Binary Indexed Tree with `update(a[i], 1)`. When the range of numbers is large, discretization is necessary, which involves removing duplicates, sorting, and then assigning an index to each number." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": null }, { "problem_id": 1410, "explanations": { "1": "We can use a hash table to store the corresponding character for each character entity. Then, we traverse the string, and when we encounter a character entity, we replace it with the corresponding character.\n\nThe time complexity is $O(n \\times l)$, and the space complexity is $O(l)$. Here, $n$ is the length of the string, and $l$ is the total length of the character entities.", "2": "" }, "is_english": true, "time_complexity": "O(n \\times l)", "space_complexity": "O(l)" }, { "problem_id": 1411, "explanations": { "1": "We classify all possible states for each row. According to the principle of symmetry, when a row only has $3$ elements, all legal states are classified as: $010$ type, $012$ type.\n\n- When the state is $010$ type: The possible states for the next row are: $101$, $102$, $121$, $201$, $202$. These $5$ states can be summarized as $3$ $010$ types and $2$ $012$ types.\n- When the state is $012$ type: The possible states for the next row are: $101$, $120$, $121$, $201$. These $4$ states can be summarized as $2$ $010$ types and $2$ $012$ types.\n\nIn summary, we can get: $newf0 = 3 \\times f0 + 2 \\times f1$, $newf1 = 2 \\times f0 + 2 \\times f1$.\n\nThe time complexity is $O(n)$, where $n$ is the number of rows in the grid. The space complexity is $O(1)$.", "2": "We notice that the grid only has $3$ columns, so there are at most $3^3=27$ different coloring schemes in a row.\n\nTherefore, we define $f[i][j]$ to represent the number of schemes in the first $i$ rows, where the coloring state of the $i$th row is $j$. The state $f[i][j]$ is transferred from $f[i - 1][k]$, where $k$ is the coloring state of the $i - 1$th row, and $k$ and $j$ meet the requirement of different colors being adjacent. That is:\n\n$$\nf[i][j] = \\sum_{k \\in \\textit{valid}(j)} f[i - 1][k]\n$$\n\nwhere $\\textit{valid}(j)$ represents all legal predecessor states of state $j$.\n\nThe final answer is the sum of $f[n][j]$, where $j$ is any legal state.\n\nWe notice that $f[i][j]$ is only related to $f[i - 1][k]$, so we can use a rolling array to optimize the space complexity.\n\nThe time complexity is $O((m + n) \\times 3^{2m})$, and the space complexity is $O(3^m)$. Here, $m$ and $n$ are the number of rows and columns of the grid, respectively." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1412, "explanations": { "1": "We can use the `RANK()` window function to calculate the ascending rank $rk1$ and descending rank $rk2$ of each student in each exam, and obtain the table $T$.\n\nNext, we can perform an inner join between the table $T$ and the table $Student$, and then group by student ID to obtain the number of times each student has a rank of $1$ in ascending order $cnt1$ and descending order $cnt2$ in all exams. If both $cnt1$ and $cnt2$ are $0$, it means that the student is in the middle of the pack in all exams." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1413, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1414, "explanations": { "1": "We can greedily select the largest Fibonacci number that does not exceed $k$ each time, then subtract this number from $k$ and increment the answer by one. This process is repeated until $k = 0$.\n\nSince we greedily select the largest Fibonacci number that does not exceed $k$ each time, suppose this number is $b$, the previous number is $a$, and the next number is $c$. Subtracting $b$ from $k$ results in a value that is less than $a$, which means that after selecting $b$, we will not select $a$. This is because if we could select $a$, then we could have greedily selected the next Fibonacci number $c$ instead of $b$ earlier, which contradicts our assumption. Therefore, after selecting $b$, we can greedily reduce the Fibonacci number.\n\nThe time complexity is $O(\\log k)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log k)", "space_complexity": "O(1)" }, { "problem_id": 1415, "explanations": { "1": "We use a string $\\textit{s}$ to record the current string, initially an empty string. Then, we design a function $\\text{dfs}$ to generate all happy strings of length $n$.\n\nThe implementation of the function $\\text{dfs}$ is as follows:\n\n1. If the length of the current string is equal to $n$, add the current string to the answer array $\\textit{ans}$ and return;\n2. If the length of the answer array is greater than or equal to $k$, return directly;\n3. Otherwise, we iterate over the character set $\\{a, b, c\\}$. For each character $c$, if the current string is empty or the last character of the current string is not equal to $c$, add the character $c$ to the current string, then recursively call $\\text{dfs}$. After the recursion ends, remove the last character of the current string.\n\nFinally, we check if the length of the answer array is less than $k$. If it is, return an empty string; otherwise, return the $k$-th element of the answer array.\n\nThe time complexity is $O(n \\times 2^n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string.", "2": "We can directly calculate what the $k$-th happy string is, without generating all happy strings.\n\nStarting from the first happy string of length $n$, we can determine what each character position should be.\n\nFor a happy string of length $n$, the first character has $3$ choices, the second character has $2$ choices (cannot be the same as the first), the third character also has $2$ choices (cannot be the same as the second), and so on, until the $n$-th character also has $2$ choices (cannot be the same as the $(n-1)$-th). Therefore, the total number of happy strings of length $n$ is $3 \\times 2^{n-1}$.\n\nIf $k$ is greater than the total number of happy strings of length $n$, we return an empty string directly.\n\nOtherwise, we start from the first character and determine each character's position one by one. For the $i$-th character, we enumerate the character set $\\{a, b, c\\}$. If the last character of the current string is not equal to $c$, we calculate the number of remaining happy strings. If $k$ is less than or equal to that count, we append character $c$ to the current string and move on to the next position; otherwise, we subtract that count from $k$ and continue enumerating the next character.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the string." }, "is_english": true, "time_complexity": "O(n \\times 2^n)", "space_complexity": "O(n)" }, { "problem_id": 1416, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1417, "explanations": { "1": "We classify all characters in string $s$ into two categories: \"digits\" and \"letters\", and put them into arrays $a$ and $b$ respectively.\n\nCompare the lengths of $a$ and $b$. If the length of $a$ is less than $b$, swap $a$ and $b$. Then check the difference in lengths; if it exceeds $1$, return an empty string.\n\nNext, iterate through both arrays simultaneously, appending characters from $a$ and $b$ alternately to the answer. After the iteration, if $a$ is longer than $b$, append the last character of $a$ to the answer.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1418, "explanations": { "1": "We can use a hash table $\\textit{tables}$ to store the dishes ordered at each table, and a set $\\textit{items}$ to store all the dishes.\n\nTraverse $\\textit{orders}$, storing the dishes ordered at each table in $\\textit{tables}$ and $\\textit{items}$.\n\nThen we sort $\\textit{items}$ to get $\\textit{sortedItems}$.\n\nNext, we construct the answer array $\\textit{ans}$. First, add the header row $\\textit{header}$ to $\\textit{ans}$. Then, traverse the sorted $\\textit{tables}$. For each table, use a counter $\\textit{cnt}$ to count the number of each dish, then construct a row $\\textit{row}$ and add it to $\\textit{ans}$.\n\nFinally, return $\\textit{ans}$.\n\nThe time complexity is $O(n + m \\times \\log m + k \\times \\log k + m \\times k)$, and the space complexity is $O(n + m + k)$. Here, $n$ is the length of the array $\\textit{orders}$, while $m$ and $k$ represent the number of dish types and the number of tables, respectively." }, "is_english": true, "time_complexity": "O(n + m \\times \\log m + k \\times \\log k + m \\times k)", "space_complexity": "O(n + m + k)" }, { "problem_id": 1419, "explanations": { "1": "We note that if the string `croakOfFrogs` is composed of several valid `\"croak\"` characters mixed together, its length must be a multiple of $5$. Therefore, if the length of the string is not a multiple of $5$, we can directly return $-1$.\n\nNext, we map the letters `'c'`, `'r'`, `'o'`, `'a'`, `'k'` to indices $0$ to $4$, respectively, and use an array $cnt$ of length $5$ to record the number of occurrences of each letter in the string `croakOfFrogs`, where $cnt[i]$ represents the number of occurrences of the letter at index $i$. Additionally, we define an integer variable $x$ to represent the number of frogs that have not completed their croak, and the minimum number of frogs needed $ans$ is the maximum value of $x$.\n\nWe traverse each letter $c$ in the string `croakOfFrogs`, find the index $i$ corresponding to $c$, and then increment $cnt[i]$ by $1$. Next, depending on the value of $i$, we perform the following operations:\n\n- If $i=0$, then a new frog starts croaking, so we increment $x$ by $1$, and then update $ans = \\max(ans, x)$;\n- Otherwise, if $cnt[i-1]=0$, it means that there is no frog that can make the sound $c$, and the croak cannot be completed, so we return $-1$. Otherwise, we decrement $cnt[i-1]$ by $1$. If $i=4$, it means that a frog has completed a croak, so we decrement $x$ by $1$.\n\nAfter traversing, if $x=0$, it means that all frogs have completed their croaks, and we return $ans$. Otherwise, we return $-1$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(C)$. Where $n$ is the length of the string `croakOfFrogs`, and $C$ is the size of the character set, in this problem $C=26$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(C)" }, { "problem_id": 1420, "explanations": { "1": "假设 $dp[i][c][j]$ 表示长度为 $i$,搜索代价为 $c$,且最大值为 $j$ 的方案数。考虑第 $i$ 个数:\n\n若第 $i$ 个数没有改变搜索代价,说明它不严格大于前 $i-1$ 个数,也就是说,$dp[i][c][j]$ 是从 $dp[i-1][c][j]$ 转移而来,即数组的前 $i-1$ 个数的最大值已经是 $j$,并且第 $i$ 个数没有改变最大值,因此第 $i$ 个数的可选范围是 $[1,..j]$,共有 $j$ 种可选方案。即\n\n$$\ndp[i][c][j]=dp[i-1][c][j] \\times j\n$$\n\n若第 $i$ 个数改变了搜索代价,说明数组前 $i-1$ 个数的最大值小于 $j$,并且第 $i$ 个数恰好为 $j$。此时 $dp[i][c][j]$ 是从所有 $dp[i-1][c-1][j']$ 转移而来,其中 $j' k$, it means the front element is no longer within the sliding window, and we need to remove the front element from the queue;\n- Then, we calculate $f[i] = \\max(0, f[q[0]]) + \\textit{nums}[i]$, which means we add $\\textit{nums}[i]$ to the sliding window to get the maximum subsequence sum;\n- Next, we update the answer $\\textit{ans} = \\max(\\textit{ans}, f[i])$;\n- Finally, we add $i$ to the back of the queue and maintain the monotonicity of the queue. If $f[q[\\textit{back}]] \\leq f[i]$, we need to remove the back element until the queue is empty or $f[q[\\textit{back}]] > f[i]$.\n\nThe final answer is $\\textit{ans}$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1426, "explanations": { "1": "We can use a hash table or array $cnt$ to record the frequency of each number in the array $arr$. Then, we traverse each number $x$ in $cnt$. If $x+1$ also exists in $cnt$, we add $cnt[x]$ to the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $arr$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1427, "explanations": { "1": "We can denote the length of the string $s$ as $n$. Next, we traverse the array $shift$, accumulate to get the final offset $x$, then take $x$ modulo $n$, the final result is to move the first $n - x$ characters of $s$ to the end.\n\nThe time complexity is $O(n + m)$, where $n$ and $m$ are the lengths of the string $s$ and the array $shift$ respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(1)" }, { "problem_id": 1428, "explanations": { "1": "First, we call `BinaryMatrix.dimensions()` to get the number of rows $m$ and columns $n$ of the matrix. Then for each row, we use binary search to find the column number $j$ where the leftmost $1$ is located. The smallest $j$ value that satisfies all rows is the answer. If there is no such column, return $-1$.\n\nThe time complexity is $O(m \\times \\log n)$, where $m$ and $n$ are the number of rows and columns of the matrix, respectively. We need to traverse each row, and use binary search within each row, which has a time complexity of $O(\\log n)$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m \\times \\log n)", "space_complexity": "O(1)" }, { "problem_id": 1429, "explanations": { "1": "我们可以使用哈希表 $cnt$ 统计每个数字出现的次数,使用双端队列 $q$ 按顺序维护出现的数字。\n\n调用 `showFirstUnique` 方法时,判断队列 $q$ 的队头元素是否在哈希表 $cnt$ 中出现的次数是否为 $1$,如果是,则返回队头元素,否则将队头元素弹出,直到队列为空或者队头元素在哈希表 $cnt$ 中出现的次数为 $1$,如果队列为空,则返回 $-1$。\n\n调用 `add` 方法时,将数字加入哈希表 $cnt$ 中,并将数字加入队列 $q$ 中。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $nums$ 的长度。", "2": "" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1430, "explanations": { "1": "根据题目,我们设计一个递归函数 $dfs(root, u)$,表示从当前节点 $root$ 开始,且当前已经遍历到数组的第 $u$ 个元素,是否存在一条从根节点到叶子节点的路径,且路径上的元素与数组中的元素一一对应。那么答案就是 $dfs(root, 0)$。\n\n在递归函数中,如果当前节点为空,或者当前节点的值与数组中的值不相等,那么直接返回 $false$。如果当前节点是叶子节点,且当前节点的值与数组中的值相等,那么返回 $u$ 是否等于数组的长度减 $1$。否则,返回 $dfs(root.left, u + 1)$ 或者 $dfs(root.right, u + 1)$。\n\n时间复杂度 $O(n)$,空间复杂度 $O(\\log n)$。其中 $n$ 是二叉树的节点个数。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(\\log n)" }, { "problem_id": 1431, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1432, "explanations": { "1": "To obtain the maximum difference, we should take the maximum and minimum values, as this yields the largest difference.\n\nTherefore, we first enumerate each digit in $\\textit{nums}$ from high to low. If a digit is not `9`, we replace all occurrences of that digit with `9` to obtain the maximum integer $a$.\n\nNext, we enumerate each digit in $\\textit{nums}$ from high to low again. The first digit cannot be `0`, so if the first digit is not `1`, we replace it with `1`; for non-leading digits that are different from the first digit, we replace them with `0` to obtain the minimum integer $b$.\n\nThe answer is the difference $a - b$.\n\nThe time complexity is $O(\\log \\textit{num})$, and the space complexity is $O(\\log \\textit{num})$, where $\\textit{nums}$ is the given integer." }, "is_english": true, "time_complexity": "O(\\log \\textit{num})", "space_complexity": "O(\\log \\textit{num})" }, { "problem_id": 1433, "explanations": { "1": "将字符串 $s1$, $s2$ 分别进行升序排序。然后同时遍历两个字符串,对应字符进行大小比较。若对于任意 $i∈[0, n),都有 $s1[i] \\le s2[i]$,或者都有 $s1[i] \\ge s2[i]$,则存在一个排列可以打破另一个排列。\n\n时间复杂度 $O(nlogn)$。" }, "is_english": false, "time_complexity": "O(nlogn)", "space_complexity": null }, { "problem_id": 1434, "explanations": { "1": "We notice that $n$ is not greater than $10$, so we consider using DP with state compression to solve this problem.\n\nWe define $f[i][j]$ as the number of ways to assign the first $i$ hats to the people whose state is $j$. Here $j$ is a binary number, which represents a set of people. We have $f[0][0]=1$ at the beginning, and the answer is $f[m][2^n - 1]$, where $m$ is the maximum number of hats and $n$ is the number of people.\n\nConsider $f[i][j]$. If we don't assign the $i$-th hat to anyone, then $f[i][j]=f[i-1][j]$; if we assign the $i$-th hat to the person $k$ who likes it, then $f[i][j]=f[i-1][j \\oplus 2^k]$. Here $\\oplus$ denotes the XOR operation. Therefore, we can get the state transition equation:\n\n$$\nf[i][j]=f[i-1][j]+ \\sum_{k \\in like[i]} f[i-1][j \\oplus 2^k]\n$$\n\nwhere $like[i]$ denotes the set of people who like the $i$-th hat.\n\nThe final answer is $f[m][2^n - 1]$, and the answer may be very large, so we need to take it modulo $10^9 + 7$.\n\nTime complexity $O(m \\times 2^n \\times n)$, space complexity $O(m \\times 2^n)$. Here $m$ is the maximum number of hats, which is no more than $40$ in this problem; and $n$ is the number of people, which is no more than $10$ in this problem." }, "is_english": true, "time_complexity": "O(m \\times 2^n \\times n)", "space_complexity": "O(m \\times 2^n)" }, { "problem_id": 1435, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1436, "explanations": { "1": "According to the problem description, the destination city will not appear in any of the $\\textit{cityA}$. Therefore, we can first traverse the $\\textit{paths}$ and put all $\\textit{cityA}$ into a set $\\textit{s}$. Then, we traverse the $\\textit{paths}$ again to find the $\\textit{cityB}$ that is not in $\\textit{s}$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of $\\textit{paths}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1437, "explanations": { "1": "We can iterate through the array $\\textit{nums}$ and use a variable $j$ to record the index of the previous $1$. When the element at the current position $i$ is $1$, we just need to check if $i - j - 1$ is less than $k$. If it is less than $k$, it means there exists a pair of $1$s with fewer than $k$ zeros between them, so we return $\\text{false}$. Otherwise, we update $j$ to $i$ and continue iterating through the array.\n\nAfter the iteration is complete, we return $\\text{true}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1438, "explanations": { "1": "We can enumerate each position as the right endpoint of the subarray, and find the leftmost left endpoint corresponding to it, such that the difference between the maximum and minimum values in the interval does not exceed $limit$. During the process, we use an ordered set to maintain the maximum and minimum values within the window.\n\nThe time complexity is $O(n \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array `nums`.", "2": "We notice that if a subarray of length $k$ satisfies the condition, then a subarray of length $k' < k$ also satisfies the condition. This shows a monotonicity, therefore, we can use binary search to find the longest subarray that satisfies the condition.\n\nWe define the left boundary of the binary search as $l = 0$, and the right boundary as $r = n$. For each $mid = \\frac{l + r + 1}{2}$, we check whether there exists a subarray of length $mid$ that satisfies the condition. If it exists, we update $l = mid$, otherwise we update $r = mid - 1$. The problem is transformed into whether there exists a subarray of length $mid$ in the array that satisfies the condition, which is actually to find the difference between the maximum and minimum values in the sliding window does not exceed $limit$. We can use two monotonic queues to maintain the maximum and minimum values in the window respectively.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $nums$.", "3": "We can use a deque to maintain the maximum and minimum values within the window. We maintain two deques, one for storing the indices of the maximum values and the other for the minimum values within the window. Define two pointers $l$ and $r$ to point to the left and right boundaries of the window, respectively.\n\nEach time we move the right boundary $r$ to the right, we check if the element corresponding to the tail index of the maximum value deque is less than the current element. If it is, we dequeue the tail element until the element corresponding to the tail of the maximum value deque is not less than the current element. Similarly, we check if the element corresponding to the tail index of the minimum value deque is greater than the current element. If it is, we dequeue the tail element until the element corresponding to the tail of the minimum value deque is not greater than the current element. Then, we enqueue the current element's index.\n\nIf the difference between the elements at the front of the maximum value deque and the minimum value deque is greater than $limit$, then we move the left boundary $l$ to the right. If the element at the front of the maximum value deque is less than $l$, we dequeue the front element of the maximum value deque. Similarly, if the element at the front of the minimum value deque is less than $l$, we dequeue the front element of the minimum value deque.\n\nThe answer is $n - l$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1439, "explanations": { "1": "根据题目描述,我们需要找出前 $m$ 行的所有可能数组中的第 $k$ 个最小数组和。\n\n如果我们能够找出前 $m - 1$ 行的所有可能数组中的前 $k$ 个最小数组和,那么我们可以将第 $m$ 行的每个元素与前 $m - 1$ 行的前 $k$ 个最小数组和相加,将得到的所有结果排序后,取前 $k$ 个最小值,即为前 $m$ 行的所有可能数组中的前 $k$ 个最小值。\n\n因此,我们可以定义一个数组 $pre$,用于存储此前遍历到的行的前 $k$ 个最小数组和,初始时 $pre$ 只有一个元素 $0$。\n\n然后,我们遍历 $mat$ 的每一行 $cur$,将 $cur$ 中的每个元素与 $pre$ 中的每个元素相加,将得到的所有结果排序后,取前 $k$ 个最小值作为新的 $pre$。继续遍历下一行,直到遍历完所有行。\n\n最后返回 $pre$ 中的第 $k$ 个数(下标 $k-1$)即可。\n\n时间复杂度 $O(m \\times n \\times k \\times \\log (n \\times k))$,空间复杂度 $O(n \\times k)$。其中 $m$ 和 $n$ 分别是矩阵的行数和列数。" }, "is_english": false, "time_complexity": "O(m \\times n \\times k \\times \\log (n \\times k))", "space_complexity": "O(n \\times k)" }, { "problem_id": 1440, "explanations": { "1": "We can associate each row in the `Expressions` table with two rows in the `Variables` table using an equi-join, where the conditions for the association are `left_operand = name` and `right_operand = name`. Then, we can use a `CASE` expression to determine the value of the boolean expression. If the `operator` is `=`, we check if the two values are equal. If the `operator` is `>`, we check if the left value is greater than the right value. If the `operator` is `<`, we check if the left value is less than the right value. If the condition is true, the boolean expression evaluates to `true`, otherwise it evaluates to `false`." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1441, "explanations": { "1": "We define a variable $\\textit{cur}$ to represent the current number to be read, initially set to $\\textit{cur} = 1$, and use an array $\\textit{ans}$ to store the answer.\n\nNext, we iterate through each number $x$ in the array $\\textit{target}$:\n\n- If $\\textit{cur} < x$, we add $\\textit{Push}$ and $\\textit{Pop}$ to the answer alternately until $\\textit{cur} = x$;\n- Then we add $\\textit{Push}$ to the answer, representing reading the number $x$;\n- After that, we increment $\\textit{cur}$ and continue to process the next number.\n\nAfter the iteration, we return the answer array.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{target}$. Ignoring the space consumption of the answer array, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1442, "explanations": { "1": "According to the problem description, to find triplets $(i, j, k)$ that satisfy $a = b$, which means $s = a \\oplus b = 0$, we only need to enumerate the left endpoint $i$, and then calculate the prefix XOR sum $s$ of the interval $[i, k]$ with $k$ as the right endpoint. If $s = 0$, then for any $j \\in [i + 1, k]$, the condition $a = b$ is satisfied, meaning $(i, j, k)$ is a valid triplet. There are $k - i$ such triplets, which we can add to our answer.\n\nAfter the enumeration is complete, we return the answer.\n\nThe time complexity is $O(n^2)$, where $n$ is the length of the array $\\textit{arr}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(1)" }, { "problem_id": 1443, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1444, "explanations": { "1": "We can use a 2D prefix sum to quickly calculate the number of apples in each sub-rectangle. Define $s[i][j]$ to represent the number of apples in the sub-rectangle that includes the first $i$ rows and the first $j$ columns. Then $s[i][j]$ can be derived from the number of apples in the three sub-rectangles $s[i-1][j]$, $s[i][j-1]$, and $s[i-1][j-1]$. The specific calculation method is as follows:\n\n$$\ns[i][j] = s[i-1][j] + s[i][j-1] - s[i-1][j-1] + (pizza[i-1][j-1] == 'A')\n$$\n\nHere, $pizza[i-1][j-1]$ represents the character at the $i$-th row and $j$-th column in the rectangle. If it is an apple, it is $1$; otherwise, it is $0$.\n\nNext, we design a function $dfs(i, j, k)$, which represents the number of ways to cut the rectangle $(i, j, m-1, n-1)$ with $k$ cuts to get $k+1$ pieces of pizza. Here, $(i, j)$ and $(m-1, n-1)$ are the coordinates of the top-left and bottom-right corners of the rectangle, respectively. The calculation method of the function $dfs(i, j, k)$ is as follows:\n\n- If $k = 0$, it means no more cuts can be made. We need to check if there are any apples in the rectangle. If there are apples, return $1$; otherwise, return $0$.\n- If $k \\gt 0$, we need to enumerate the position of the last cut. If the last cut is horizontal, we need to enumerate the cutting position $x$, where $i \\lt x \\lt m$. If $s[x][n] - s[i][n] - s[x][j] + s[i][j] \\gt 0$, it means there are apples in the upper piece of pizza, and we add the value of $dfs(x, j, k-1)$ to the answer. If the last cut is vertical, we need to enumerate the cutting position $y$, where $j \\lt y \\lt n$. If $s[m][y] - s[i][y] - s[m][j] + s[i][j] \\gt 0$, it means there are apples in the left piece of pizza, and we add the value of $dfs(i, y, k-1)$ to the answer.\n\nThe final answer is the value of $dfs(0, 0, k-1)$.\n\nTo avoid repeated calculations, we can use memoized search. We use a 3D array $f$ to record the value of $dfs(i, j, k)$. When we need to calculate the value of $dfs(i, j, k)$, if $f[i][j][k]$ is not $-1$, it means we have already calculated it before, and we can directly return $f[i][j][k]$. Otherwise, we calculate the value of $dfs(i, j, k)$ according to the above method and save the result in $f[i][j][k]$.\n\nThe time complexity is $O(m \\times n \\times k \\times (m + n))$, and the space complexity is $O(m \\times n \\times k)$. Here, $m$ and $n$ are the number of rows and columns of the rectangle, respectively.\n\nSimilar problems:\n\n- [2312. Selling Pieces of Wood](https://github.com/doocs/leetcode/blob/main/solution/2300-2399/2312.Selling%20Pieces%20of%20Wood/README_EN.md)" }, "is_english": true, "time_complexity": "O(m \\times n \\times k \\times (m + n))", "space_complexity": "O(m \\times n \\times k)" }, { "problem_id": 1445, "explanations": { "1": "We can group the data by date, and then use the `sum` function to calculate the difference in sales between apples and oranges for each day. If it is an apple, we represent it with a positive number, and if it is an orange, we represent it with a negative number. Finally, we sort the data by date." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1446, "explanations": { "1": "We define a variable $\\textit{t}$ to represent the length of the current consecutive characters, initially $\\textit{t}=1$.\n\nNext, we traverse the string $s$ starting from the second character. If the current character is the same as the previous character, then $\\textit{t} = \\textit{t} + 1$, and update the answer $\\textit{ans} = \\max(\\textit{ans}, \\textit{t})$; otherwise, set $\\textit{t} = 1$.\n\nFinally, return the answer $\\textit{ans}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1447, "explanations": { "1": "我们可以枚举分子 $i$ 和分母 $j$,其中 $1 \\leq i < j \\leq n$,并判断 $i$ 和 $j$ 的最大公约数是否为 $1$,如果是则 $i/j$ 是一个最简分数。\n\n时间复杂度 $O(n^2 \\times \\log n)$,空间复杂度 $O(\\log n)$。其中 $n$ 是给定的参数。" }, "is_english": false, "time_complexity": "O(n^2 \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 1448, "explanations": { "1": "我们设计一个函数 $dfs(root, mx)$,表示从当前节点 $root$ 开始搜索好节点,其中 $mx$ 表示从根节点到当前节点的路径(不包括当前节点)上的最大值。\n\n函数 $dfs(root, mx)$ 的执行逻辑如下:\n\n如果 $root$ 为空,说明搜索结束,直接返回;\n\n否则,我们判断 $root.val$ 与 $mx$ 的大小关系。如果 $mx \\leq root.val$,说明 $root$ 是好节点,答案加一,并且我们需要更新 $mx$ 的值为 $root.val$。\n\n接下来,我们递归调用 $dfs(root.left, mx)$ 和 $dfs(root.right, mx)$。\n\n在主函数中,我们调用 $dfs(root, -10^6)$,其中 $-10^6$ 表示负无穷,因为题目中说明了每个节点权值的范围是 $[-10^4, 10^4]$,所以 $-10^6$ 肯定是一个比所有节点权值都小的值,这样就能保证 $dfs(root, -10^6)$ 一定会把根节点 $root$ 算作好节点。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点数。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1449, "explanations": { "1": "我们定义 $f[i][j]$ 表示使用前 $i$ 个数位,花费恰好为 $j$ 的情况下,能够得到的最大位数。初始时,$f[0][0]=0$,其余为 $-\\infty$。\n\n考虑 $f[i][j]$,第 $i$ 个数的花费为 $c = cost[i-1]$,如果 $j \\lt c$,那么我们无法选取第 $i$ 个数位,此时有 $f[i][j]=f[i-1][j]$;否则我们可以选取第 $i$ 个数位,此时有 $f[i][j]=f[i][j-c]+1$。\n\n如果 $f[9][target] \\lt 0$,那么说明无法得到满足要求的整数,返回 \"0\" 即可。\n\n否则,我们需要从 $f[9][target]$ 开始,倒推出每一位的数字。我们可以使用一个数组 $g[i][j]$ 记录 $f[i][j]$ 的上一个状态,从而倒推出每一位的数字。\n\n具体地,在状态转移时,如果 $j \\lt c$,或者 $f[i][j-c]+1 \\lt f[i-1][j]$,那么我们不选取第 $i$ 个数位,此时有 $g[i][j]=j$;否则我们选取第 $i$ 个数位,此时有 $g[i][j]=j-c$。\n\n最后,我们定义 $i = 9$, $j = target$,从 $g[i][j]$ 开始不断地倒推,如果 $g[i][j]=j$,说明数字 $i$ 没有被选取,我们令 $i = i - 1$;否则说明数字 $i$ 被选取,我们令 $j = g[i][j]$,并将数字 $i$ 加入答案中。重复上述操作,直到 $i = 0$。\n\n时间复杂度 $O(m \\times n)$,空间复杂度 $O(m \\times n)$,其中 $m$ 和 $n$ 分别为数组 $cost$ 和 $target$ 的长度。" }, "is_english": false, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 1450, "explanations": { "1": "We can directly traverse the two arrays. For each student, we check if $\\textit{queryTime}$ is within their homework time interval. If it is, we increment the answer by one.\n\nAfter the traversal, we return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the number of students. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1451, "explanations": { "1": "将 `text` 按空格切分为字符串数组 `words`,并将 `words[0]` 转为小写。然后对 `words` 进行排序(这里需要确保长度相同的情况下,相对顺序保持不变,因此是一种稳定排序)。\n\n排完序后,对 `words[0]` 首字母转为大写。最后将 `words` 所有字符串用空格拼接成一个字符串。\n\n时间复杂度 $O(n\\log n)$。" }, "is_english": false, "time_complexity": "O(n\\log n)", "space_complexity": null }, { "problem_id": 1452, "explanations": { "1": "We can map each company to a unique integer. Then, for each person, we convert their favorite companies into a set of integers. Finally, we check if the favorite companies of one person are a subset of another person's favorite companies.\n\nThe time complexity is $(n \\times m \\times k + n^2 \\times m)$, and the space complexity is $O(n \\times m)$. Here, $n$ and $m$ are the lengths of `favoriteCompanies` and the average length of each company's list, respectively, and $k$ is the average length of each company." }, "is_english": true, "time_complexity": "O(n \\times m)", "space_complexity": "O(n \\times m)" }, { "problem_id": 1453, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1454, "explanations": { "1": "First, we join the `Logins` table and the `Accounts` table, and remove duplicates to get the temporary table `T`.\n\nThen, we use the window function `ROW_NUMBER()` to calculate the base login date `g` for each user `id`. If a user logs in for 5 consecutive days, their `g` values are the same.\n\nFinally, we group by `id` and `g` to count the number of logins for each user. If the number of logins is greater than or equal to 5, then the user is considered active." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1455, "explanations": { "1": "We split $\\textit{sentence}$ by spaces into $\\textit{words}$, then iterate through $\\textit{words}$ to check if $\\textit{words}[i]$ is a prefix of $\\textit{searchWord}$. If it is, we return $i+1$. If the iteration completes and no words satisfy the condition, we return $-1$.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m)$. Here, $m$ and $n$ are the lengths of $\\textit{sentence}$ and $\\textit{searchWord}$, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m)" }, { "problem_id": 1456, "explanations": { "1": "First, we count the number of vowels in the first $k$ characters, denoted as $cnt$, and initialize the answer $ans$ as $cnt$.\n\nThen we start traversing the string from $k$. For each iteration, we add the current character to the window. If the current character is a vowel, we increment $cnt$. We remove the first character from the window. If the removed character is a vowel, we decrement $cnt$. Then, we update the answer $ans = \\max(ans, cnt)$.\n\nAfter the traversal, we return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1457, "explanations": { "1": "A path is a pseudo-palindromic path if and only if the number of nodes with odd occurrences in the path is $0$ or $1$.\n\nSince the range of the binary tree node values is from $1$ to $9$, for each path from root to leaf, we can use a $10$-bit binary number $mask$ to represent the occurrence status of the node values in the current path. The $i$th bit of $mask$ is $1$ if the node value $i$ appears an odd number of times in the current path, and $0$ if it appears an even number of times. Therefore, a path is a pseudo-palindromic path if and only if $mask \\&(mask - 1) = 0$, where $\\&$ represents the bitwise AND operation.\n\nBased on the above analysis, we can use the depth-first search method to calculate the number of paths. We define a function $dfs(root, mask)$, which represents the number of pseudo-palindromic paths starting from the current $root$ node and with the current state $mask$. The answer is $dfs(root, 0)$.\n\nThe execution logic of the function $dfs(root, mask)$ is as follows:\n\nIf $root$ is null, return $0$;\n\nOtherwise, let $mask = mask \\oplus 2^{root.val}$, where $\\oplus$ represents the bitwise XOR operation.\n\nIf $root$ is a leaf node, return $1$ if $mask \\&(mask - 1) = 0$, otherwise return $0$;\n\nIf $root$ is not a leaf node, return $dfs(root.left, mask) + dfs(root.right, mask)$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1458, "explanations": { "1": "We define $f[i][j]$ to represent the maximum dot product of two subsequences formed by the first $i$ elements of $\\textit{nums1}$ and the first $j$ elements of $\\textit{nums2}$. Initially, $f[i][j] = -\\infty$.\n\nFor $f[i][j]$, we have the following cases:\n\n1. Do not select $\\textit{nums1}[i-1]$ or do not select $\\textit{nums2}[j-1]$, i.e., $f[i][j] = \\max(f[i-1][j], f[i][j-1])$;\n2. Select $\\textit{nums1}[i-1]$ and $\\textit{nums2}[j-1]$, i.e., $f[i][j] = \\max(f[i][j], \\max(0, f[i-1][j-1]) + \\textit{nums1}[i-1] \\times \\textit{nums2}[j-1])$.\n\nThe final answer is $f[m][n]$.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the lengths of the arrays $\\textit{nums1}$ and $\\textit{nums2}$, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 1459, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1460, "explanations": { "1": "If two arrays are equal after sorting, then they can be made equal by reversing sub-arrays.\n\nTherefore, we only need to sort the two arrays and then check if the sorted arrays are equal.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$, where $n$ is the length of the array $arr$.", "2": "We note that the range of the array elements given in the problem is $1 \\sim 1000$. Therefore, we can use two arrays `cnt1` and `cnt2` of length $1001$ to record the number of times each element appears in the arrays `target` and `arr` respectively. Finally, we just need to check if the two arrays are equal.\n\nWe can also use only one array `cnt`. We traverse the arrays `target` and `arr`. For `target[i]`, we increment `cnt[target[i]]`, and for `arr[i]`, we decrement `cnt[arr[i]]`. In the end, we check if all elements in the array `cnt` are $0$.\n\nThe time complexity is $O(n + M)$, and the space complexity is $O(M)$. Here, $n$ is the length of the array `arr`, and $M$ is the range of the array elements. In this problem, $M = 1001$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 1461, "explanations": { "1": "First, for a string $s$ of length $n$, the number of substrings of length $k$ is $n - k + 1$. If $n - k + 1 < 2^k$, then there must exist a binary string of length $k$ that is not a substring of $s$, so we return `false`.\n\nNext, we traverse the string $s$ and store all substrings of length $k$ in a set $ss$. Finally, we check if the size of the set $ss$ is equal to $2^k$.\n\nThe time complexity is $O(n \\times k)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $s$.", "2": "In Solution 1, we stored all distinct substrings of length $k$, and processing each substring requires $O(k)$ time. We can instead use a sliding window, where each time we add the latest character, we remove the leftmost character from the window. During this process, we use an integer $x$ to store the substring.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n \\times k)", "space_complexity": "O(n)" }, { "problem_id": 1462, "explanations": { "1": "We create a 2D array $f$, where $f[i][j]$ indicates whether node $i$ can reach node $j$.\n\nNext, we iterate through the prerequisites array $prerequisites$. For each item $[a, b]$ in it, we set $f[a][b]$ to $true$.\n\nThen, we use Floyd's algorithm to compute the reachability between all pairs of nodes.\n\nSpecifically, we use three nested loops: first enumerating the intermediate node $k$, then the starting node $i$, and finally the ending node $j$. For each iteration, if node $i$ can reach node $k$ and node $k$ can reach node $j$, then node $i$ can also reach node $j$, and we set $f[i][j]$ to $true$.\n\nAfter computing the reachability between all pairs of nodes, for each query $[a, b]$, we can directly return $f[a][b]$.\n\nThe time complexity is $O(n^3)$, and the space complexity is $O(n^2)$, where $n$ is the number of nodes.", "2": "Similar to Solution 1, we create a 2D array $f$, where $f[i][j]$ indicates whether node $i$ can reach node $j$. Additionally, we create an adjacency list $g$, where $g[i]$ represents all successor nodes of node $i$, and an array $indeg$, where $indeg[i]$ represents the in-degree of node $i$.\n\nNext, we iterate through the prerequisites array $prerequisites$. For each item $[a, b]$ in it, we update the adjacency list $g$ and the in-degree array $indeg$.\n\nThen, we use topological sorting to compute the reachability between all pairs of nodes.\n\nWe define a queue $q$, initially adding all nodes with an in-degree of $0$ to the queue. Then, we continuously perform the following operations: remove the front node $i$ from the queue, then iterate through all nodes $j$ in $g[i]$, setting $f[i][j]$ to $true$. Next, we enumerate node $h$, and if $f[h][i]$ is $true$, we also set $f[h][j]$ to $true$. After this, we decrease the in-degree of $j$ by $1$. If the in-degree of $j$ becomes $0$, we add $j$ to the queue.\n\nAfter computing the reachability between all pairs of nodes, for each query $[a, b]$, we can directly return $f[a][b]$.\n\nThe time complexity is $O(n^3)$, and the space complexity is $O(n^2)$, where $n$ is the number of nodes." }, "is_english": true, "time_complexity": "O(n^3)", "space_complexity": "O(n^2)" }, { "problem_id": 1463, "explanations": { "1": "We define $f[i][j_1][j_2]$ as the maximum number of cherries that can be picked when the two robots are at positions $j_1$ and $j_2$ in the $i$-th row. Initially, $f[0][0][n-1] = grid[0][0] + grid[0][n-1]$, and the other values are $-1$. The answer is $\\max_{0 \\leq j_1, j_2 < n} f[m-1][j_1][j_2]$.\n\nConsider $f[i][j_1][j_2]$. If $j_1 \\neq j_2$, then the number of cherries that the robots can pick in the $i$-th row is $grid[i][j_1] + grid[i][j_2]$. If $j_1 = j_2$, then the number of cherries that the robots can pick in the $i$-th row is $grid[i][j_1]$. We can enumerate the previous state of the two robots $f[i-1][y1][y2]$, where $y_1, y_2$ are the positions of the two robots in the $(i-1)$-th row, then $y_1 \\in \\{j_1-1, j_1, j_1+1\\}$ and $y_2 \\in \\{j_2-1, j_2, j_2+1\\}$. The state transition equation is as follows:\n\n$$\nf[i][j_1][j_2] = \\max_{y_1 \\in \\{j_1-1, j_1, j_1+1\\}, y_2 \\in \\{j_2-1, j_2, j_2+1\\}} f[i-1][y_1][y_2] + \\begin{cases} grid[i][j_1] + grid[i][j_2], & j_1 \\neq j_2 \\\\ grid[i][j_1], & j_1 = j_2 \\end{cases}\n$$\n\nWhere $f[i-1][y_1][y_2]$ is ignored when it is $-1$.\n\nThe final answer is $\\max_{0 \\leq j_1, j_2 < n} f[m-1][j_1][j_2]$.\n\nThe time complexity is $O(m \\times n^2)$, and the space complexity is $O(m \\times n^2)$. Where $m$ and $n$ are the number of rows and columns of the grid, respectively.", "2": "Notice that the calculation of $f[i][j_1][j_2]$ is only related to $f[i-1][y_1][y_2]$. Therefore, we can use a rolling array to optimize the space complexity. After optimizing the space complexity, the time complexity is $O(n^2)$." }, "is_english": true, "time_complexity": "O(m \\times n^2)", "space_complexity": "O(m \\times n^2)" }, { "problem_id": 1464, "explanations": { "1": "双重循环,枚举所有的下标对,求出 $(nums[i]-1) \\times (nums[j]-1)$ 的最大值。其中 $i \\neq j$。\n\n时间复杂度 $O(n^2)$。", "2": "对 $nums$ 进行排序,取最后两个元素,计算乘积 $(nums[n-1]-1) \\times (nums[n-2]-1)$ 即可。\n\n时间复杂度 $O(nlogn)$。", "3": "遍历 $nums$,维护最大值 $a$ 和次大值 $b$。遍历结束,返回 $(a-1) \\times (b-1)$。" }, "is_english": false, "time_complexity": "O(n^2)", "space_complexity": null }, { "problem_id": 1465, "explanations": { "1": "We first sort `horizontalCuts` and `verticalCuts` separately, and then traverse both arrays to calculate the maximum difference between adjacent elements. We denote these maximum differences as $x$ and $y$, respectively. Finally, we return $x \\times y$.\n\nNote that we need to consider the boundary cases, i.e., the first and last elements of `horizontalCuts` and `verticalCuts`.\n\nThe time complexity is $O(m\\log m + n\\log n)$, where $m$ and $n$ are the lengths of `horizontalCuts` and `verticalCuts`, respectively. The space complexity is $O(\\log m + \\log n)$." }, "is_english": true, "time_complexity": "O(m\\log m + n\\log n)", "space_complexity": "O(\\log m + \\log n)" }, { "problem_id": 1466, "explanations": { "1": "The route map given in the problem has $n$ nodes and $n-1$ edges. If we ignore the direction of the edges, then these $n$ nodes form a tree. The problem requires us to change the direction of some edges so that each node can reach node $0$.\n\nWe might as well consider starting from node $0$ and reaching all other nodes. The direction is opposite to the problem description, which means that when we build the graph, for the directed edge $[a, b]$, we should regard it as the directed edge $[b, a]$. That is to say, if it is from $a$ to $b$, we need to change the direction once; if it is from $b$ to $a$, no direction change is needed.\n\nNext, we only need to start from node $0$, search all other nodes, and during the process, if we encounter an edge that needs to change direction, we accumulate the number of direction changes once.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the problem.", "2": "We can use the Breadth-First Search (BFS) method, starting from node $0$, to search all other nodes. During the process, if we encounter an edge that requires a change of direction, we increment the count of direction changes.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in the problem." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1467, "explanations": { "1": "我们知道 $2n$ 个球,平均分到两个盒子中,总共有 $C_{2n}^n$ 种分法。接下来,我们可以求出每种分法中,两个盒子中球的颜色数相同的情况数。最后,将两者相除即可。\n\n我们可以预处理出组合数 $C_{n}^m$,然后使用记忆化搜索求解。\n\n设计一个函数 $dfs(i, j, diff)$,表示当前从第 $i$ 种球开始,第一个盒子剩余可放置 $j$ 个球,两个盒子中球的颜色数的差为 $diff$ 的方案数。\n\n函数 $dfs(i, j, diff)$ 的执行逻辑如下:\n\n- 如果 $i \\geq k$,表示所有球都已经放完,如果 $j = 0$ 且 $diff = 0$,表示两个盒子中球的颜色数相同,返回 $1$,否则返回 $0$;\n- 如果 $j < 0$,表示第一个盒子中球的数量超过了 $n$,返回 $0$;\n- 如果 $f[i][j][diff]$ 不为 $-1$,表示已经计算过,直接返回 $f[i][j][diff]$;\n- 否则,枚举第 $i$ 种球放入第一个盒子中的数量 $x$,则第 $i$ 种球放入第二个盒子中的数量为 $balls[i] - x$,两个盒子中球的颜色数的变化量为 $y$。如果所有球都放入第一个盒子中,那么 $y = 1$;如果所有球都放入第二个盒子中,那么 $y = -1$;否则 $y = 0$。然后,递归计算 $dfs(i + 1, j - x, diff + y)$,并将结果与 $C_{balls[i]}^x$ 相乘,累加到答案中。最后,将答案存入 $f[i][j][diff]$ 中,并返回答案。\n\n时间复杂度 $O(n^2 \\times k^2)$,空间复杂度 $O(n \\times k^2)$。其中 $n$ 和 $k$ 分别是球的总数和颜色的种数。" }, "is_english": false, "time_complexity": "O(n^2 \\times k^2)", "space_complexity": "O(n \\times k^2)" }, { "problem_id": 1468, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1469, "explanations": { "1": "We can use Depth-First Search (DFS) to traverse the entire tree. We design a function $\\textit{dfs}$, which traverses each node in the tree. If the current node is a lone child, we add its value to the answer array. The execution process of the function $\\textit{dfs}$ is as follows:\n\n1. If the current node is null, or the current node is a leaf node (i.e., both the left and right children of the current node are null), then return directly.\n2. If the left child of the current node is null, then the right child of the current node is a lone child, and we add its value to the answer array.\n3. If the right child of the current node is null, then the left child of the current node is a lone child, and we add its value to the answer array.\n4. Recursively traverse the left and right children of the current node.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1470, "explanations": { "1": "We traverse the indices $i$ in the range $[0, n)$. Each time, we take $\\textit{nums}[i]$ and $\\textit{nums}[i+n]$ and place them sequentially into the answer array.\n\nAfter the traversal is complete, we return the answer array.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1471, "explanations": { "1": "We first sort the array $\\textit{arr}$ and then find the median $m$ of the array.\n\nNext, we sort the array according to the rules described in the problem, and finally return the first $k$ elements of the array.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{arr}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1472, "explanations": { "1": "We can use two stacks, $\\textit{stk1}$ and $\\textit{stk2}$, to store the back and forward pages, respectively. Initially, $\\textit{stk1}$ contains the $\\textit{homepage}$, and $\\textit{stk2}$ is empty.\n\nWhen calling $\\text{visit}(url)$, we add $\\textit{url}$ to $\\textit{stk1}$ and clear $\\textit{stk2}$. The time complexity is $O(1)$.\n\nWhen calling $\\text{back}(steps)$, we pop the top element from $\\textit{stk1}$ and push it to $\\textit{stk2}$. We repeat this operation $steps$ times until the length of $\\textit{stk1}$ is $1$ or $steps$ is $0$. Finally, we return the top element of $\\textit{stk1}$. The time complexity is $O(\\textit{steps})$.\n\nWhen calling $\\text{forward}(steps)$, we pop the top element from $\\textit{stk2}$ and push it to $\\textit{stk1}$. We repeat this operation $steps$ times until $\\textit{stk2}$ is empty or $steps$ is $0$. Finally, we return the top element of $\\textit{stk1}$. The time complexity is $O(\\textit{steps})$.\n\nThe space complexity is $O(n)$, where $n$ is the length of the browsing history." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(n)" }, { "problem_id": 1473, "explanations": { "1": "We define $f[i][j][k]$ to represent the minimum cost to paint houses from index $0$ to $i$, with the last house painted in color $j$, and exactly forming $k$ blocks. The answer is $f[m-1][j][\\textit{target}]$, where $j$ ranges from $1$ to $n$. Initially, we check if the house at index $0$ is already painted. If it is not painted, then $f[0][j][1] = \\textit{cost}[0][j - 1]$, where $j \\in [1,..n]$. If it is already painted, then $f[0][\\textit{houses}[0]][1] = 0$. All other values of $f[i][j][k]$ are initialized to $\\infty$.\n\nNext, we start iterating from index $i=1$. For each $i$, we check if the house at index $i$ is already painted:\n\nIf it is not painted, we can paint the house at index $i$ with color $j$. We enumerate the number of blocks $k$, where $k \\in [1,..\\min(\\textit{target}, i + 1)]$, and enumerate the color of the previous house $j_0$, where $j_0 \\in [1,..n]$. Then we can derive the state transition equation:\n\n$$\nf[i][j][k] = \\min_{j_0 \\in [1,..n]} \\{ f[i - 1][j_0][k - (j \\neq j_0)] + \\textit{cost}[i][j - 1] \\}\n$$\n\nIf it is already painted, we can paint the house at index $i$ with color $j$. We enumerate the number of blocks $k$, where $k \\in [1,..\\min(\\textit{target}, i + 1)]$, and enumerate the color of the previous house $j_0$, where $j_0 \\in [1,..n]$. Then we can derive the state transition equation:\n\n$$\nf[i][j][k] = \\min_{j_0 \\in [1,..n]} \\{ f[i - 1][j_0][k - (j \\neq j_0)] \\}\n$$\n\nFinally, we return $f[m - 1][j][\\textit{target}]$, where $j \\in [1,..n]$. If all values of $f[m - 1][j][\\textit{target}]$ are $\\infty$, then return $-1$.\n\nThe time complexity is $O(m \\times n^2 \\times \\textit{target})$, and the space complexity is $O(m \\times n \\times \\textit{target})$. Here, $m$, $n$, and $\\textit{target}$ represent the number of houses, the number of colors, and the number of blocks, respectively." }, "is_english": true, "time_complexity": "O(m \\times n^2 \\times \\textit{target})", "space_complexity": "O(m \\times n \\times \\textit{target})" }, { "problem_id": 1474, "explanations": { "1": "We can simulate the entire deletion process. First, use a pointer $\\textit{pre}$ to point to the head of the linked list, then traverse the linked list, moving $m - 1$ steps. If $\\textit{pre}$ is null, it means the number of nodes from the current node is less than $m$, so we directly return the head. Otherwise, use a pointer $\\textit{cur}$ to point to $\\textit{pre}$, then move $n$ steps. If $\\textit{cur}$ is null, it means the number of nodes from $\\textit{pre}$ is less than $m + n$, so we directly set the $\\textit{next}$ of $\\textit{pre}$ to null. Otherwise, set the $\\textit{next}$ of $\\textit{pre}$ to the $\\textit{next}$ of $\\textit{cur}$, then move $\\textit{pre}$ to its $\\textit{next}$. Continue traversing the linked list until $\\textit{pre}$ is null, then return the head.\n\nThe time complexity is $O(n)$, where $n$ is the number of nodes in the linked list. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1475, "explanations": { "1": "The problem is essentially to find the first element on the right side that is smaller than each element. We can use a monotonic stack to solve this.\n\nWe traverse the array $\\textit{prices}$ in reverse order, using the monotonic stack to find the nearest smaller element on the left side of the current element, and then calculate the discount.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{prices}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1476, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1477, "explanations": { "1": "We can use a hash table $d$ to record the most recent position where each prefix sum appears, with the initial value $d[0]=0$.\n\nDefine $f[i]$ as the minimum length of a subarray with sum equal to $target$ among the first $i$ elements. Initially, $f[0]=\\infty$.\n\nIterate through the array $\\textit{arr}$. For the current position $i$, calculate the prefix sum $s$. If $s - \\textit{target}$ exists in the hash table, let $j = d[s - \\textit{target}]$, then $f[i] = \\min(f[i], i - j)$, and the answer is $ans = \\min(ans, f[j] + i - j)$. Continue to the next position.\n\nFinally, if the answer is greater than the array length, return $-1$; otherwise, return the answer.\n\nThe complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": null, "space_complexity": "O(n)" }, { "problem_id": 1478, "explanations": { "1": "We define $f[i][j]$ to represent the minimum total distance between the houses and their nearest mailbox, when placing $j$ mailboxes among the first $i+1$ houses. Initially, $f[i][j] = \\infty$, and the final answer will be $f[n-1][k]$.\n\nWe can iterate over the last house $p$ controlled by the $j-1$-th mailbox, i.e., $0 \\leq p \\leq i-1$. The $j$-th mailbox will control the houses in the range $[p+1, \\dots, i]$. Let $g[i][j]$ denote the minimum total distance when placing a mailbox for the houses in the range $[i, \\dots, j]$. The state transition equation is:\n\n$$\nf[i][j] = \\min_{0 \\leq p \\leq i-1} \\{f[p][j-1] + g[p+1][i]\\}\n$$\n\nwhere $g[i][j]$ is computed as follows:\n\n$$\ng[i][j] = g[i + 1][j - 1] + \\textit{houses}[j] - \\textit{houses}[i]\n$$\n\nThe time complexity is $O(n^2 \\times k)$, and the space complexity is $O(n^2)$, where $n$ is the number of houses." }, "is_english": true, "time_complexity": "O(n^2 \\times k)", "space_complexity": "O(n^2)" }, { "problem_id": 1479, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1480, "explanations": { "1": "We directly traverse the array. For the current element $nums[i]$, we add it with the prefix sum $nums[i-1]$ to get the prefix sum $nums[i]$ of the current element.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1481, "explanations": { "1": "We use the hash table $cnt$ to count the number of times each integer in the array $arr$ appears, and then sort the values in $cnt$ in ascending order, and record them in the array $nums$.\n\nNext, we traverse the array $nums$. For the current value that we traverse to $nums[i]$, we subtract $k$ by $nums[i]$. If $k \\lt 0$, it means that we have removed $k$ elements, and the minimum number of different integers in the array is the length of $nums$ minus the index $i$ that we traverse to at the current time. Return directly.\n\nIf we traverse to the end, it means that we have removed all the elements, and the minimum number of different integers in the array is $0$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $arr$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1482, "explanations": { "1": "According to the problem description, if a day $t$ can satisfy making $m$ bouquets, then for any $t' > t$, it can also satisfy making $m$ bouquets. Therefore, we can use binary search to find the minimum day that satisfies making $m$ bouquets.\n\nLet $mx$ be the maximum blooming day in the garden. Next, we define the left boundary of the binary search as $l = 1$ and the right boundary as $r = mx + 1$.\n\nThen, we perform binary search. For each middle value $\\textit{mid} = \\frac{l + r}{2}$, we check if it is possible to make $m$ bouquets. If it is possible, we update the right boundary $r$ to $\\textit{mid}$; otherwise, we update the left boundary $l$ to $\\textit{mid} + 1$.\n\nFinally, when $l = r$, the binary search ends. At this point, if $l > mx$, it means it is not possible to make $m$ bouquets, and we return $-1$; otherwise, we return $l$.\n\nTherefore, the problem is reduced to checking if a day $\\textit{days}$ can make $m$ bouquets.\n\nWe can use a function $\\text{check}(\\textit{days})$ to determine if it is possible to make $m$ bouquets. Specifically, we traverse each flower in the garden from left to right. If the blooming day of the current flower is less than or equal to $\\textit{days}$, we add the current flower to the current bouquet; otherwise, we clear the current bouquet. When the number of flowers in the current bouquet equals $k$, we increment the bouquet count and clear the current bouquet. Finally, we check if the bouquet count is greater than or equal to $m$. If it is, it means it is possible to make $m$ bouquets; otherwise, it is not possible.\n\nThe time complexity is $O(n \\times \\log M)$, where $n$ and $M$ are the number of flowers in the garden and the maximum blooming day, respectively. In this problem, $M \\leq 10^9$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(1)" }, { "problem_id": 1483, "explanations": { "1": "The problem asks us to find the $k$-th ancestor node of a node $node$. If we solve it by brute force, we need to traverse upwards from $node$ for $k$ times, which has a time complexity of $O(k)$ and will obviously exceed the time limit.\n\nWe can use dynamic programming combined with the idea of binary lifting to handle this.\n\nWe define $p[i][j]$ as the $2^j$-th ancestor node of node $i$, i.e., the node reached by moving $2^j$ steps upwards from node $i$. Then we can get the state transition equation:\n\n$$\np[i][j] = p[p[i][j-1]][j-1]\n$$\n\nThat is, to find the $2^j$-th ancestor node of node $i$, we can first find the $2^{j-1}$-th ancestor node of node $i$, and then find the $2^{j-1}$-th ancestor node of this node. Therefore, we need to find the ancestor node of each node at a distance of $2^j$, until we reach the maximum height of the tree.\n\nFor each query later, we can decompose $k$ into its binary representation, and then according to the positions of $1$ in the binary, we accumulate the queries upwards, and finally get the $k$-th ancestor node of node $node$.\n\nIn terms of time complexity, the initialization is $O(n \\times \\log n)$, and the query is $O(\\log n)$. The space complexity is $O(n \\times \\log n)$, where $n$ is the number of nodes in the tree.\n\nSimilar problems:\n\n- [2836. Maximize Value of Function in a Ball Passing Game](https://github.com/doocs/leetcode/blob/main/solution/2800-2899/2836.Maximize%20Value%20of%20Function%20in%20a%20Ball%20Passing%20Game/README_EN.md)" }, "is_english": true, "time_complexity": "O(k)", "space_complexity": "O(n \\times \\log n)" }, { "problem_id": 1484, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1485, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1486, "explanations": { "1": "We can directly simulate to calculate the XOR result of all elements in the array.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1487, "explanations": { "1": "We can use a hash table $d$ to record the minimum available index for each folder name, where $d[name] = k$ means the minimum available index for the folder $name$ is $k$. Initially, $d$ is empty since there are no folders.\n\nNext, we iterate through the folder names array. For each file name $name$:\n\n- If $name$ is already in $d$, it means the folder $name$ already exists, and we need to find a new folder name. We can keep trying $name(k)$, where $k$ starts from $d[name]$, until we find a folder name $name(k)$ that does not exist in $d$. We add $name(k)$ to $d$, update $d[name]$ to $k + 1$, and then update $name$ to $name(k)$.\n- If $name$ is not in $d$, we can directly add $name$ to $d$ and set $d[name]$ to $1$.\n- Then, we add $name$ to the answer array and continue to the next file name.\n\nAfter traversing all file names, we obtain the answer array.\n\n> In the code implementation below, we directly modify the $names$ array without using an extra answer array.\n\nThe complexity is $O(L)$, and the space complexity is $O(L)$, where $L$ is the sum of the lengths of all file names in the $names$ array." }, "is_english": true, "time_complexity": null, "space_complexity": "O(L)" }, { "problem_id": 1488, "explanations": { "1": "We store all sunny days in the $sunny$ array or a sorted set, and use the hash table $rainy$ to record the last rainy day for each lake. We initialize the answer array $ans$ with each element set to $-1$.\n\nNext, we traverse the $rains$ array. For each rainy day $i$, if $rainy[rains[i]]$ exists, it means that the lake has rained before, so we need to find the first date in the $sunny$ array that is greater than $rainy[rains[i]]$, and replace it with the rainy day. Otherwise, it means that the flood cannot be prevented, and we return an empty array. For each non-rainy day $i$, we store $i$ in the $sunny$ array and set $ans[i]$ to $1$.\n\nAfter the traversal, we return the answer array.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the $rains$ array." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1489, "explanations": { "1": "先利用 Kruskal 算法,得出最小生成树的权值 v。然后依次枚举每条边,按上面的方法,判断是否是关键边;如果不是关键边,再判断是否是伪关键边。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1490, "explanations": { "1": "我们可以用递归的方法来实现 N 叉树的深拷贝。\n\n对于当前节点,如果为空,则返回空;否则,创建一个新节点,其值为当前节点的值,然后对当前节点的每个子节点递归调用该函数,将返回值作为新节点的子节点。最后返回新节点即可。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为 N 叉树的节点个数。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1491, "explanations": { "1": "Simulate according to the problem's requirements.\n\nTraverse the array, find the maximum and minimum values, and accumulate the sum. Then calculate the average value after removing the maximum and minimum values.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array `salary`. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1492, "explanations": { "1": "A \"factor\" is a number that can divide another number. Therefore, we only need to enumerate from $1$ to $n$, find all numbers that can divide $n$, and then return the $k$-th one.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$.", "2": "We can observe that if $n$ has a factor $x$, then $n$ must also have a factor $n/x$.\n\nTherefore, we first need to enumerate $[1,2,...\\left \\lfloor \\sqrt{n} \\right \\rfloor]$, find all numbers that can divide $n$. If we find the $k$-th factor, then we can return it directly. If we do not find the $k$-th factor, then we need to enumerate $[\\left \\lfloor \\sqrt{n} \\right \\rfloor ,..1]$ in reverse order, and find the $k$-th factor.\n\nThe time complexity is $O(\\sqrt{n})$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1493, "explanations": { "1": "We can enumerate each position $i$ to be deleted, then calculate the number of consecutive 1s on the left and right, and finally take the maximum value.\n\nSpecifically, we use two arrays $left$ and $right$ of length $n+1$, where $left[i]$ represents the number of consecutive 1s ending with $nums[i-1]$, and $right[i]$ represents the number of consecutive 1s starting with $nums[i]$.\n\nThe final answer is $\\max_{0 \\leq i < n} \\{left[i] + right[i+1]\\}$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $nums$.", "2": "The problem is actually asking us to find the longest subarray that contains at most one $0$. The remaining length after deleting one element from this subarray is the answer.\n\nTherefore, we can use two pointers $j$ and $i$ to point to the left and right boundaries of the subarray, initially $j = 0$, $i = 0$. In addition, we use a variable $cnt$ to record the number of $0$s in the subarray.\n\nNext, we move the right pointer $i$. If $nums[i] = 0$, then $cnt$ is incremented by $1$. When $cnt > 1$, we need to move the left pointer $j$ until $cnt \\leq 1$. Then, we update the answer, i.e., $ans = \\max(ans, i - j)$. Continue to move the right pointer $i$ until $i$ reaches the end of the array.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$.", "3": "In Solution 2, we move the left pointer in a loop until $cnt \\leq 1$. Since the problem asks for the longest subarray, it means we don't need to reduce the length of the subarray. Therefore, if $\\textit{cnt} \\gt 1$, we only move the left pointer once, and the right pointer continues to move to the right. This ensures that the length of the subarray does not decrease.\n\nFinally, the answer we return is $n - l - 1$, where $l$ is the position of the left pointer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1494, "explanations": { "1": "我们用数组 $d[i]$ 表示课程 $i$ 的先修课程的集合。由于数据规模 $n\\lt 15$,我们可以用一个整数的二进制位(状态压缩)来表示集合,其中第 $j$ 位为 $1$ 表示课程 $j$ 是课程 $i$ 的先修课程。\n\n我们用一个状态变量 $cur$ 表示当前已经上过的课程的集合,初始时 $cur=0$。如果 $cur=2^{n+1}-2$,表示所有课程都上过了,返回当前学期即可。\n\n如果课程 $i$ 的先修课程 $d[i]$ 的集合是 $cur$ 的子集,说明课程 $i$ 可以上。这样我们可以找到当前 $cur$ 状态的下一个状态 $nxt$,表示后续学期可以上的课程集合。\n\n如果 $nxt$ 的二进制表示中 $1$ 的个数小于等于 $k$,说明后续学期可以上的课程数不超过 $k$,我们就可以将 $nxt$ 加入队列中。否则,说明后续学期可以上的课程数超过 $k$,那么我们就应该从后续可以上的课程中选择 $k$ 门课程,这样才能保证后续学期可以上的课程数不超过 $k$。我们可以枚举 $nxt$ 的所有子集,将子集加入队列中。\n\n时间复杂度 $O(3^n)$,空间复杂度 $O(2^n)$。其中 $n$ 是题目给定的课程数。" }, "is_english": false, "time_complexity": "O(3^n)", "space_complexity": "O(2^n)" }, { "problem_id": 1495, "explanations": { "1": "We can first use an equi-join to join the two tables based on the `content_id` field, and then use conditional filtering to select the child-friendly movies that were played in June 2020." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1496, "explanations": { "1": "我们可以用一个哈希表 $vis$ 记录路径上的点。初始时 $vis$ 中只有原点 $(0, 0)$。\n\n遍历字符串 $path$,对于每个字符 $c$,根据 $c$ 的值更新当前位置 $(i, j)$,然后判断 $(i, j)$ 是否在 $vis$ 中,如果在,则返回 `true`,否则将 $(i, j)$ 加入 $vis$ 中。\n\n遍历结束后,返回 `false`。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为字符串 $path$ 的长度。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1497, "explanations": { "1": "The sum of two numbers $a$ and $b$ is divisible by $k$ if and only if the sum of their remainders when divided by $k$ is divisible by $k$.\n\nTherefore, we can count the remainder of each number in the array when divided by $k$, and record them in an array $\\textit{cnt}$. Then we traverse the array $\\textit{cnt}$. For each number $i$ in the range $[1,..k-1]$, if the values of $\\textit{cnt}[i]$ and $\\textit{cnt}[k-i]$ are not equal, it means we cannot divide the numbers in the array into $n/2$ pairs such that the sum of each pair is divisible by $k$. Similarly, if the value of $\\textit{cnt}[0]$ is not even, it also means we cannot divide the numbers in the array into $n/2$ pairs such that the sum of each pair is divisible by $k$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{arr}$. The space complexity is $O(k)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(k)" }, { "problem_id": 1498, "explanations": { "1": "Since the problem is about subsequences and involves the sum of the minimum and maximum elements, we can first sort the array $\\textit{nums}$.\n\nThen we enumerate the minimum element $\\textit{nums}[i]$. For each $\\textit{nums}[i]$, we can find the maximum element $\\textit{nums}[j]$ in $\\textit{nums}[i + 1]$ to $\\textit{nums}[n - 1]$ such that $\\textit{nums}[i] + \\textit{nums}[j] \\leq \\textit{target}$. The number of valid subsequences in this case is $2^{j - i}$, where $2^{j - i}$ represents all possible subsequences from $\\textit{nums}[i + 1]$ to $\\textit{nums}[j]$. We sum up the counts of all such subsequences.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1499, "explanations": { "1": "题目要求 $y_i + y_j + |x_i - x_j|$ 的最大值,其中 $i \\lt j$,并且 $|x_i - x_j| \\leq k$。由于 $x_i$ 是严格单调递增的,那么:\n\n$$\n\\begin{aligned}\ny_i + y_j + |x_i - x_j| & = y_i + y_j + x_j - x_i \\\\\n& = (y_i - x_i) + (x_j + y_j)\n\\end{aligned}\n$$\n\n因此,对于当前遍历到的点 $(x_j, y_j)$,我们只需要找到前面所有满足 $x_j - x_i \\leq k$ 的点 $(x_i, y_i)$ 中 $y_i - x_i$ 的最大值,再加上当前的 $x_j + y_j$ 即可。而 $y_i - x_i$ 的最大值,我们可以使用优先队列(大根堆)来维护。\n\n具体地,我们定义一个优先队列(大根堆) $pq$,堆中每个元素是一个二元组 $(y_i - x_i, x_i)$。\n\n当我们遍历到点 $(x, y)$ 时,如果堆 $pq$ 不为空,并且 $x - pq[0][1] \\gt k$,那么循环将堆顶元素弹出,直到堆为空或者满足 $x - pq[0][1] \\leq k$。此时,堆顶元素 $(y_i - x_i, x_i)$ 即为所有满足 $x_j - x_i \\leq k$ 的点中 $y_i - x_i$ 的最大值,此时更新答案 $ans = \\max(ans, x + y + pq[0][0])$。\n\n然后,我们将点 $(x, y)$ 加入堆中,继续遍历下一个点,直到遍历完整个数组 $points$。\n\n时间复杂度 $O(n \\times \\log n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 $points$ 的长度。", "2": "这道题实际上需要我们维护的是一个长度为 $k$ 的窗口中 $y-x$ 的最大值,单调队列可以很好地解决这个问题。\n\n具体地,我们定义一个单调队列 $q$,队列中每个元素是一个二元组 $(x_i, y_i)$。\n\n当我们遍历到点 $(x, y)$ 时,如果队列 $q$ 不为空,并且 $x - q[0][0] \\gt k$,那么不断弹出队首元素,直到队列为空或者满足 $x - q[0][0] \\leq k$。此时,队首元素 $(x_i, y_i)$ 即为所有满足 $x_j - x_i \\leq k$ 的点中 $y_i - x_i$ 的最大值,此时更新答案 $ans = \\max(ans, x + y + y_i - x_i)$。\n\n接下来,在将点 $(x, y)$ 加入队尾之前,我们将队列中所有 $y_i - x_i \\leq y - x$ 的元素 $(x_i, y_i)$ 弹出队列,然后将点 $(x, y)$ 加入队尾。继续遍历下一个点,直到遍历完整个数组 $points$。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 $points$ 的长度。" }, "is_english": false, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1500, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1501, "explanations": { "1": "We can use an equi-join to join the `Person` table and the `Calls` table on the condition of `Person.id = Calls.caller_id` or `Person.id = Calls.callee_id`, and then join the result with the `Country` table on the condition of `left(phone_number, 3) = country_code`. After that, we can group by country and calculate the average call duration for each country. Finally, we can use a subquery to find the countries whose average call duration is greater than the global average call duration.", "2": "" }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1502, "explanations": { "1": "We can first sort the array $\\textit{arr}$, then traverse the array, and check whether the difference between adjacent items is equal.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array $\\textit{arr}$.", "2": "We first find the minimum value $a$ and the maximum value $b$ in the array $\\textit{arr}$. If the array $\\textit{arr}$ can be rearranged into an arithmetic sequence, then the common difference $d = \\frac{b - a}{n - 1}$ must be an integer.\n\nWe can use a hash table to record all elements in the array $\\textit{arr}$, then traverse $i \\in [0, n)$, and check whether $a + d \\times i$ is in the hash table. If not, it means that the array $\\textit{arr}$ cannot be rearranged into an arithmetic sequence, and we return `false`. Otherwise, after traversing the array, we return `true`.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{arr}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 1503, "explanations": { "1": "The key point of the problem is that when two ants meet and then turn around, it is equivalent to the two ants continuing to move in their original directions. Therefore, we only need to find the maximum distance moved by any ant.\n\nNote that the lengths of the $\\textit{left}$ and $\\textit{right}$ arrays may be $0$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the plank. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1504, "explanations": { "1": "We can enumerate the bottom-right corner $(i, j)$ of the matrix, and then enumerate the first row $k$ upwards. The width of the matrix with $(i, j)$ as the bottom-right corner in each row is $\\min_{k \\leq i} \\textit{g}[k][j]$, where $\\textit{g}[k][j]$ represents the width of the matrix with $(k, j)$ as the bottom-right corner in the $k$-th row.\n\nTherefore, we can preprocess a 2D array $g[i][j]$, where $g[i][j]$ represents the number of consecutive $1$s from the $j$-th column to the left in the $i$-th row.\n\nThe time complexity is $O(m^2 \\times n)$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the number of rows and columns of the matrix, respectively." }, "is_english": true, "time_complexity": "O(m^2 \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 1505, "explanations": { "1": "树状数组,也称作“二叉索引树”(Binary Indexed Tree)或 Fenwick 树。 它可以高效地实现如下两个操作:\n\n1. **单点更新** `update(x, delta)`: 把序列 x 位置的数加上一个值 delta;\n1. **前缀和查询** `query(x)`:查询序列 `[1,...x]` 区间的区间和,即位置 x 的前缀和。\n\n这两个操作的时间复杂度均为 $O(\\log n)$。\n\n对于本题,要想得到在 k 次交换内字典序最小整数,我们可以「贪心」地从 num 的最高位开始考虑,即希望 num 的最高位尽可能小。我们可以依次枚举 `0~9`,对于当前枚举到的数位 x,判断是否可以将某个位置上的 x 通过最多 k 次交换移动到最高位。由于每一次交换只能交换相邻位置的两个数字,因此将一个距离最高位为 s 的数位移动到最高位,需要 s 次交换操作。例如当 `num = 97620` 时,0 与最高位的距离为 4,我们可以通过 4 次交换操作把 0 移动到最高位。\n\n这样的交换操作相当于把 0 移动到最高位,同时将 0 之前的所有数位向后移动了一位。\n\n我们接下来考虑次高位。与最高位类似,我们选择最小的数位 x,使得它与次高位的距离不超过 k',其中 k' 是 k 扣除最高位交换后的剩余次数。\n\n考虑上面 `num = 97620` 的例子,此时我们应当选择 x=2 交换至次高位。然而我们发现,经过第一次的交换操作,2 所在的位置发生了变化!在 num 中,2 与次高位的距离为 2,而将 0 交换至最高位后,2 与次高位的距离增加了 1,变为 3。这是因为 0 从 2 的后面「转移」到了 2 的前面,使得 2 向后移动了一位。因此,x 实际所在的位置,等于 x 初始时在 num 中的位置,加上 x 后面发生交换的数位个数。这里的「x 后面发生交换的数位个数」,就可以使用**树状数组**进行维护。\n\n解题思路如下:\n\n1. 用 `pos[x]` 按照高位到低位的顺序,存放所有 x 在 num 中出现的位置;\n1. 从高到低遍历每一个位置。对于位置 i,我们从小到大枚举交换的数位 x。`pos[x]` 中的首个元素即为与当前位置距离最近的 x 的位置:\n - 记 j 为 `pos[x]` 中的首元素,那么 `num[j]`(也即是 x)当前实际所在的位置,等于 j 加上 j 后面发现交换的数位个数。我们使用树状数组查询区间 `[j + 1, n]`,那么 num[j] 与位置 i 的实际距离 dist 为:`tree.query(n) - tree.query(j) + j - i`。\n - 如果 dist 小于等于 k,那么我们可以将 x 交换至位置 i。我们使用树状数组更新单点 j,将对应的值增加 1,表示该位置的数位发生了变换。随后更新 k 值,以及将 j 从 `pos[x]` 中移除。\n1. 遍历结束后,我们就得到了答案。" }, "is_english": false, "time_complexity": "O(\\log n)", "space_complexity": null }, { "problem_id": 1506, "explanations": { "1": "对于一棵 N 叉树的节点,如果该节点是根节点,那么该节点只会出现一次在数组 `tree` 中;而如果该节点不是根节点,那么该节点会出现两次,一次在数组 `tree` 中,一次在该节点的父节点的 `children` 数组中。\n\n因此,我们可以遍历数组 `tree`,计算每个节点的值以及其所有子节点的值的异或和,记录在变量 $x$ 中。遍历结束后,我们得到的 $x$ 就是根节点的值。\n\n接下来,我们再遍历数组 `tree`,找到值为 $x$ 的节点,即为根节点,返回即可。\n\n时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 `tree` 的长度。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1507, "explanations": { "1": "将字符串按空格分割为三个部分,分别为 `day`、`month` 和 `year`,然后拼接为 `YYYY-MM-DD` 的格式。\n\n时间复杂度 $O(1)$,空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 1508, "explanations": { "1": "We can generate the array $\\textit{arr}$ according to the problem's requirements, then sort the array, and finally calculate the sum of all elements in the range $[\\textit{left}-1, \\textit{right}-1]$ to get the result.\n\nThe time complexity is $O(n^2 \\times \\log n)$, and the space complexity is $O(n^2)$. Here, $n$ is the length of the array given in the problem." }, "is_english": true, "time_complexity": "O(n^2 \\times \\log n)", "space_complexity": "O(n^2)" }, { "problem_id": 1509, "explanations": { "1": "我们可以先判断数组长度是否小于 $5$,如果小于 $5$,那么直接返回 $0$。\n\n否则,我们将数组排序,然后贪心地选择数组左边最小的 $l=[0,..3]$ 个数和右边最小的 $r = 3 - l$ 个数,取其中最小的差值 $nums[n - 1 - r] - nums[l]$ 即可。\n\n时间复杂度 $O(n \\times \\log n)$,空间复杂度 $O(\\log n)$。其中 $n$ 为数组 `nums` 的长度。\n\n相似题目:\n\n- [2567. 修改两个元素的最小分数](https://github.com/doocs/leetcode/blob/main/solution/2500-2599/2567.Minimum%20Score%20by%20Changing%20Two%20Elements/README.md)" }, "is_english": false, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 1510, "explanations": { "1": "我们设计一个函数 $dfs(i)$,表示当前石子堆中有 $i$ 个石子时,当前玩家是否能赢得比赛。如果当前玩家能赢得比赛,则返回 $true$,否则返回 $false$。那么答案即为 $dfs(n)$。\n\n函数 $dfs(i)$ 的计算过程如下:\n\n- 如果 $i \\leq 0$,说明当前玩家无法进行任何操作,因此当前玩家输掉比赛,返回 $false$;\n- 否则,枚举当前玩家可以拿走的石子数量 $j$,其中 $j$ 为平方数,如果当前玩家拿走 $j$ 个石子后,另一个玩家无法赢得比赛,则当前玩家赢得比赛,返回 $true$。如果枚举完所有的 $j$,都无法满足上述条件,则当前玩家输掉比赛,返回 $false$。\n\n为了避免重复计算,我们可以使用记忆化搜索,即使用数组 $f$ 记录函数 $dfs(i)$ 的计算结果。\n\n时间复杂度 $O(n \\times \\sqrt{n})$,空间复杂度 $O(n)$。其中 $n$ 为石子堆中石子的数量。", "2": "我们也可以使用动态规划求解本题。\n\n定义数组 $f$,其中 $f[i]$ 表示当前石子堆中有 $i$ 个石子时,当前玩家是否能赢得比赛。如果当前玩家能赢得比赛,则 $f[i]$ 为 $true$,否则为 $false$。那么答案即为 $f[n]$。\n\n我们在 $[1,..n]$ 的范围内枚举 $i$,并在 $[1,..i]$ 的范围内枚举 $j$,其中 $j$ 为平方数,如果当前玩家拿走 $j$ 个石子后,另一个玩家无法赢得比赛,则当前玩家赢得比赛,即 $f[i] = true$。如果枚举完所有的 $j$,都无法满足上述条件,则当前玩家输掉比赛,即 $f[i] = false$。因此我们可以得到状态转移方程:\n\n$$\nf[i]=\n\\begin{cases}\ntrue, & \\textit{if } \\exists j \\in [1,..i], j^2 \\leq i \\textit{ and } f[i-j^2] = false\\\\\nfalse, & \\textit{otherwise}\n\\end{cases}\n$$\n\n最后,我们返回 $f[n]$ 即可。\n\n时间复杂度 $O(n \\times \\sqrt{n})$,空间复杂度 $O(n)$。其中 $n$ 为石子堆中石子的数量。" }, "is_english": false, "time_complexity": "O(n \\times \\sqrt{n})", "space_complexity": "O(n)" }, { "problem_id": 1511, "explanations": { "1": "We can use the `JOIN` statement to join the `Orders` table and the `Product` table, and then join the result with the `Customers` table. We can filter out the records where the `order_date` is not in the year $2020$, and then use the `GROUP BY` statement to group the data by `customer_id`. Finally, we can use the `HAVING` statement to filter out the customers whose spending in June and July is greater than or equal to $100$." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1512, "explanations": { "1": "Traverse the array, and for each element $x$, count how many elements before it are equal to $x$. This count represents the number of good pairs formed by $x$ and the previous elements. After traversing the entire array, we obtain the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(C)$. Here, $n$ is the length of the array, and $C$ is the range of values in the array. In this problem, $C = 101$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(C)" }, { "problem_id": 1513, "explanations": { "1": "We traverse the string $s$, using a variable $\\textit{cur}$ to record the current count of consecutive 1s, and a variable $\\textit{ans}$ to record the answer. When we traverse to character $s[i]$, if $s[i] = 0$, then set $\\textit{cur}$ to 0; otherwise, increment $\\textit{cur}$ by 1, then add $\\textit{cur}$ to $\\textit{ans}$, and take modulo $10^9 + 7$.\n\nAfter the traversal is complete, return $\\textit{ans}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$.\n\nSimilar problems:\n\n- [413. Arithmetic Slices](https://github.com/doocs/leetcode/blob/main/solution/0400-0499/0413.Arithmetic%20Slices/README_EN.md)\n- [2348. Number of Zero-Filled Subarrays](https://github.com/doocs/leetcode/blob/main/solution/2300-2399/2348.Number%20of%20Zero-Filled%20Subarrays/README_EN.md)" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1514, "explanations": { "1": "We can use Dijkstra's algorithm to find the shortest path, but here we modify it slightly to find the path with the maximum probability.\n\nWe use a priority queue (max-heap) $\\textit{pq}$ to store the probability from the starting point to each node and the node's identifier. Initially, we set the probability of the starting point to $1$ and the probabilities of the other nodes to $0$, then add the starting point to $\\textit{pq}$.\n\nIn each iteration, we take out the node $a$ with the highest probability from $\\textit{pq}$ and its probability $w$. If the probability of node $a$ is already greater than $w$, we can skip this node. Otherwise, we traverse all adjacent edges $(a, b)$ of $a$. If the probability of $b$ is less than the probability of $a$ multiplied by the probability of $(a, b)$, we update the probability of $b$ and add $b$ to $\\textit{pq}$.\n\nFinally, we obtain the maximum probability from the starting point to the endpoint.\n\nThe time complexity is $O(m \\times \\log m)$, and the space complexity is $O(m)$. Here, $m$ is the number of edges." }, "is_english": true, "time_complexity": "O(m \\times \\log m)", "space_complexity": "O(m)" }, { "problem_id": 1515, "explanations": { "1": "我们可以先设定一个初始的服务中心位置为所有客户坐标的几何中心 $(x, y)$。接下来,使用梯度下降法不断迭代,设定一个学习率 $\\alpha=0.5$,衰减率 $decay=0.999$。每次一次迭代,计算当前位置到所有客户的距离之和,然后计算当前位置的梯度,最后更新当前位置。当梯度的绝对值都小于 $10^{-6}$ 时,停止迭代,返回当前位置到所有客户的距离之和。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1516, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1517, "explanations": { "1": "We can use a regular expression to match valid email formats. The expression ensures that the username part meets the required rules and that the domain is fixed as `@leetcode.com`." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1518, "explanations": { "1": "我们可以直接模拟整个过程。\n\n初始时,我们有 `numBottles` 瓶水,因此可以喝到 `ans = numBottles` 瓶水,然后得到 `numBottles` 个空瓶子。\n\n接下来,如果我们有 `numExchange` 个空瓶子,那么我们可以用它们兑换一瓶水并喝掉,此时我们剩余的空瓶子数量为 `numBottles - numExchange + 1`,然后我们累加喝到的水的数量,即 $ans = ans + 1$。\n\n最后,返回 `ans` 即可。\n\n时间复杂度 $(\\frac{numBottles}{numExchange})$,空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 1519, "explanations": { "1": "我们先将边数组转换为邻接表 $g$。\n\n接下来我们从根节点 $0$ 开始遍历其子树,过程中维护一个计数器 $cnt$,用于统计当前各个字母出现的次数。\n\n在访问某个节点 $i$ 时,我们先将 $ans[i]$ 减去 $cnt[labels[i]]$,然后将 $cnt[labels[i]]$ 加 $1$,表示当前节点 $i$ 的标签出现了一次。接下来递归访问其子节点,最后将 $ans[i]$ 加上 $cnt[labels[i]]$。也即是说,我们将每个点离开时的计数器值减去每个点进来时的计数器值,就得到了以该点为根的子树中各个字母出现的次数。\n\n时间复杂度 $O(n)$,空间复杂度 $O(C)$。其中 $n$ 为节点数;而 $C$ 为字符集大小,本题中 $C = 26$。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(C)" }, { "problem_id": 1520, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1521, "explanations": { "1": "According to the problem description, we know that the function $func(arr, l, r)$ is actually the bitwise AND result of the elements in the array $arr$ from index $l$ to $r$, i.e., $arr[l] \\& arr[l + 1] \\& \\cdots \\& arr[r]$.\n\nIf we fix the right endpoint $r$ each time, then the range of the left endpoint $l$ is $[0, r]$. Since the sum of bitwise ANDs decreases monotonically with decreasing $l$, and the value of $arr[i]$ does not exceed $10^6$, there are at most $20$ different values in the interval $[0, r]$. Therefore, we can use a set to maintain all the values of $arr[l] \\& arr[l + 1] \\& \\cdots \\& arr[r]$. When we traverse from $r$ to $r+1$, the value with $r+1$ as the right endpoint is the value obtained by performing bitwise AND with each value in the set and $arr[r + 1]$, plus $arr[r + 1]$ itself. Therefore, we only need to enumerate each value in the set, perform bitwise AND with $arr[r]$, to obtain all the values with $r$ as the right endpoint. Then we subtract each value from $target$ and take the absolute value to obtain the absolute difference between each value and $target$. The minimum value among them is the answer.\n\nThe time complexity is $O(n \\times \\log M)$, and the space complexity is $O(\\log M)$. Here, $n$ and $M$ are the length of the array $arr$ and the maximum value in the array $arr$, respectively.\n\nSimilar problems:\n\n- [3171. Find Subarray With Bitwise AND Closest to K](https://github.com/doocs/leetcode/blob/main/solution/3100-3199/3171.Find%20Subarray%20With%20Bitwise%20AND%20Closest%20to%20K/README_EN.md)" }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(\\log M)" }, { "problem_id": 1522, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1523, "explanations": { "1": "We know that the count of odd numbers in the range $[0, x]$ is $\\lfloor\\frac{x+1}{2}\\rfloor$. Therefore, the count of odd numbers in the range $[low, high]$ is $\\lfloor\\frac{high+1}{2}\\rfloor - \\lfloor\\frac{low}{2}\\rfloor$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 1524, "explanations": { "1": "We define an array $\\textit{cnt}$ of length 2 as a counter, where $\\textit{cnt}[0]$ and $\\textit{cnt}[1]$ represent the number of subarrays with even and odd prefix sums, respectively. Initially, $\\textit{cnt}[0] = 1$ and $\\textit{cnt}[1] = 0$.\n\nNext, we maintain the current prefix sum $s$, initially $s = 0$.\n\nTraverse the array $\\textit{arr}$, for each element $x$ encountered, add the value of $x$ to $s$, then based on the parity of $s$, add the value of $\\textit{cnt}[s \\mod 2 \\oplus 1]$ to the answer, and then increment the value of $\\textit{cnt}[s \\mod 2]$ by 1.\n\nAfter the traversal, we get the answer. Note the modulo operation for the answer.\n\nTime complexity is $O(n)$, where $n$ is the length of the array $\\textit{arr}$. Space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1525, "explanations": { "1": "我们维护两个哈希表,分别记录左侧出现的字符、右侧的字符以及出现的次数。初始时,左侧的哈希表为空,右侧的哈希表为字符串 $s$ 中所有字符出现的次数。\n\n接下来,我们从左到右遍历字符串 $s$,对于遍历到的字符 $c$,我们将其加入左侧的哈希表,同时将其在右侧的哈希表中的出现次数减一。如果减一后,右侧哈希表中的出现次数为 0,则将其从右侧哈希表中移除。然后,我们判断左侧哈希表中的键值对数量是否与右侧哈希表中的键值对数量相等,如果相等,则将答案加一。\n\n最终,我们返回答案即可。\n\n时间复杂度为 $O(n)$,空间复杂度为 $O(n)$。其中 $n$ 为字符串 $s$ 的长度。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1526, "explanations": { "1": "We define $f[i]$ as the minimum number of operations required to obtain $target[0,..i]$, initially setting $f[0] = target[0]$.\n\nFor $target[i]$, if $target[i] \\leq target[i-1]$, then $f[i] = f[i-1]$; otherwise, $f[i] = f[i-1] + target[i] - target[i-1]$.\n\nThe final answer is $f[n-1]$.\n\nWe notice that $f[i]$ only depends on $f[i-1]$, so we can maintain the operation count using just one variable.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $target$. The space complexity is $O(1)$.\n\nSimilar problems:\n\n- [3229. Minimum Operations to Make Array Equal to Target](https://github.com/doocs/leetcode/blob/main/solution/3200-3299/3229.Minimum%20Operations%20to%20Make%20Array%20Equal%20to%20Target/README_EN.md)" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1527, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1528, "explanations": { "1": "We create a character array or string $\\textit{ans}$ of the same length as the input string, then iterate through the string $\\textit{s}$ and place each character $\\textit{s}[i]$ at position $\\textit{indices}[i]$ in $\\textit{ans}$. Finally, we join the character array or string $\\textit{ans}$ to form the final result and return it.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of the string." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1529, "explanations": { "1": "We traverse the string $\\textit{target}$ from left to right, using a variable $\\textit{ans}$ to record the number of flips. When we reach index $i$, if the parity of the current flip count $\\textit{ans}$ is different from $\\textit{target}[i]$, we need to perform a flip operation at index $i$ and increment $\\textit{ans}$ by $1$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1530, "explanations": { "1": "The problem asks for the number of good leaf node pairs in a binary tree. The answer can be divided into three parts: the number of good leaf node pairs in the left subtree, the number of good leaf node pairs in the right subtree, and the number of good leaf node pairs formed by leaf nodes from the left subtree and leaf nodes from the right subtree.\n\nWe can solve this recursively.\n\nThe time complexity is $O(n \\times d^2 \\times h)$, where $n$ is the number of nodes in the binary tree, and $h$ and $d$ are the height of the binary tree and the distance limit, respectively. The space complexity is $O(h)$ for the recursion stack." }, "is_english": true, "time_complexity": "O(n \\times d^2 \\times h)", "space_complexity": "O(h)" }, { "problem_id": 1531, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1532, "explanations": { "1": "We can use an equi-join to join the `Customers` table and the `Orders` table based on `customer_id`, and then use the window function `row_number()` to sort the orders for each customer by `order_date` in descending order and assign a row number to each order. Finally, we can filter out the orders with a row number less than or equal to $3$." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1533, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1534, "explanations": { "1": "We can enumerate all $i$, $j$, and $k$ where $i \\lt j \\lt k$, and check if they simultaneously satisfy $|\\textit{arr}[i] - \\textit{arr}[j]| \\le a$, $|\\textit{arr}[j] - \\textit{arr}[k]| \\le b$, and $|\\textit{arr}[i] - \\textit{arr}[k]| \\le c$. If they do, we increment the answer by one.\n\nAfter enumerating all possible triplets, we get the answer.\n\nThe time complexity is $O(n^3)$, where $n$ is the length of the array $\\textit{arr}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n^3)", "space_complexity": "O(1)" }, { "problem_id": 1535, "explanations": { "1": "We notice that each time the first two elements of the array are compared, regardless of the result, the next comparison will always be between the next element in the array and the current winner. Therefore, if we have looped $n-1$ times, the final winner must be the maximum element in the array. Otherwise, if an element has won consecutively $k$ times, then this element is the final winner.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$.\n\nSimilar problems:\n\n- [1535. Find the Winner of an Array Game](https://github.com/doocs/leetcode/blob/main/solution/3100-3199/3175.Find%20The%20First%20Player%20to%20win%20K%20Games%20in%20a%20Row/README_EN.md)" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1536, "explanations": { "1": "We process row by row. For the $i$-th row, the position of the last '1' must be less than or equal to $i$. We find the first row that meets the condition in $[i, n)$, denoted as $k$. Then, starting from the $k$-th row, we swap the adjacent two rows upwards until the $i$-th row.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ is the side length of the grid." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 1537, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1538, "explanations": { "1": "We first call `reader.query(0, 1, 2, 3)` and record the result as $x$.\n\nNext, we iterate from index $4$ onwards. Each time we call `reader.query(0, 1, 2, i)`, if the result is the same as $x$, we increment $a$ by one; otherwise, we increment $b$ by one and update $k$ to $i$.\n\nThen, we need to check whether the elements at indices $0, 1, 2$ are the same as the element at index $3$. If they are the same, we increment $a$ by one; otherwise, we increment $b$ by one and update $k$ to the corresponding index.\n\nFinally, if $a = b$, it means the number of $0$s and $1$s in the array are equal, so we return $-1$; otherwise, if $a > b$, we return $3$, otherwise we return $k$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1539, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1540, "explanations": { "1": "我们首先判断字符串 $s$ 和字符串 $t$ 的长度是否相等,如果不相等,直接返回 `false`。\n\n如果相等,我们可以统计每个位置的字符需要操作的最小次数,即 $cnt[x]$ 表示最小操作次数为 $x$ 的字符的个数。\n\n如果有 $cnt[x]$ 个字符需要操作 $x$ 次,那么我们需要 $x + 26 \\times (cnt[x] - 1)$ 次操作才能将这些字符转换为 $t$ 中对应的字符。因此,我们在 $[1,..25] 范围内枚举 $x$,如果 $x + 26 \\times (cnt[x] - 1) \\gt k$,说明我们无法将所有字符转换为 $t$ 中对应的字符,返回 `false`。\n\n否则,枚举结束后,说明我们可以将所有字符转换为 $t$ 中对应的字符,返回 `true`。\n\n时间复杂度 $O(n + C)$,空间复杂度 $O(C)$,其中 $n$ 为字符串 $s$ 和 $t$ 的长度;而 $C$ 为字符集大小,本题中 $C = 26$。" }, "is_english": false, "time_complexity": "O(n + C)", "space_complexity": "O(C)" }, { "problem_id": 1541, "explanations": { "1": "我们用 $x$ 表示字符串中待匹配的左括号的数量,初始时为 $0$。遍历字符串 $s$:\n\n如果遇到左括号,则 $x$ 的值加 $1$;如果遇到右括号,我们分情况讨论:\n\n- 如果有两个连续的右括号,那么我们先让指针往后移动一位;否则,我们需要插入一个右括号,使得出现两个连续的右括号,因此插入次数加 $1$;\n- 如果 $x = 0$,说明当前没有待匹配的左括号,我们需要插入一个左括号,用于匹配上面准备好的两个连续的右括号,因此插入次数加 $1$;否则,我们让 $x$ 的值减 $1$。\n\n然后指针往后移动一位,继续下一次遍历。\n\n遍历结束后,如果 $x = 0$,说明字符串已经平衡,返回插入次数;否则,说明字符串中有待匹配的左括号,我们需要再插入 $2 \\times x$ 个右括号,使得字符串变成平衡字符串,返回插入次数。\n\n时间复杂度 $O(n)$,空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1542, "explanations": { "1": "According to the problem description, the characters in the \"super awesome substring\" can be swapped to obtain a palindrome string. Therefore, there is at most one digit character in the \"super awesome substring\" that appears an odd number of times, and the rest of the digit characters appear an even number of times.\n\nWe can use an integer $st$ to represent the parity of the digit characters in the current prefix string, where the $i$-th bit of $st$ represents the parity of the digit character $i$, i.e., the $i$-th bit of $st$ is $1$ means that the digit character $i$ appears an odd number of times, and $0$ means that the digit character $i$ appears an even number of times.\n\nIf the substring $s[j,..i]$ is a \"super awesome string\", then the state $st$ of the prefix string $s[0,..i]$ and the state $st'$ of the prefix string $s[0,..j-1]$ differ by at most one bit in binary. This is because, if the binary bits are different, it means that the parity is different, and if the parity is different, it means that the number of times the digit appears in the substring $s[j,..i]$ is odd.\n\nSo, we can use a hash table or array to record the first occurrence of all states $st$. If the state $st$ of the current prefix string already exists in the hash table, it means that all bits in the binary of the state $st$ of the current prefix string and the state $st'$ of the prefix string $s[0,..j-1]$ are the same, i.e., the substring $s[j,..i]$ is a \"super awesome string\", and we update the maximum value of the answer. Or, we can enumerate each bit, flip the $i$-th bit of the state $st$ of the current prefix string, i.e., $st \\oplus 2^i$, and then check whether $st \\oplus 2^i$ is in the hash table. If it is, it means that only the $i$-th bit in the binary of the state $st$ of the current prefix string and the state $st' \\oplus 2^i$ of the prefix string $s[0,..j-1]$ is different, i.e., the substring $s[j,..i]$ is a \"super awesome string\", and we update the maximum value of the answer.\n\nFinally, return the answer.\n\nThe time complexity is $O(n \\times C)$, and the space complexity is $O(2^C)$. Where $n$ and $C$ are the length of the string $s$ and the number of types of digit characters, respectively." }, "is_english": true, "time_complexity": "O(n \\times C)", "space_complexity": "O(2^C)" }, { "problem_id": 1543, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1544, "explanations": { "1": "时间复杂度 $O(n)$,空间复杂度 $O(n)$,其中 $n$ 是字符串 `s` 的长度。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1545, "explanations": { "1": "We can observe that for $S_n$, the first half is the same as $S_{n-1}$, and the second half is the reverse and negation of $S_{n-1}$. Therefore, we can design a function $dfs(n, k)$, which represents the $k$-th character of the $n$-th string. The answer is $dfs(n, k)$.\n\nThe calculation process of the function $dfs(n, k)$ is as follows:\n\n- If $k = 1$, then the answer is $0$;\n- If $k$ is a power of $2$, then the answer is $1$;\n- If $k \\times 2 < 2^n - 1$, it means that $k$ is in the first half, and the answer is $dfs(n - 1, k)$;\n- Otherwise, the answer is $dfs(n - 1, 2^n - k) \\oplus 1$, where $\\oplus$ represents the XOR operation.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the given $n$ in the problem." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1546, "explanations": { "1": "We traverse the array $nums$, using the method of prefix sum + hash table, to find subarrays with a sum of $target$. If found, we increment the answer by one, then we set the prefix sum to $0$ and continue to traverse the array $nums$ until the entire array is traversed.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1547, "explanations": { "1": "We can add two elements to the array $\\textit{cuts}$, namely $0$ and $n$, representing the two ends of the stick. Then we sort the $\\textit{cuts}$ array, so we can divide the entire stick into several intervals, each with two cut points. Let the length of the $\\textit{cuts}$ array be $m$.\n\nNext, we define $\\textit{f}[i][j]$ to represent the minimum cost to cut the interval $[\\textit{cuts}[i], \\textit{cuts}[j]]$.\n\nIf an interval has only two cut points, meaning we do not need to cut this interval, then $\\textit{f}[i][j] = 0$.\n\nOtherwise, we enumerate the length $l$ of the interval, where $l$ is equal to the number of cut points minus $1$. Then we enumerate the left endpoint $i$ of the interval, and the right endpoint $j$ can be obtained by $i + l$. For each interval, we enumerate its cut point $k$, where $i \\lt k \\lt j$. We can then divide the interval $[i, j]$ into $[i, k]$ and $[k, j]$. The cost at this point is $\\textit{f}[i][k] + \\textit{f}[k][j] + \\textit{cuts}[j] - \\textit{cuts}[i]$. We take the minimum value among all possible $k$, which is the value of $\\textit{f}[i][j]$.\n\nFinally, we return $\\textit{f}[0][m - 1]$.\n\nThe time complexity is $O(m^3)$, and the space complexity is $O(m^2)$. Here, $m$ is the length of the modified $\\textit{cuts}$ array.", "2": "We can also enumerate $i$ from large to small and $j$ from small to large. This ensures that when calculating $f[i][j]$, the states $f[i][k]$ and $f[k][j]$ have already been computed, where $i \\lt k \\lt j$.\n\nThe time complexity is $O(m^3)$, and the space complexity is $O(m^2)$. Here, $m$ is the length of the modified $\\textit{cuts}$ array." }, "is_english": true, "time_complexity": "O(m^3)", "space_complexity": "O(m^2)" }, { "problem_id": 1548, "explanations": { "1": "We first build an adjacency list $g$ based on the given roads, where $g[i]$ represents the list of cities directly connected to city $i$.\n\nThen we define $f[i][j]$ to be the minimum edit distance of the first $i$ cities of $targetPath$ and the first $j$ cities of $names$ when city $i$ of $targetPath$ matches city $j$ of $names$.\n\nThen we can get the following recurrence equation:\n\n$$\nf[i][j] = \\min_{k \\in g[j]} f[i - 1][k] + (targetPath[i] \\neq names[j])\n$$\n\nIn the process of state transition, we record the predecessor city of each state, and finally restore the optimal path from the end to the beginning according to the predecessor city array $pre$.\n\nThe time complexity is $O(m \\times n^2)$, and the space complexity is $O(m \\times n)$. Where $m$ and $n$ are the lengths of $targetPath$ and $names$ respectively." }, "is_english": true, "time_complexity": "O(m \\times n^2)", "space_complexity": "O(m \\times n)" }, { "problem_id": 1549, "explanations": { "1": "We can use an equi-join to join the `Orders` table and the `Products` table based on `product_id`, and then use the window function `rank()`, which assigns a rank to each `product_id` in the `Orders` table based on its `order_date` in descending order. Finally, we can select the rows with a rank of $1$ for each `product_id`." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1550, "explanations": { "1": "We use a variable $\\textit{cnt}$ to record the current count of consecutive odd numbers.\n\nNext, we iterate through the array. If the current element is odd, then $\\textit{cnt}$ is incremented by one. If $\\textit{cnt}$ equals 3, then return $\\textit{True}$. If the current element is even, then $\\textit{cnt}$ is reset to zero.\n\nAfter the iteration, if three consecutive odd numbers are not found, then return $\\textit{False}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{arr}$. The space complexity is $O(1)$.", "2": "Based on the properties of bitwise operations, the result of a bitwise AND operation between two numbers is odd if and only if both numbers are odd. If there are three consecutive numbers whose bitwise AND result is odd, then these three numbers are all odd.\n\nTherefore, we only need to iterate through the array and check if there exists three consecutive numbers whose bitwise AND result is odd. If such numbers exist, return $\\textit{True}$; otherwise, return $\\textit{False}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{arr}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1551, "explanations": { "1": "According to the problem description, the array $arr$ is an arithmetic sequence with the first term as $1$ and the common difference as $2$. Therefore, the sum of the first $n$ terms of the array is:\n\n$$\n\\begin{aligned}\nS_n &= \\frac{n}{2} \\times (a_1 + a_n) \\\\\n&= \\frac{n}{2} \\times (1 + (2n - 1)) \\\\\n&= n^2\n\\end{aligned}\n$$\n\nSince in one operation, one number is decreased by one and another number is increased by one, the sum of all elements in the array remains unchanged. Therefore, when all elements in the array are equal, the value of each element is $S_n / n = n$. Hence, the minimum number of operations required to make all elements in the array equal is:\n\n$$\n\\sum_{i=0}^{\\frac{n}{2}} (n - (2i + 1))\n$$\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1552, "explanations": { "1": "We notice that the greater the minimum magnetic force between any two balls, the fewer balls can be placed, which exhibits monotonicity. We can use binary search to find the maximum minimum magnetic force that allows the number of balls not less than $m$ to be placed.\n\nFirst, we sort the positions of the baskets, and then use binary search with the left boundary $l = 1$ and the right boundary $r = \\textit{position}[n - 1]$, where $n$ is the number of baskets. In each binary search iteration, we calculate the midpoint $m = (l + r + 1) / 2$, and then determine if there is a way to place the balls such that the number of balls placed is not less than $m$.\n\nThe problem is transformed into determining whether a given minimum magnetic force $f$ can place $m$ balls. We can traverse the positions of the baskets from left to right, and if the distance between the position of the last ball and the current basket's position is greater than or equal to $f$, it indicates that a ball can be placed in the current basket. Finally, we check if the number of balls placed is not less than $m$.\n\nThe time complexity is $O(n \\times \\log n + n \\times \\log M)$, and the space complexity is $O(\\log n)$. Here, $n$ and $M$ respectively represent the number of baskets and the maximum value of the basket positions." }, "is_english": true, "time_complexity": "O(n \\times \\log n + n \\times \\log M)", "space_complexity": "O(\\log n)" }, { "problem_id": 1553, "explanations": { "1": "According to the problem description, for each $n$, we can choose one of three ways:\n\n1. Decrease $n$ by $1$;\n2. If $n$ can be divided by $2$, divide the value of $n$ by $2$;\n3. If $n$ can be divided by $3$, divide the value of $n$ by $3$.\n\nTherefore, the problem is equivalent to finding the minimum number of days to reduce $n$ to $0$ through the above three ways.\n\nWe design a function $dfs(n)$, which represents the minimum number of days to reduce $n$ to $0$. The execution process of the function $dfs(n)$ is as follows:\n\n1. If $n < 2$, return $n$;\n2. Otherwise, we can first reduce $n$ to a multiple of $2$ by $n \\bmod 2$ operations of $1$, and then perform operation $2$ to reduce $n$ to $n/2$; we can also first reduce $n$ to a multiple of $3$ by $n \\bmod 3$ operations of $1$, and then perform operation $3$ to reduce $n$ to $n/3$. We choose the minimum of the above two ways, that is, $1 + \\min(n \\bmod 2 + dfs(n/2), n \\bmod 3 + dfs(n/3))$.\n\nTo avoid repeated calculations, we use the method of memoization search and store the calculated values of $dfs(n)$ in a hash table.\n\nThe time complexity is $O(\\log^2 n)$, and the space complexity is $O(\\log^2 n)$." }, "is_english": true, "time_complexity": "O(\\log^2 n)", "space_complexity": "O(\\log^2 n)" }, { "problem_id": 1554, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1555, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1556, "explanations": { "1": "直接按照题目要求模拟即可。\n\n时间复杂度 $O(\\log n)$,忽略答案的空间消耗,空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 1557, "explanations": { "1": "我们注意到,所有入度为 $0$ 的点都一定属于最小点集,因为它们没有任何入边。而由于题目给定的是一张有向无环图,因此所有入度不为 $0$ 的点一定存在一条入边,也即一定能从某个入度为 $0$ 的点出发到达。因此我们只需要找到所有入度为 $0$ 的点即可。\n\n时间复杂度 $O(n + m)$,空间复杂度 $O(n)$。其中 $n$ 和 $m$ 分别是节点数和边数。" }, "is_english": false, "time_complexity": "O(n + m)", "space_complexity": "O(n)" }, { "problem_id": 1558, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1559, "explanations": { "1": "We can traverse each cell in the 2D grid. For each cell, if the cell $grid[i][j]$ has not been visited, we start a breadth-first search (BFS) from that cell. During the search, we need to record the parent node of each cell and the coordinates of the previous cell. If the value of the next cell is the same as the current cell, and it is not the previous cell, and it has already been visited, then it indicates the presence of a cycle, and we return $\\textit{true}$. After traversing all cells, if no cycle is found, we return $\\textit{false}$.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the number of rows and columns of the 2D grid, respectively.", "2": "We can traverse each cell in the 2D grid. For each cell, if the cell $grid[i][j]$ has not been visited, we start a depth-first search (DFS) from that cell. During the search, we need to record the parent node of each cell and the coordinates of the previous cell. If the value of the next cell is the same as the current cell, and it is not the previous cell, and it has already been visited, then it indicates the presence of a cycle, and we return $\\textit{true}$. After traversing all cells, if no cycle is found, we return $\\textit{false}$.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the number of rows and columns of the 2D grid, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 1560, "explanations": { "1": "Since the end position of each stage is the start position of the next stage, and each stage is in a counterclockwise direction, we can determine the number of times each sector is passed based on the relationship between the start and end positions.\n\nIf $\\textit{rounds}[0] \\leq \\textit{rounds}[m]$, then the sectors from $\\textit{rounds}[0]$ to $\\textit{rounds}[m]$ are passed the most times, and we can directly return all sectors within this interval.\n\nOtherwise, the sectors from $1$ to $\\textit{rounds}[m]$ and the sectors from $\\textit{rounds}[0]$ to $n$ form the union of the most passed sectors, and we can return the union of these two intervals.\n\nThe time complexity is $O(n)$, where $n$ is the number of sectors. Ignoring the space consumption of the answer array, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1561, "explanations": { "1": "To maximize the number of coins we get, we can greedily let Bob take the smallest $n$ piles of coins. Each time, we let Alice take the largest pile of coins, then we take the second largest pile of coins, and so on, until there are no more coins to take.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the number of piles of coins." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 1562, "explanations": { "1": "正向遍历 $arr$,利用并查集动态维护每组 $1$ 的长度。\n\n时间复杂度 $O(n \\times \\log n)$。\n\n相似题目:\n\n- [2334. 元素值大于变化阈值的子数组](https://github.com/doocs/leetcode/blob/main/solution/2300-2399/2334.Subarray%20With%20Elements%20Greater%20Than%20Varying%20Threshold/README.md)", "2": "我们其实并不需要去通过查找并查集来获取每个区间长度,我们只需要在每个区间端点处记录每个区间长度,由于合并的时候**只会访问区间端点**,所以合并区间的时候修改端点区间长度即可。\n\n时间复杂度 $O(n)$。" }, "is_english": false, "time_complexity": "O(n \\times \\log n)", "space_complexity": null }, { "problem_id": 1563, "explanations": { "1": "First, we preprocess the prefix sum array $\\textit{s}$, where $\\textit{s}[i]$ represents the sum of the first $i$ elements of the array $\\textit{stoneValue}$.\n\nNext, we design a function $\\textit{dfs}(i, j)$, which represents the maximum score Alice can get from the stones in the subarray $\\textit{stoneValue}$ within the index range $[i, j]$. The answer is $\\textit{dfs}(0, n - 1)$.\n\nThe calculation process of the function $\\textit{dfs}(i, j)$ is as follows:\n\n- If $i \\geq j$, it means there is only one stone left, and Alice cannot split it, so return $0$.\n- Otherwise, we enumerate the split point $k$, i.e., $i \\leq k < j$, splitting the stones in the subarray $\\textit{stoneValue}$ within the index range $[i, j]$ into two parts: $[i, k]$ and $[k + 1, j]$. We calculate $a$ and $b$, which represent the total sum of the stones in the two parts, respectively. Then we calculate $\\textit{dfs}(i, k)$ and $\\textit{dfs}(k + 1, j)$, and update the answer.\n\nNote that if $a < b$ and $\\textit{ans} \\geq a \\times 2$, this enumeration can be skipped; if $a > b$ and $\\textit{ans} \\geq b \\times 2$, all subsequent enumerations can be skipped, and the loop can be exited directly.\n\nFinally, we return the answer.\n\nTo avoid repeated calculations, we can use memoization and pruning to optimize the enumeration efficiency.\n\nThe time complexity is $O(n^3)$, and the space complexity is $O(n^2)$. Here, $n$ is the length of the array $\\textit{stoneValue}$." }, "is_english": true, "time_complexity": "O(n^3)", "space_complexity": "O(n^2)" }, { "problem_id": 1564, "explanations": { "1": "我们可以先对仓库的房间进行预处理,得到一个数组 $left$,其中 $left[i]$ 表示下标 $i$ 可以放入的最大箱子高度。\n\n然后对箱子的高度进行排序,从小到大依次放入仓库中。我们使用两个指针 $i$ 和 $j$ 分别指向箱子的第一个位置以及仓库的最后一个位置,如果 $left[j] \\lt boxes[i]$,说明当前仓库无法放入箱子 $i$,我们将指针 $j$ 循环向左移动,直到 $left[j] \\ge boxes[i]$ 或者 $j \\lt 0$。如果此时 $j \\lt 0$,说明仓库已经没有空间可以放入箱子 $i$,我们可以直接退出循环。否则说明仓库可以放入箱子 $i$,我们将指针 $i$ 循环向右移动,指针 $j$ 循环向左移动。继续进行上述操作,直到指针 $i$ 超出箱子的范围。\n\n最后我们返回指针 $i$ 的值即可。\n\n时间复杂度 $O(n \\times \\log n)$,空间复杂度 $O(n)$。其中 $n$ 为仓库的房间数。" }, "is_english": false, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1565, "explanations": { "1": "We can first filter out orders with an amount greater than $20$, and then group by month to count the number of orders and customers." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1566, "explanations": { "1": "First, if the length of the array is less than $m \\times k$, then there is definitely no pattern of length $m$ that repeats at least $k$ times, so we directly return $\\textit{false}$.\n\nNext, we define a variable $\\textit{cnt}$ to record the current count of consecutive repetitions. If there are $(k - 1) \\times m$ consecutive elements $a_i$ in the array such that $a_i = a_{i - m}$, then we have found a pattern of length $m$ that repeats at least $k$ times, and we return $\\textit{true}$. Otherwise, we reset $\\textit{cnt}$ to $0$ and continue traversing the array.\n\nFinally, if we finish traversing the array without finding a pattern that meets the conditions, we return $\\textit{false}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1567, "explanations": { "1": "We define two arrays $f$ and $g$ of length $n$, where $f[i]$ represents the length of the longest subarray ending at $\\textit{nums}[i]$ with a positive product, and $g[i]$ represents the length of the longest subarray ending at $\\textit{nums}[i]$ with a negative product.\n\nInitially, if $\\textit{nums}[0] > 0$, then $f[0] = 1$, otherwise $f[0] = 0$; if $\\textit{nums}[0] < 0$, then $g[0] = 1$, otherwise $g[0] = 0$. We initialize the answer $ans = f[0]$.\n\nNext, we iterate through the array $\\textit{nums}$ starting from $i = 1$. For each $i$, we have the following cases:\n\n- If $\\textit{nums}[i] > 0$, then $f[i]$ can be transferred from $f[i - 1]$, i.e., $f[i] = f[i - 1] + 1$, and the value of $g[i]$ depends on whether $g[i - 1]$ is $0$. If $g[i - 1] = 0$, then $g[i] = 0$, otherwise $g[i] = g[i - 1] + 1$;\n- If $\\textit{nums}[i] < 0$, then the value of $f[i]$ depends on whether $g[i - 1]$ is $0$. If $g[i - 1] = 0$, then $f[i] = 0$, otherwise $f[i] = g[i - 1] + 1$, and $g[i]$ can be transferred from $f[i - 1]$, i.e., $g[i] = f[i - 1] + 1$.\n- Then, we update the answer $ans = \\max(ans, f[i])$.\n\nAfter the iteration, we return the answer $ans$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$.", "2": "We observe that for each $i$, the values of $f[i]$ and $g[i]$ only depend on $f[i - 1]$ and $g[i - 1]$. Therefore, we can use two variables $f$ and $g$ to record the values of $f[i - 1]$ and $g[i - 1]$, respectively, thus optimizing the space complexity to $O(1)$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1568, "explanations": { "1": "观察发现,我们总是可以通过把角落相邻的两个陆地变成水,使得岛屿分离。因此,答案只可能是 0,1 或 2。\n\n我们跑一遍 DFS,统计当前岛屿的数量,如果数量不等于 $1$,也就是说不满足恰好只有一座岛屿,那么答案就是 0。\n\n否则,我们遍历每一块陆地,把它变成水,然后再跑一遍 DFS,看看岛屿的数量是否不等于 1,如果不等于 1,说明这块陆地变成水后,岛屿分离了,答案就是 1。\n\n遍历结束,说明必须要把两块陆地变成水,才能使得岛屿分离,因此答案就是 2。\n\n时间复杂度 $O(m^2\\times n^2)$,其中 $m$ 和 $n$ 分别是 `grid` 的行数和列数。" }, "is_english": false, "time_complexity": "O(m^2\\times n^2)", "space_complexity": null }, { "problem_id": 1569, "explanations": { "1": "We design a function $dfs(nums)$, which is used to calculate the number of solutions of the binary search tree with $nums$ as nodes. Then the answer is $dfs(nums)-1$, because $dfs(nums)$ calculates the number of solutions of the binary search tree with $nums$ as nodes, while the problem requires the number of solutions of the binary search tree with $nums$ as nodes after reordering, so the answer needs to be subtracted by one.\n\nNext, let's take a look at how $dfs(nums)$ is calculated.\n\nFor an array $nums$, its first element is the root node, so its left subtree elements are smaller than it, and its right subtree elements are larger than it. So we can divide the array into three parts, the first part is the root node, the second part is the elements of the left subtree, denoted as $left$, and the third part is the elements of the right subtree, denoted as $right$. Then, the number of elements in the left subtree is $m$, and the number of elements in the right subtree is $n$, so the number of solutions for $left$ and $right$ are $dfs(left)$ and $dfs(right)$ respectively. We can choose $m$ positions from $m + n$ positions in array $nums$ to place the elements of the left subtree, and the remaining $n$ positions to place the elements of the right subtree, so that we can ensure that the reordered binary search tree is the same as the original array $nums$. Therefore, the calculation method of $dfs(nums)$ is:\n\n$$\ndfs(nums) = C_{m+n}^m \\times dfs(left) \\times dfs(right)\n$$\n\nwhere $C_{m+n}^m$ represents the number of schemes to select $m$ positions from $m + n$ positions, which we can get through preprocessing.\n\nNote the modulo operation of the answer, because the value of $dfs(nums)$ may be very large, so we need to take the modulo of each step in the calculation process, and finally take the modulo of the entire result.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Where $n$ is the length of array $nums$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 1570, "explanations": { "1": "We use a hash map $d$ to store non-zero elements, where the key is the index, and the value is the corresponding value. We iterate through $\\textit{nums}$, and if $\\textit{nums}[i]$ is not $0$, we add $(i, \\textit{nums}[i])$ to the hash map $d$.\n\nWhen calculating the dot product, we iterate through the hash map with fewer non-zero elements and check if the other hash map contains the corresponding key. If it exists, we multiply the corresponding values and add them to the result.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1571, "explanations": { "1": "We can use an inner join to join the `Warehouse` table and the `Products` table on the condition of `product_id`, and then group by warehouse name to calculate the inventory of each warehouse using the `SUM` function." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1572, "explanations": { "1": "We can traverse each row $\\textit{row}[i]$ of the matrix. For each row, we calculate the elements on the two diagonals, i.e., $\\textit{row}[i][i]$ and $\\textit{row}[i][n - i - 1]$, where $n$ is the number of rows in the matrix. If $i = n - i - 1$, it means there is only one element on the diagonals of the current row; otherwise, there are two elements. We add these elements to the answer.\n\nAfter traversing all rows, we get the answer.\n\nThe time complexity is $O(n)$, where $n$ is the number of rows in the matrix. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1573, "explanations": { "1": "First, we traverse the string $s$ and count the number of characters $1$, denoted as $cnt$. If $cnt$ cannot be divided by $3$, then it is impossible to split the string, so we directly return $0$. If $cnt$ is $0$, it means there are no characters $1$ in the string. We can choose any two positions out of $n-1$ positions to split the string into three substrings, so the number of ways is $C_{n-1}^2$.\n\nIf $cnt \\gt 0$, we update $cnt$ to $\\frac{cnt}{3}$, which is the number of characters $1$ in each substring.\n\nNext, we find the minimum index of the right boundary of the first substring, denoted as $i_1$, and the maximum index of the right boundary of the first substring (exclusive), denoted as $i_2$. Similarly, we find the minimum index of the right boundary of the second substring, denoted as $j_1$, and the maximum index of the right boundary of the second substring (exclusive), denoted as $j_2$. Then the number of ways is $(i_2 - i_1) \\times (j_2 - j_1)$.\n\nNote that the answer may be very large, so we need to take the modulo $10^9+7$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the string $s$.\n\nSimilar problems:\n\n- [927. Three Equal Parts](https://github.com/doocs/leetcode/blob/main/solution/0900-0999/0927.Three%20Equal%20Parts/README_EN.md)" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1574, "explanations": { "1": "First, we find the longest non-decreasing prefix and the longest non-decreasing suffix of the array, denoted as $\\textit{nums}[0..i]$ and $\\textit{nums}[j..n-1]$, respectively.\n\nIf $i \\geq j$, it means the array is already non-decreasing, so we return $0$.\n\nOtherwise, we can choose to delete the right suffix or the left prefix. Therefore, initially, the answer is $\\min(n - i - 1, j)$.\n\nNext, we enumerate the right endpoint $l$ of the left prefix. For each $l$, we can use binary search to find the first position greater than or equal to $\\textit{nums}[l]$ in $\\textit{nums}[j..n-1]$, denoted as $r$. At this point, we can delete $\\textit{nums}[l+1..r-1]$ and update the answer $\\textit{ans} = \\min(\\textit{ans}, r - l - 1)$. Continue enumerating $l$ to get the final answer.\n\nThe time complexity is $O(n \\times \\log n)$, where $n$ is the length of the array. The space complexity is $O(1)$.", "2": "Similar to Solution 1, we first find the longest non-decreasing prefix and the longest non-decreasing suffix of the array, denoted as $\\textit{nums}[0..i]$ and $\\textit{nums}[j..n-1]$, respectively.\n\nIf $i \\geq j$, it means the array is already non-decreasing, so we return $0$.\n\nOtherwise, we can choose to delete the right suffix or the left prefix. Therefore, initially, the answer is $\\min(n - i - 1, j)$.\n\nNext, we enumerate the right endpoint $l$ of the left prefix. For each $l$, we directly use two pointers to find the first position greater than or equal to $\\textit{nums}[l]$ in $\\textit{nums}[j..n-1]$, denoted as $r$. At this point, we can delete $\\textit{nums}[l+1..r-1]$ and update the answer $\\textit{ans} = \\min(\\textit{ans}, r - l - 1)$. Continue enumerating $l$ to get the final answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(1)" }, { "problem_id": 1575, "explanations": { "1": "We design a function $dfs(i, k)$, which represents the number of paths from city $i$ with $k$ remaining fuel to the destination $finish$. So the answer is $dfs(start, fuel)$.\n\nThe process of calculating the function $dfs(i, k)$ is as follows:\n\n- If $k \\lt |locations[i] - locations[finish]|$, then return $0$.\n- If $i = finish$, then the number of paths is $1$ at the beginning, otherwise it is $0$.\n- Then, we traverse all cities $j$. If $j \\ne i$, then we can move from city $i$ to city $j$, and the remaining fuel is $k - |locations[i] - locations[j]|$. Then we can add the number of paths to the answer $dfs(j, k - |locations[i] - locations[j]|)$.\n- Finally, we return the number of paths to the answer.\n\nTo avoid repeated calculations, we can use memoization.\n\nThe time complexity is $O(n^2 \\times m)$, and the space complexity is $O(n \\times m)$. Where $n$ and $m$ are the size of the array $locations$ and $fuel$ respectively.", "2": "We can also convert the memoization of solution 1 into dynamic programming.\n\nWe define $f[i][k]$ represents the number of paths from city $i$ with $k$ remaining fuel to the destination $finish$. So the answer is $f[start][fuel]$. Initially $f[finish][k]=1$, others are $0$.\n\nNext, we enumerate the remaining fuel $k$ from small to large, and then enumerate all cities $i$. For each city $i$, we enumerate all cities $j$. If $j \\ne i$, and $|locations[i] - locations[j]| \\le k$, then we can move from city $i$ to city $j$, and the remaining fuel is $k - |locations[i] - locations[j]|$. Then we can add the number of paths to the answer $f[j][k - |locations[i] - locations[j]|]$.\n\nFinally, we return the number of paths to the answer $f[start][fuel]$.\n\nThe time complexity is $O(n^2 \\times m)$, and the space complexity is $O(n \\times m)$. Where $n$ and $m$ are the size of the array $locations$ and $fuel$ respectively." }, "is_english": true, "time_complexity": "O(n^2 \\times m)", "space_complexity": "O(n \\times m)" }, { "problem_id": 1576, "explanations": { "1": "我们遍历字符串,对于每个位置,如果该位置是 `?`,则枚举字符 `'a'`、`'b'`、`'c'`,如果该字符 $c$ 与前后字符都不相同,则将该位置替换为该字符,否则继续枚举下一个字符。\n\n遍历结束后,返回字符串即可。\n\n时间复杂度 $O(n)$,其中 $n$ 为字符串的长度。忽略答案的空间消耗,空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1577, "explanations": { "1": "We use a hash table $\\textit{cnt1}$ to count the occurrences of each pair $(\\textit{nums}[j], \\textit{nums}[k])$ in $\\textit{nums1}$, where $0 \\leq j < k < m$, and $m$ is the length of the array $\\textit{nums1}$. Similarly, we use a hash table $\\textit{cnt2}$ to count the occurrences of each pair $(\\textit{nums}[j], \\textit{nums}[k])$ in $\\textit{nums2}$, where $0 \\leq j < k < n$, and $n$ is the length of the array $\\textit{nums2}$.\n\nNext, we enumerate each number $x$ in the array $\\textit{nums1}$ and calculate the value of $\\textit{cnt2}[x^2]$, which is the number of pairs $(\\textit{nums}[j], \\textit{nums}[k])$ in $\\textit{nums2}$ that satisfy $\\textit{nums}[j] \\times \\textit{nums}[k] = x^2$. Similarly, we enumerate each number $x$ in the array $\\textit{nums2}$ and calculate the value of $\\textit{cnt1}[x^2]$, which is the number of pairs $(\\textit{nums}[j], \\textit{nums}[k])$ in $\\textit{nums1}$ that satisfy $\\textit{nums}[j] \\times \\textit{nums}[k] = x^2$. Finally, we return the sum of the two results.\n\nThe time complexity is $O(m^2 + n^2 + m + n)$, and the space complexity is $O(m^2 + n^2)$. Here, $m$ and $n$ are the lengths of the arrays $\\textit{nums1}$ and $\\textit{nums2}$, respectively.", "2": "We use a hash table $\\textit{cnt1}$ to count the occurrences of each number in $\\textit{nums1}$, and a hash table $\\textit{cnt2}$ to count the occurrences of each number in $\\textit{nums2}$.\n\nNext, we enumerate each number $x$ in the array $\\textit{nums1}$, and then enumerate each pair $(y, v1)$ in $\\textit{cnt2}$, where $y$ is the key of $\\textit{cnt2}$ and $v1$ is the value of $\\textit{cnt2}$. We calculate $z = x^2 / y$. If $y \\times z = x^2$, and if $y = z$, it means $y$ and $z$ are the same number, then the number of ways to choose two numbers from $v1$ is $v1 \\times (v1 - 1) = v1 \\times (v2 - 1)$. If $y \\neq z$, then the number of ways to choose two numbers from $v1$ is $v1 \\times v2$. Finally, we sum all the ways and divide by $2$. The division by $2$ is because we count the number of ways for the pair $(j, k)$, but $(j, k)$ and $(k, j)$ are the same way.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m + n)$. Here, $m$ and $n$ are the lengths of the arrays $\\textit{nums1}$ and $\\textit{nums2}$, respectively." }, "is_english": true, "time_complexity": "O(m^2 + n^2 + m + n)", "space_complexity": "O(m^2 + n^2)" }, { "problem_id": 1578, "explanations": { "1": "We can use two pointers to point to the beginning and end of the current consecutive balloons with the same color, then calculate the total time $s$ of these consecutive balloons with the same color, as well as the maximum time $mx$. If the number of consecutive balloons with the same color is greater than $1$, we can greedily choose to keep the balloon with the maximum time and remove the other balloons with the same color, which takes time $s - mx$, and add it to the answer. Then we continue to traverse until all balloons are traversed.\n\nThe time complexity is $O(n)$ and the space complexity is $O(1)$, where $n$ is the number of balloons." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1579, "explanations": { "1": "题目要求我们删除最多数目的边,使得 Alice 和 Bob 都可以遍历整个图。也即是说,我们需要保留尽可能少的边,并且要求这些边能够使得 Alice 和 Bob 都可以遍历整个图。\n\n我们可以用两个并查集 $ufa$ 和 $ufb$ 分别维护 Alice 和 Bob 的遍历情况。\n\n接下来,我们优先遍历公共边,即 $type=3$ 的边。对于每一条公共边的两个端点 $u$ 和 $v$,如果这两个点已经在同一个连通分量中,那么我们就可以删去这条边,因此答案加一;否则我们就将这两个点合并,即执行 $ufa.union(u, v)$ 和 $ufb.union(u, v)$。\n\n然后,我们再遍历 Alice 独有的边,即 $type=1$ 的边。对于每一条 Alice 独有的边的两个端点 $u$ 和 $v$,如果这两个点已经在同一个连通分量中,那么我们就可以删去这条边,答案加一;否则我们就将这两个点合并,即执行 $ufa.union(u, v)$。同理,对于 Bob 独有的边,我们也可以执行相同的操作。\n\n最后,如果 Alice 和 Bob 都可以遍历整个图,那么答案就是我们删除的边数;否则答案就是 $-1$。\n\n时间复杂度 $O(m \\times \\alpha(n))$,空间复杂度 $O(n)$。其中 $m$ 是边数,而 $\\alpha(n)$ 是阿克曼函数的反函数。" }, "is_english": false, "time_complexity": "O(m \\times \\alpha(n))", "space_complexity": "O(n)" }, { "problem_id": 1580, "explanations": { "1": "First, we preprocess the warehouse to get the maximum height of each room. Then, we sort both the boxes and the warehouse. Starting with the smallest box and the smallest room, if the current room's height is greater than or equal to the current box's height, we can place the current box in the current room; otherwise, we continue to the next room.\n\nFinally, we return the number of boxes that can be placed.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the warehouse." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1581, "explanations": { "1": "We can use a subquery to first find all `visit_id`s that have not made any transactions, and then group by `customer_id` to count the number of times each customer has not made any transactions.", "2": "We can also use a left join to join the `Visits` table and the `Transactions` table on `visit_id`, and then filter out the records where `amount` is `NULL`. After that, we can group by `customer_id` to count the number of times each customer has not made any transactions." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1582, "explanations": { "1": "We can use two arrays, $\\textit{rows}$ and $\\textit{cols}$, to record the number of $1$s in each row and each column, respectively.\n\nThen, we traverse the matrix. For each $1$, we check whether there is only one $1$ in its row and column. If so, we increment the answer by one.\n\nAfter the traversal, we return the answer.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m + n)$. Here, $m$ and $n$ are the number of rows and columns of the matrix $\\textit{mat}$, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m + n)" }, { "problem_id": 1583, "explanations": { "1": "We use an array $\\textit{d}$ to record the closeness between each pair of friends, where $\\textit{d}[i][j]$ represents the closeness of friend $i$ to friend $j$ (the smaller the value, the closer they are). Additionally, we use an array $\\textit{p}$ to record the paired friend for each friend.\n\nWe enumerate each friend $x$. For $x$'s paired friend $y$, we find the closeness $\\textit{d}[x][y]$ of $x$ to $y$. Then, we enumerate other friends $u$ who are closer than $\\textit{d}[x][y]$. If there exists a friend $u$ such that the closeness $\\textit{d}[u][x]$ of $u$ to $x$ is higher than $\\textit{d}[u][y]$, then $x$ is an unhappy friend, and we increment the result by one.\n\nAfter the enumeration, we obtain the number of unhappy friends.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ is the number of friends." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 1584, "explanations": { "1": "我们定义一个数组 $dist$,其中 $dist[i]$ 表示点 $i$ 到当前生成树的距离,初始时 $dist[0] = 0$,其余均为 $+\\infty$,定义一个数组 $vis$,其中 $vis[i]$ 表示点 $i$ 是否在生成树中,初始时所有点均不在生成树中,定义一个二维数组 $g$,其中 $g[i][j]$ 表示点 $i$ 到点 $j$ 的距离,那么我们的目标是将所有点都加入到生成树中,且总费用最小。\n\n我们每次从不在生成树中的点中选取一个距离最小的点 $i$,将点 $i$ 加入到生成树中,并将 $i$ 到其它点的距离更新到 $dist$ 数组中,直到所有点都在生成树中为止。\n\n该算法适用于稠密图,时间复杂度 $O(n^2)$,空间复杂度 $O(n^2)$。其中 $n$ 为点的数量。", "2": "我们先将所有边按照长度由小到大进行排序,循环遍历每条边,逐个加入到图中,当所有点达到一个连通状态时,退出循环,返回此时的总费用即可。\n\n时间复杂度 $O(m \\times \\log m)$,空间复杂度 $O(m)$。其中 $m$ 为边的数量,本题中 $m = n^2$。" }, "is_english": false, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 1585, "explanations": { "1": "The problem is essentially equivalent to determining whether any substring of length 2 in string $s$ can be swapped using bubble sort to obtain $t$.\n\nTherefore, we use an array $pos$ of length 10 to record the indices of each digit in string $s$, where $pos[i]$ represents the list of indices where digit $i$ appears, sorted in ascending order.\n\nNext, we iterate through string $t$. For each character $t[i]$ in $t$, we convert it to the digit $x$. We check if $pos[x]$ is empty. If it is, it means that the digit in $t$ does not exist in $s$, so we return `false`. Otherwise, to swap the character at the first index of $pos[x]$ to index $i$, all indices of digits less than $x$ must be greater than or equal to the first index of $pos[x]. If this condition is not met, we return `false`. Otherwise, we pop the first index from $pos[x]$ and continue iterating through string $t$.\n\nAfter the iteration, we return `true`.\n\nThe time complexity is $O(n \\times C)$, and the space complexity is $O(n)$. Here, $n$ is the length of string $s$, and $C$ is the size of the digit set, which is 10 in this problem." }, "is_english": true, "time_complexity": "O(n \\times C)", "space_complexity": "O(n)" }, { "problem_id": 1586, "explanations": { "1": "We can use in-order traversal to store the values of all nodes in the binary search tree into an array $nums$, and then use the array to implement the iterator. We define a pointer $i$, initially $i = -1$, which points to an element in the array $nums$. Each time we call $next()$, we add $1$ to the value of $i$ and return $nums[i]$; each time we call $prev()$, we subtract $1$ from the value of $i$ and return $nums[i]$.\n\nIn terms of time complexity, initializing the iterator requires $O(n)$ time, where $n$ is the number of nodes in the binary search tree. Each call to $next()$ and $prev()$ requires $O(1)$ time. In terms of space complexity, we need $O(n)$ space to store the values of all nodes in the binary search tree." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1587, "explanations": { "1": "We can use an equi-join to join the `Users` table and the `Transactions` table on the condition of `account`, and then group by `account` to calculate the balance for each account using the `SUM` function. Finally, we can filter out the users whose balance is less than or equal to $10000$." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1588, "explanations": { "1": "We define two arrays $f$ and $g$ of length $n$, where $f[i]$ represents the sum of subarrays ending at $\\textit{arr}[i]$ with odd lengths, and $g[i]$ represents the sum of subarrays ending at $\\textit{arr}[i]$ with even lengths. Initially, $f[0] = \\textit{arr}[0]$, and $g[0] = 0$. The answer is $\\sum_{i=0}^{n-1} f[i]$.\n\nWhen $i > 0$, consider how $f[i]$ and $g[i]$ transition:\n\nFor the state $f[i]$, the element $\\textit{arr}[i]$ can form an odd-length subarray with the previous $g[i-1]$. The number of such subarrays is $(i / 2) + 1$, so $f[i] = g[i-1] + \\textit{arr}[i] \\times ((i / 2) + 1)$.\n\nFor the state $g[i]$, when $i = 0$, there are no even-length subarrays, so $g[0] = 0$. When $i > 0$, the element $\\textit{arr}[i]$ can form an even-length subarray with the previous $f[i-1]$. The number of such subarrays is $(i + 1) / 2$, so $g[i] = f[i-1] + \\textit{arr}[i] \\times ((i + 1) / 2)$.\n\nThe final answer is $\\sum_{i=0}^{n-1} f[i]$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{arr}$.", "2": "We notice that the values of $f[i]$ and $g[i]$ only depend on $f[i - 1]$ and $g[i - 1]$. Therefore, we can use two variables $f$ and $g$ to record the values of $f[i - 1]$ and $g[i - 1]$, respectively, thus optimizing the space complexity.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1589, "explanations": { "1": "We observe that for a query operation, it returns the sum of all elements in the query interval $[l, r]$. The problem requires the maximum sum of the results of all query operations, which means we need to accumulate the results of all query operations to maximize the sum. Therefore, if an index $i$ appears more frequently in the query operations, we should assign a larger value to index $i$ to maximize the sum of the results of all query operations.\n\nTherefore, we can use the idea of a difference array to count the number of times each index appears in the query operations, then sort these counts in ascending order, and also sort the array $\\textit{nums}$ in ascending order. This ensures that the more frequently an index $i$ appears in the query operations, the larger the value $\\textit{nums}[i]$ corresponding to that index will be. Next, we only need to multiply the values $\\textit{nums}[i]$ corresponding to these indices by the number of times they appear in the query operations, and then sum them up to get the maximum sum of the results of all query operations.\n\nTime complexity $O(n \\times \\log n)$, space complexity $O(n)$. Where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1590, "explanations": { "1": "First, we calculate the sum of all elements in the array $\\textit{nums}$ modulo $p$, denoted as $k$. If $k$ is $0$, it means the sum of all elements in the array $\\textit{nums}$ is a multiple of $p$, so we directly return $0$.\n\nIf $k$ is not $0$, we need to find the shortest subarray such that removing this subarray makes the sum of the remaining elements modulo $p$ equal to $0$.\n\nWe can traverse the array $\\textit{nums}$, maintaining the current prefix sum modulo $p$, denoted as $cur$. We use a hash table $last$ to record the last occurrence of each prefix sum modulo $p$.\n\nIf there exists a subarray ending at $\\textit{nums}[i]$ such that removing this subarray makes the sum of the remaining elements modulo $p$ equal to $0$, we need to find a previous prefix sum modulo $p$ equal to $target$ at position $j$ such that $(target + k - cur) \\bmod p = 0$. If found, we can remove the subarray $\\textit{nums}[j+1,..i]$ to make the sum of the remaining elements modulo $p$ equal to $0$.\n\nTherefore, if there exists a $target = (cur - k + p) \\bmod p$, we can update the answer to $\\min(ans, i - j)$. Then, we update $last[cur]$ to $i$. We continue traversing the array $\\textit{nums}$ until the end to get the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1591, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1592, "explanations": { "1": "First, we count the number of spaces in the string $\\textit{text}$, denoted as $\\textit{spaces}$. Then, we split $\\textit{text}$ by spaces into an array of strings $\\textit{words}$. Next, we calculate the number of spaces that need to be inserted between adjacent words and perform the concatenation. Finally, we append the remaining spaces to the end.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ represents the length of the string $\\textit{text}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1593, "explanations": { "1": "We define a hash table $\\textit{st}$ to store the currently split substrings. Then we use a depth-first search approach to try to split the string $\\textit{s}$ into several unique substrings.\n\nSpecifically, we design a function $\\text{dfs}(i)$, which means we are considering splitting $\\textit{s}[i:]$.\n\nIn the function $\\text{dfs}(i)$, we first check if the number of substrings already split plus the remaining characters is less than or equal to the current answer. If so, there is no need to continue splitting, and we return directly. If $i \\geq n$, it means we have completed the splitting of the entire string, and we update the answer to the maximum of the current number of substrings and the answer. Otherwise, we enumerate the end position $j$ (exclusive) of the current substring and check if $\\textit{s}[i..j)$ has already been split. If not, we add it to the hash table $\\textit{st}$ and continue to recursively consider splitting the remaining part. After the recursive call, we need to remove $\\textit{s}[i..j)$ from the hash table $\\textit{st}$.\n\nFinally, we return the answer.\n\nThe time complexity is $O(n^2 \\times 2^n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $\\textit{s}$." }, "is_english": true, "time_complexity": "O(n^2 \\times 2^n)", "space_complexity": "O(n)" }, { "problem_id": 1594, "explanations": { "1": "We define a 3D array $f$, where $f[i][j][0]$ and $f[i][j][1]$ represent the minimum and maximum product of all paths from the top-left corner $(0, 0)$ to position $(i, j)$, respectively. For each position $(i, j)$, we can transition from above $(i - 1, j)$ or from the left $(i, j - 1)$, so we need to consider the results of multiplying the minimum and maximum products of these two paths by the value of the current cell.\n\nFinally, we need to return $f[m - 1][n - 1][1]$ modulo $10^9 + 7$. If $f[m - 1][n - 1][1]$ is less than $0$, return $-1$.\n\nThe time complexity is $O(m \\times n)$ and the space complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns of the matrix, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 1595, "explanations": { "1": "Let $m$ and $n$ denote the number of points in the first group and the second group, respectively.\n\nSince $1 \\leq n \\leq m \\leq 12$, we can use an integer to represent the state of points in the second group — specifically, a binary integer of length $n$, where bit $k$ being $1$ means the $k$-th point in the second group is connected to some point in the first group, and $0$ means it is not.\n\nNext, we define $f[i][j]$ as the minimum cost when the first $i$ points in the first group are all connected, and the state of points in the second group is $j$. Initially, $f[0][0] = 0$ and all other values are positive infinity. The answer is $f[m][2^n - 1]$.\n\nConsider $f[i][j]$ where $i \\geq 1$. We enumerate each point $k$ in the second group. If point $k$ is connected to the $i$-th point in the first group, we discuss the following two cases:\n\n- If point $k$ is only connected to the $i$-th point in the first group, then $f[i][j]$ can be transitioned from $f[i][j \\oplus 2^k]$ or $f[i - 1][j \\oplus 2^k]$, where $\\oplus$ denotes the XOR operation;\n- If point $k$ is connected to the $i$-th point in the first group as well as other points, then $f[i][j]$ can be transitioned from $f[i - 1][j]$.\n\nIn both cases, we take the minimum transition value:\n\n$$\nf[i][j] = \\min_{k \\in \\{0, 1, \\cdots, n - 1\\}} \\{f[i][j \\oplus 2^k], f[i - 1][j \\oplus 2^k], f[i - 1][j]\\} + cost[i - 1][k]\n$$\n\nFinally, we return $f[m][2^n - 1]$.\n\nThe time complexity is $O(m \\times n \\times 2^n)$ and the space complexity is $O(m \\times 2^n)$, where $m$ and $n$ are the number of points in the first group and the second group, respectively.", "2": "We notice that the transition of $f[i][j]$ only depends on $f[i - 1][\\cdot]$ and $f[i][\\cdot]$, so we can use a rolling array to optimize the space complexity down to $O(2^n)$." }, "is_english": true, "time_complexity": "O(m \\times n \\times 2^n)", "space_complexity": "O(m \\times 2^n)" }, { "problem_id": 1596, "explanations": { "1": "We group the `Orders` table by `customer_id` and `product_id`, and then use the window function `rank()`, which assigns a rank to each `product_id` in each `customer_id` group based on its frequency in descending order. Finally, we select the `product_id` with a rank of $1$ for each `customer_id`, which is the most frequently ordered product for that `customer_id`." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1597, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1598, "explanations": { "1": "直接模拟,记录深度的变化即可。\n\n时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为 `logs` 的长度。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1599, "explanations": { "1": "We directly simulate the rotation process of the Ferris wheel. Each time it rotates, we add up the waiting customers and the newly arrived customers, then at most $4$ people get on the ride, update the number of waiting customers and profit, and record the maximum profit and its corresponding number of rotations.\n\nThe time complexity is $O(n)$, where $n$ is the length of the `customers` array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1600, "explanations": { "1": "According to the problem description, we can find that the order of throne inheritance is actually a preorder traversal of a multi-branch tree. We can use a hash table $g$ to store the children of each person, and a set $dead$ to store the people who have died.\n\n- When calling `birth(parentName, childName)`, we add `childName` to the child list of `parentName`.\n- When calling `death(name)`, we add `name` to the `dead` set.\n- When calling `getInheritanceOrder()`, we start a depth-first search from the king. If the current node `x` is not dead, we add `x` to the answer list, and then recursively traverse all children of `x`.\n\nIn terms of time complexity, both `birth` and `death` have a time complexity of $O(1)$, and `getInheritanceOrder` has a time complexity of $O(n)$. The space complexity is $O(n)$, where $n$ is the number of nodes." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(n)" }, { "problem_id": 1601, "explanations": { "1": "We note that the length of the room change request list does not exceed $16$. Therefore, we can use the method of binary enumeration to enumerate all room change request lists. Specifically, we can use a binary number of length $16$ to represent a room change request list, where the $i$-th bit being $1$ means the $i$-th room change request is selected, and $0$ means the $i$-th room change request is not selected.\n\nWe enumerate all binary numbers in the range of $[1, 2^{m})$, for each binary number $mask$, we first calculate how many $1$s are in its binary representation, denoted as $cnt$. If $cnt$ is larger than the current answer $ans$, then we judge whether $mask$ is a feasible room change request list. If it is, then we update the answer $ans$ with $cnt$. To judge whether $mask$ is a feasible room change request list, we only need to check whether the net inflow of each room is $0$.\n\nThe time complexity is $O(2^m \\times (m + n))$, and the space complexity is $O(n)$, where $m$ and $n$ are the lengths of the room change request list and the number of rooms, respectively." }, "is_english": true, "time_complexity": "O(2^m \\times (m + n))", "space_complexity": "O(n)" }, { "problem_id": 1602, "explanations": { "1": "We can use Breadth-First Search, starting from the root node. When we reach node $u$, we return the next node in the queue.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in the binary tree.", "2": "DFS performs a pre-order traversal of the binary tree. The first time we search to node $u$, we mark the current depth $d$. The next time we encounter a node at the same level, it is the target node.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1603, "explanations": { "1": "We use an array $\\textit{cnt}$ of length 4 to represent the number of parking spaces for each type of car, where $\\textit{cnt}[1]$, $\\textit{cnt}[2]$, and $\\textit{cnt}[3]$ represent the number of large, medium, and small parking spaces, respectively.\n\nDuring initialization, we set $\\textit{cnt}[1]$, $\\textit{cnt}[2]$, and $\\textit{cnt}[3]$ to the number of large, medium, and small parking spaces, respectively.\n\nEach time a car parks, we check if there is a corresponding parking space in the parking lot. If not, we return $\\textit{false}$; otherwise, we decrement the number of corresponding parking spaces by one and return $\\textit{true}$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 1604, "explanations": { "1": "First, we use a hash table $d$ to record all the clock-in times of each employee.\n\nThen we traverse the hash table. For each employee, we first check whether the number of clock-in times is greater than or equal to 3. If not, we skip this employee. Otherwise, we sort all the clock-in times of this employee in chronological order, and then traverse the sorted clock-in times to check whether the two times at a distance of 2 indices are within the same hour. If so, we add this employee to the answer array.\n\nFinally, we sort the answer array in lexicographical order to get the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the number of clock-in records." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1605, "explanations": { "1": "We can first initialize an $m$ by $n$ answer matrix $ans$.\n\nNext, we traverse each position $(i, j)$ in the matrix, set the element at this position to $x = \\min(rowSum[i], colSum[j])$, and subtract $x$ from $rowSum[i]$ and $colSum[j]$ respectively. After traversing all positions, we can get a matrix $ans$ that meets the requirements of the problem.\n\nThe correctness of the above strategy is explained as follows:\n\nAccording to the requirements of the problem, we know that the sum of $rowSum$ and $colSum$ is equal, so $rowSum[0]$ must be less than or equal to $\\sum_{j = 0}^{n - 1} colSum[j]$. Therefore, after $n$ operations, $rowSum[0]$ can definitely be made $0$, and for any $j \\in [0, n - 1]$, $colSum[j] \\geq 0$ is guaranteed.\n\nTherefore, we reduce the original problem to a subproblem with $m-1$ rows and $n$ columns, continue the above operations, until all elements in $rowSum$ and $colSum$ are $0$, we can get a matrix $ans$ that meets the requirements of the problem.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Where $m$ and $n$ are the lengths of $rowSum$ and $colSum$ respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 1606, "explanations": { "1": "题目求的是最繁忙的服务器列表,因此可以想到用**哈希表**记录每个服务器处理的任务数,然后获取所有处理了最大任务数 mx 的服务器列表即可。关键的问题就在于,求出每个任务分配给了哪台服务器处理。\n\n我们用 有序集合 free 存放所有的空闲服务器,优先队列 busy 存放正在处理请求的服务器的处理结束时间和对应的服务器编号,即二元组 `(end, server)`,优先队列满足队首元素的处理结束时间最小,用一个哈希表 cnt 记录每台服务器处理的任务数。\n\n当第 i 个请求到达时,如果 busy 不为空,我们循环判断 busy 队首的任务结束时间是否小于等于当前请求的到达时间 `arrival[i]`,即 start。如果是,说明队首任务在此时刻已经处理结束,可以从 busy 队列中移出,循环判断。\n\n接下来,如果 free 为空,说明当前没有空闲服务器能够处理第 i 个请求,直接 continue 丢弃;否则,查找 free 中大于等于 `i % k` 的第一个服务器,如果查找成功,那么由该服务器来处理该请求,否则,由 free 的第一个服务器(编号最小)来处理。假设该服务器是 server, 那么 `cnt[server]` 加 1,同时将二元组 `(end, server)` 放入优先队列 busy 中,并且将该 server 中有序集合 free 中移出。\n\n最后,只需要获取 cnt 中的最大值 mx,找出处理了 mx 个任务数的服务器列表,即为答案。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1607, "explanations": { "1": "We can use a left join to join the `Seller` table with the `Orders` table on the condition `seller_id`, and then group by `seller_id` to count the number of sales for each seller in the year $2020$. Finally, we can filter out the sellers with zero sales." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1608, "explanations": { "1": "We enumerate $x$ in the range of $[1..n]$, and then count the number of elements in the array that are greater than or equal to $x$, denoted as $cnt$. If there exists $cnt$ equal to $x$, return $x$ directly.\n\nThe time complexity is $O(n^2)$, where $n$ is the length of the array. The space complexity is $O(1)$.", "2": "We can also sort `nums` first.\n\nNext, we still enumerate $x$, and use binary search to find the first element in `nums` that is greater than or equal to $x$, quickly counting the number of elements in `nums` that are greater than or equal to $x$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(1)" }, { "problem_id": 1609, "explanations": { "1": "BFS traverses level by level. Each level is judged by its parity. The node values at each level are either all even or all odd, and they are strictly increasing or decreasing.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of nodes in the binary tree.", "2": "DFS performs a pre-order traversal of the binary tree, and similarly judges whether it meets the conditions based on the parity of the layer where the node is located. During the traversal, a hash table is used to record the node value that was most recently visited at each layer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1610, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1611, "explanations": { "1": "This problem essentially asks for the inverse transformation of Gray code at position $n$, i.e., constructing the original number from the Gray code.\n\nLet's first review how to convert binary code to binary Gray code. The rule is to keep the most significant bit of the binary code as the most significant bit of the Gray code, while the second most significant bit of the Gray code is obtained by XORing the most significant bit and the second most significant bit of the binary code. The remaining bits of the Gray code are computed similarly to the second most significant bit.\n\nSuppose a binary number is represented as $B_{n-1}B_{n-2}...B_2B_1B_0$, and its Gray code representation is $G_{n-1}G_{n-2}...G_2G_1G_0$. The most significant bit is kept, so $G_{n-1} = B_{n-1}$; and for other bits $G_i = B_{i+1} \\oplus B_{i}$, where $i=0,1,2..,n-2$.\n\nSo what is the inverse transformation from Gray code to binary code?\n\nWe can observe that the most significant bit of the Gray code is kept, so $B_{n-1} = G_{n-1}$; and $B_{n-2} = G_{n-2} \\oplus B_{n-1} = G_{n-2} \\oplus G_{n-1}$; and for other bits $B_i = G_{i} \\oplus G_{i+1} \\cdots \\oplus G_{n-1}$, where $i=0,1,2..,n-2$. Therefore, we can use the following function $rev(x)$ to obtain its binary code:\n\n```java\nint rev(int x) {\n int n = 0;\n for (; x != 0; x >>= 1) {\n n ^= x;\n }\n return n;\n}\n```\n\nThe time complexity is $O(\\log n)$, where $n$ is the integer given in the problem. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 1612, "explanations": { "1": "我们定义一个计数器 $cnt$,用于统计每个字母出现的次数。\n\n然后我们分别对两棵二叉表达式树进行深度优先搜索,如果字母出现在左子树,则 $cnt$ 中对应的字母的值加 $1$,如果出现在右子树,则 $cnt$ 中对应的字母的值减 $1$。\n\n最后,我们遍历 $cnt$,如果所有字母的值都为 $0$,则返回 `true`,否则返回 `false`。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉表达式树的节点个数。", "2": "" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1613, "explanations": { "1": "利用 `recursive` 关键字,递归生成 `[1, 100]` 的序列,然后排除已有的 `customer_id`,即可得到结果。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1614, "explanations": { "1": "We use a variable $d$ to record the current depth, initially $d = 0$.\n\nTraverse the string $s$. When encountering a left parenthesis, increment the depth $d$ by one and update the answer to be the maximum of the current depth $d$ and the answer. When encountering a right parenthesis, decrement the depth $d$ by one.\n\nFinally, return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1615, "explanations": { "1": "We can use a one-dimensional array $\\textit{cnt}$ to record the degree of each city and a two-dimensional array $\\textit{g}$ to record whether there is a road between each pair of cities. If there is a road between city $a$ and city $b$, then $\\textit{g}[a][b] = \\textit{g}[b][a] = 1$; otherwise, $\\textit{g}[a][b] = \\textit{g}[b][a] = 0$.\n\nNext, we enumerate each pair of cities $(a, b)$, where $a \\lt b$, and calculate their network rank, which is $\\textit{cnt}[a] + \\textit{cnt}[b] - \\textit{g}[a][b]$. The maximum value among these is the answer.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ is the number of cities." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 1616, "explanations": { "1": "We can use two pointers, where one pointer $i$ starts from the beginning of string $a$, and the other pointer $j$ starts from the end of string $b$. If the characters pointed to by the two pointers are equal, then both pointers move towards the center until they encounter different characters or the two pointers cross.\n\nIf the two pointers cross, i.e., $i \\geq j$, it means that $prefix$ and $suffix$ can already form a palindrome, and we return `true`. Otherwise, we need to check if $a[i,...j]$ or $b[i,...j]$ is a palindrome. If so, return `true`.\n\nOtherwise, we try swapping the two strings $a$ and $b$ and repeat the same process.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$. Where $n$ is the length of string $a$ or $b$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1617, "explanations": { "1": "我们注意到 $n \\leq 15$,因此可以考虑使用二进制枚举的方法枚举所有的子树。而子树中节点的最大距离,其实就是子树中两个节点之间的最长路径,也即是树的直径,求解树的直径一般可以使用 DFS 或 BFS,先找到树直径的一个端点,然后再从该端点出发,找到树的另一个端点,这两个端点之间的路径长度就是树的直径。\n\n接下来,我们详细说明具体的代码实现。\n\n我们先根据数组 $edges$ 构建出邻接表 $g$,其中 $g[u]$ 表示节点 $u$ 的所有邻接节点。\n\n用一个二进制数 $mask$ 表示子树,其中 $mask$ 的第 $i$ 位为 $1$ 表示节点 $i$ 在子树中,否则表示节点 $i$ 不在子树中。每个节点都有两种状态,即在子树中或不在子树中,有 $n$ 个节点,因此一共有 $2^n$ 种状态。\n\n接下来,我们在 $[1,..2^n-1]$ 的范围内枚举子树 $mask$,对于每个子树:\n\n如果 $mask$ 的二进制表示中只有一个二进制位为 $1$,即 $mask \\in [1,2,4,8,\\cdots,2^{n-1}]$,则跳过该 $mask$,因为这些 $mask$ 表示的子树只有一个节点,不符合题意;\n\n否则,我们找到 $mask$ 的二进制表示中最高位的二进制位为 $1$ 的位置,记为 $cur$。然后从节点 $cur$ 出发,通过深度优先搜索或者广度优先搜索,找到树直径的一个端点 $nxt$,然后我们再从节点 $nxt$ 出发,同样通过深度优先搜索或者广度优先搜索,过程中记录下最大距离 $mx$。\n\n当走到最深的节点时,即可得知树的直径。此时我们更新答案数组 $ans$,将 $ans[mx-1]$ 的值加 $1$。注意,这里是 $mx-1$,因为题目中的最大距离是从 $1$ 开始计数的。\n\n最后,枚举完所有的子树,返回答案数组 $ans$ 即可。\n\n时间复杂度 $O(2^n \\times n)$,空间复杂度 $O(n)$。其中 $n$ 为节点个数。", "2": "" }, "is_english": false, "time_complexity": "O(2^n \\times n)", "space_complexity": "O(n)" }, { "problem_id": 1618, "explanations": { "1": "根据题目描述,字体数组按升序排列。因此,我们可以二分枚举字体大小 `fontSize`,找到最大的并且能够在屏幕上显示文本字体大小即可。\n\n时间复杂度 $O(m\\log n)$。其中 $m$, $n$ 为文本 `text` 的长度以及字体大小 `fonts` 个数。\n\n关于二分查找,见[整数二分算法模板 2](https://github.com/doocs/leetcode/blob/main/basic/searching/BinarySearch/README.md)。" }, "is_english": false, "time_complexity": "O(m\\log n)", "space_complexity": null }, { "problem_id": 1619, "explanations": { "1": "直接模拟。\n\n先对数组 `arr` 排序,然后截取中间的 90% 个元素,求平均值。\n\n时间复杂度 $O(n\\log n)$。其中 $n$ 为数组 `arr` 的长度。" }, "is_english": false, "time_complexity": "O(n\\log n)", "space_complexity": null }, { "problem_id": 1620, "explanations": { "1": "由于坐标点的范围是 $[0,.. 50]$,因此我们可以直接暴力枚举所有的坐标点 $(i, j)$,计算每个坐标点的信号强度,然后找出信号强度最大的坐标点。\n\n时间复杂度 $O(n \\times C^2)$,其中 $n$ 是信号塔的数量,而 $C$ 是坐标点的范围大小。" }, "is_english": false, "time_complexity": "O(n \\times C^2)", "space_complexity": null }, { "problem_id": 1621, "explanations": { "1": "记 $f[i][j]$ 表示使用前 $i$ 个点构造了 $j$ 条线段,且最后一条线段的右端点不为 $i$ 的方案数;记 $g[i][j]$ 表示使用了前 $i$ 个点构造了 $j$ 条线段,且最后一条线段的右端点为 $i$ 的方案数。初始时 $f[1][0]=1$。\n\n考虑 $f[i][j]$,由于第 $j$ 条线段的右端点不为 $i$,因此前 $i-1$ 个点构造了 $j$ 条线段,因此有:\n\n$$\nf[i][j] = f[i-1][j] + g[i - 1][j]\n$$\n\n考虑 $g[i][j]$,第 $j$ 条线段的右端点为 $i$,如果第 $j$ 条线段的长度超过 $1$,则前 $i-1$ 个点构造了 $j$ 条线段,且第 $j$ 条线段的右端点一定覆盖了 $i-1$,因此有:\n\n$$\ng[i][j] = g[i - 1][j]\n$$\n\n如果第 $j$ 条线段的长度为 $1$,则前 $i-1$ 个点构造了 $j-1$ 条线段,有:\n\n$$\ng[i][j] = f[i - 1][j - 1] + g[i - 1][j - 1]\n$$\n\n答案为 $f[n][k]+g[n][k]$。\n\n时间复杂度 $O(n\\times k)$,空间复杂度 $O(n\\times k)$。" }, "is_english": false, "time_complexity": "O(n\\times k)", "space_complexity": "O(n\\times k)" }, { "problem_id": 1622, "explanations": { "1": "线段树将整个区间分割为多个不连续的子区间,子区间的数量不超过 `log(width)`。更新某个元素的值,只需要更新 `log(width)` 个区间,并且这些区间都包含在一个包含该元素的大区间内。区间修改时,需要使用**懒标记**保证效率。\n\n- 线段树的每个节点代表一个区间;\n- 线段树具有唯一的根节点,代表的区间是整个统计范围,如 `[1, N]`;\n- 线段树的每个叶子节点代表一个长度为 1 的元区间 `[x, x]`;\n- 对于每个内部节点 `[l, r]`,它的左儿子是 `[l, mid]`,右儿子是 `[mid + 1, r]`, 其中 `mid = ⌊(l + r) / 2⌋` (即向下取整)。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1623, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1624, "explanations": { "1": "用数组或哈希表记录字符串 $s$ 每个字符第一次出现的位置。由于本题中字符串 $s$ 只含小写英文字母,因此可以用一个长度为 $26$ 的数组 $d$ 来记录,初始时数组元素值均为 $-1$。\n\n遍历字符串 $s$ 中每个字符 $c$,若 $c$ 在数组中的值为 $-1$,则更新为当前位置 $i$;否则我们将答案更新为当前位置 $i$ 与数组中的值 $d[c]$ 的差值的最大值减一,即 $ans = \\max (ans, i - d[c]-1)$。\n\n时间复杂度 $O(n)$,空间复杂度 $O(C)$。其中 $n$ 为字符串长度,而 $C$ 为字符串 $s$ 的字符集大小,本题 $C=26$。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(C)" }, { "problem_id": 1625, "explanations": { "1": "Since the data scale of this problem is relatively small, we can use BFS to brute-force search all possible states and then take the lexicographically smallest state.", "2": "We observe that for the addition operation, a digit will return to its original state after at most $10$ additions; for the rotation operation, the string will also return to its original state after at most $n$ rotations.\n\nTherefore, the rotation operation produces at most $n$ states. If the rotation count $b$ is even, the addition operation only affects digits at odd indices, resulting in a total of $n \\times 10$ states; if the rotation count $b$ is odd, the addition operation affects both odd and even index digits, resulting in a total of $n \\times 10 \\times 10$ states.\n\nThus, we can directly enumerate all possible string states and take the lexicographically smallest one.\n\nThe time complexity is $O(n^2 \\times 10^2)$ and the space complexity is $O(n)$, where $n$ is the length of string $s$." }, "is_english": true, "time_complexity": "O(n^2 \\times 10^2)", "space_complexity": "O(n)" }, { "problem_id": 1626, "explanations": { "1": "我们可以将球员按照分数从小到大排序,如果分数相同,则按照年龄从小到大排序。\n\n接下来,使用动态规划求解。\n\n我们定义 $f[i]$ 表示以排序后的第 $i$ 个球员作为最后一个球员的最大得分,那么答案就是 $\\max_{0 \\leq i < n} f[i]$。\n\n对于 $f[i]$,我们可以枚举 $0 \\leq j \\lt i$,如果第 $i$ 个球员的年龄大于等于第 $j$ 个球员的年龄,则 $f[i]$ 可以从 $f[j]$ 转移而来,转移方程为 $f[i] = \\max(f[i], f[j])$。然后我们将第 $i$ 个球员的分数加到 $f[i]$ 中,即 $f[i] += scores[i]$。\n\n最后,我们返回 $\\max_{0 \\leq i < n} f[i]$ 即可。\n\n时间复杂度 $O(n^2)$,空间复杂度 $O(n)$。其中 $n$ 为球员的数量。", "2": "与方法一类似,我们可以将球员按照分数从小到大排序,如果分数相同,则按照年龄从小到大排序。\n\n接下来,我们使用树状数组维护不超过当前球员年龄的球员的最大得分。每一次,我们只需要在 $O(\\log m)$ 的时间内找出不超过当前球员年龄的球员的最大得分,然后将当前球员的分数加到该得分上,即可更新当前球员年龄的最大得分。\n\n最后,我们返回得分的最大值即可。\n\n时间复杂度 $O(n \\times (\\log n + \\log m))$,空间复杂度 $O(n + m)$。其中 $n$ 和 $m$ 分别为球员的数量和球员的年龄的最大值。" }, "is_english": false, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 1627, "explanations": { "1": "We can enumerate $z$ and its multiples, and use union-find to connect them. In this way, for each query $[a, b]$, we only need to determine whether $a$ and $b$ are in the same connected component.\n\nThe time complexity is $O(n \\times \\log n \\times (\\alpha(n) + q))$, and the space complexity is $O(n)$. Here, $n$ and $q$ are the number of nodes and queries, respectively, and $\\alpha$ is the inverse function of the Ackermann function." }, "is_english": true, "time_complexity": "O(n \\times \\log n \\times (\\alpha(n) + q))", "space_complexity": "O(n)" }, { "problem_id": 1628, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1629, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1630, "explanations": { "1": "我们设计一个函数 $check(nums, l, r)$,用于判断子数组 $nums[l], nums[l+1], \\dots, nums[r]$ 是否可以重新排列形成等差数列。\n\n函数 $check(nums, l, r)$ 的实现逻辑如下:\n\n- 首先,我们计算子数组的长度 $n = r - l + 1$,并将子数组中的元素放入集合 $s$ 中,方便后续的查找;\n- 然后,我们获取子数组中的最小值 $a_1$ 和最大值 $a_n$,如果 $a_n - a_1$ 不能被 $n - 1$ 整除,那么子数组不可能形成等差数列,直接返回 $false$;否则,我们计算等差数列的公差 $d = \\frac{a_n - a_1}{n - 1}$;\n- 接下来从 $a_1$ 开始,依次计算等差数列中第 $i$ 项元素,如果第 $i$ 项元素 $a_1 + (i - 1) \\times d$ 不在集合 $s$ 中,那么子数组不可能形成等差数列,直接返回 $false$;否则,当我们遍历完所有的元素,说明子数组可以重新排列形成等差数列,返回 $true$。\n\n在主函数中,我们遍历所有的查询,对于每个查询 $l[i]$ 和 $r[i]$,我们调用函数 $check(nums, l[i], r[i])$ 判断子数组是否可以重新排列形成等差数列,将结果存入答案数组中。\n\n时间复杂度 $O(n \\times m)$,空间复杂度 $O(n)$。其中 $n$ 和 $m$ 分别为数组 $nums$ 的长度以及查询的组数。" }, "is_english": false, "time_complexity": "O(n \\times m)", "space_complexity": "O(n)" }, { "problem_id": 1631, "explanations": { "1": "For this problem, we can treat each cell as a node in a graph, and the absolute difference in height between two adjacent cells as the weight of the edge. Therefore, this problem is to solve the connectivity problem from the top-left node to the bottom-right node.\n\nWe first construct a set of edges, then sort them in ascending order of edge weight, and add edges one by one until the top-left node and the bottom-right node are connected. At this point, the weight of the edge is the minimum physical consumption value required by the problem.\n\nThe time complexity is $O(m \\times n \\times \\log(m \\times n))$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the number of rows and columns in the two-dimensional array, respectively.", "2": "We notice that if the maximum physical consumption value of a path is $x$, then for any $y > x$, this path also meets the conditions. This shows monotonicity, so we can use the binary search method to find the minimum physical consumption value that meets the conditions.\n\nWe define the left boundary of the binary search as $l=0$, and the right boundary as $r=10^6$. Each time we take $mid=(l+r)/2$, then use BFS to determine whether there is a path from the top-left corner to the bottom-right corner, so that the absolute difference in height between adjacent nodes on the path is not greater than $mid$. If it exists, it means that $mid$ may still be the minimum physical consumption value that meets the conditions, so we set $r=mid$, otherwise we set $l=mid+1$.\n\nThe time complexity is $O(m \\times n \\times \\log M)$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the number of rows and columns in the two-dimensional array, respectively, and $M$ is the maximum value in the two-dimensional array. In this problem, $M=10^6$.", "3": "We can treat each cell as a node in a graph, and the absolute difference in height between two adjacent cells as the weight of the edge. Therefore, this problem is to solve the shortest path problem from the top-left node to the bottom-right node.\n\nWe can use the Dijkstra algorithm to solve the shortest path problem, and use a priority queue (heap) to optimize the time complexity. Specifically, we maintain a two-dimensional array $dist$ of size $m \\times n$, where $dist[i][j]$ represents the maximum weight of the shortest path from the top-left corner to the node $(i,j)$. Initially, $dist[0][0]=0$, and all other elements are positive infinity.\n\nWe use a priority queue (heap) to store nodes, and each time we take out the node with the smallest weight from the priority queue (heap), then update the weights of its adjacent nodes. If the weight of an adjacent node changes, then we add this node to the priority queue (heap). When the priority queue (heap) is empty, it means that we have found the shortest path.\n\nThe time complexity is $O(m \\times n \\times \\log(m \\times n))$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the number of rows and columns in the two-dimensional array, respectively." }, "is_english": true, "time_complexity": "O(m \\times n \\times \\log(m \\times n))", "space_complexity": "O(m \\times n)" }, { "problem_id": 1632, "explanations": { "1": "我们先考虑简化情形:没有相同的元素。那么显然最小的元素的秩为 $1$,第二小的元素则要考虑是否和最小元素同行或同列。于是得到贪心解法:从小到大遍历元素,并维护每行、每列的最大秩,该元素的秩即为同行、同列的最大秩加 $1$。见题目:[2371. 最小化网格中的最大值](https://github.com/doocs/leetcode/blob/main/solution/2300-2399/2371.Minimize%20Maximum%20Value%20in%20a%20Grid/README.md)。\n\n存在相同元素时则较为复杂,假设两个相同元素同行(或同列),那么就要考虑到两个元素分别对应的行(或列)的最大秩。同时还可能出现联动,比如元素 `a` 和 `b` 同行,`b` 和 `c` 同列,那么要同时考虑这三个元素。\n\n这种联动容易想到并查集,于是我们用并查集将元素分为几个连通块,对于每个连通块,里面所有元素对应的行或列的最大秩加 $1$,即为该连通块内所有元素的秩。\n\n时间复杂度 $O(m \\times n \\times \\log(m \\times n))$,空间复杂度 $O(m \\times n)$。其中 $m$ 和 $n$ 分别为矩阵的行数和列数。" }, "is_english": false, "time_complexity": "O(m \\times n \\times \\log(m \\times n))", "space_complexity": "O(m \\times n)" }, { "problem_id": 1633, "explanations": { "1": "We can group the `Register` table by `contest_id` and count the number of registrations for each contest. The registration rate of each contest is the number of registrations divided by the total number of registrations." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1634, "explanations": { "1": "我们可以同时遍历两个链表,根据指数大小关系,将节点添加到结果链表中。\n\n最后,如果链表 $1$ 或链表 $2$ 还有剩余节点,将其添加到结果链表中。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为两个链表中节点数的较大值。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1635, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1636, "explanations": { "1": "用数组或者哈希表统计 `nums` 中每个数字出现的次数,由于题目中数字的范围是 $[-100, 100]$,我们可以直接创建一个大小为 $201$ 的数组来统计。\n\n然后对 `nums` 按照数字出现次数升序排序,如果出现次数相同,则按照数字降序排序。\n\n时间复杂度为 $O(n \\times \\log n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 `nums` 的长度。" }, "is_english": false, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1637, "explanations": { "1": "我们可以对数组 $points$ 按照 $x$ 升序排列,获取相邻点之间 $x$ 的差值的最大值。\n\n时间复杂度 $O(n \\times \\log n)$,空间复杂度 $O(\\log n)$。其中 $n$ 为数组 $points$ 的长度。", "2": "方法一中排序的时间复杂度为 $O(n \\times \\log n)$,其实我们可以利用桶排序的思想,将时间复杂度降低到 $O(n)$。\n\n我们将数组 $points$ 的横坐标放入数组 $nums$ 中。\n\n假设数组 $nums$ 有 $n$ 个元素,所有元素从小到大依次是 $nums_0$ 到 $nums_{n - 1}$,最大间距是 $maxGap$。考虑数组中的最大元素和最小元素之差:\n\n$$\nnums_{n - 1} - nums_0 = \\sum_{i = 1}^{n - 1} (nums_i - nums_{i - 1}) \\le{maxGap} \\times (n - 1)\n$$\n\n因此 $maxGap \\ge \\dfrac{nums_{n - 1} - nums_0}{n - 1}$,即最大间距至少为 $\\dfrac{nums_{n - 1} - nums_0}{n - 1}$。\n\n可以利用桶排序的思想,设定桶的大小(即每个桶最多包含的不同元素个数)为 $\\dfrac{nums_{n - 1} - nums_0}{n - 1}$,将元素按照元素值均匀分布到各个桶内,则同一个桶内的任意两个元素之差小于 ${maxGap}$,差为 ${maxGap}$ 的两个元素一定在两个不同的桶内。对于每个桶,维护桶内的最小值和最大值,初始时每个桶内的最小值和最大值分别是正无穷和负无穷,表示桶内没有元素。\n\n遍历数组 ${nums}$ 中的所有元素。对于每个元素,根据该元素与最小元素之差以及桶的大小计算该元素应该分到的桶的编号,可以确保编号小的桶内的元素都小于编号大的桶内的元素,使用元素值更新元素所在的桶内的最小值和最大值。\n\n遍历数组结束之后,每个非空的桶内的最小值和最大值都可以确定。按照桶的编号从小到大的顺序依次遍历每个桶,当前的桶的最小值和上一个非空的桶的最大值是排序后的相邻元素,计算两个相邻元素之差,并更新最大间距。遍历桶结束之后即可得到最大间距。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $points$ 的长度。" }, "is_english": false, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 1638, "explanations": { "1": "我们可以枚举字符串 $s$ 和 $t$ 中不同的那个字符位置,然后分别向两边扩展,直到遇到不同的字符为止,这样就可以得到以该位置为中心的满足条件的子串对数目。我们记左边扩展的相同字符个数为 $l$,右边扩展的相同字符个数为 $r$,那么以该位置为中心的满足条件的子串对数目为 $(l + 1) \\times (r + 1)$,累加到答案中即可。\n\n枚举结束后,即可得到答案。\n\n时间复杂度 $O(m \\times n \\times \\min(m, n))$,空间复杂度 $O(1)$。其中 $m$ 和 $n$ 分别为字符串 $s$ 和 $t$ 的长度。", "2": "方法一中,我们每次需要分别往左右两边扩展,得出 $l$ 和 $r$ 的值。实际上,我们可以预处理出以每个位置 $(i, j)$ 结尾的最长相同后缀的长度,以及以每个位置 $(i, j)$ 开头的最长相同前缀的长度,分别记录在数组 $f$ 和 $g$ 中。\n\n接下来,与方法一类似,我们枚举字符串 $s$ 和 $t$ 中不同的那个字符位置 $(i, j)$,那么以该位置为中心的满足条件的子串对数目为 $(f[i][j] + 1) \\times (g[i + 1][j + 1] + 1)$,累加到答案中即可。\n\n时间复杂度 $O(m \\times n)$,空间复杂度 $O(m \\times n)$。其中 $m$ 和 $n$ 分别为字符串 $s$ 和 $t$ 的长度。" }, "is_english": false, "time_complexity": "O(m \\times n \\times \\min(m, n))", "space_complexity": "O(1)" }, { "problem_id": 1639, "explanations": { "1": "We noticed that the length of each string in the string array $words$ is the same, so let's remember $n$, then we can preprocess a two-dimensional array $cnt$, where $cnt[j][c]$ represents the string array $words$ The number of characters $c$ in the $j$-th position of.\n\nNext, we design a function $dfs(i, j)$, which represents the number of schemes that construct $target[i,..]$ and the currently selected character position from $words$ is $j$. Then the answer is $dfs(0, 0)$.\n\nThe calculation logic of function $dfs(i, j)$ is as follows:\n\n- If $i \\geq m$, it means that all characters in $target$ have been selected, then the number of schemes is $1$.\n- If $j \\geq n$, it means that all characters in $words$ have been selected, then the number of schemes is $0$.\n- Otherwise, we can choose not to select the character in the $j$-th position of $words$, then the number of schemes is $dfs(i, j + 1)$; or we choose the character in the $j$-th position of $words$, then the number of schemes is $dfs(i + 1, j + 1) \\times cnt[j][target[i] - 'a']$.\n\nFinally, we return $dfs(0, 0)$. Note that the answer is taken in modulo operation.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Where $m$ is the length of the string $target$, and $n$ is the length of each string in the string array $words$.", "2": "Similar to Solution 1, we can first preprocess a two-dimensional array $cnt$, where $cnt[j][c]$ represents the number of characters $c$ in the $j$-th position of the string array $words$.\n\nNext, we define $f[i][j]$ which represents the number of ways to construct the first $i$ characters of $target$, and currently select characters from the first $j$ characters of each word in $words$. Then the answer is $f[m][n]$. Initially $f[0][j] = 1$, where $0 \\leq j \\leq n$.\n\nConsider $f[i][j]$, where $i \\gt 0$, $j \\gt 0$. We can choose not to select the character in the $j$-th position of $words$, in which case the number of ways is $f[i][j - 1]$; or we choose the character in the $j$-th position of $words$, in which case the number of ways is $f[i - 1][j - 1] \\times cnt[j - 1][target[i - 1] - 'a']$. Finally, we add the number of ways in these two cases, which is the value of $f[i][j]$.\n\nFinally, we return $f[m][n]$. Note the mod operation of the answer.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Where $m$ is the length of the string $target$, and $n$ is the length of each string in the string array $words$." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 1640, "explanations": { "1": "遍历 `arr`,在 `pieces` 中找到首元素等于当前 `arr[i]` 的数组项,如果找不到,直接返回 `false`。\n\n如果找到了,我们记数组项为 `pieces[k]`,然后继续往后遍历 `arr[i]` 和 `pieces[k]`,直至 `pieces[k]` 遍历完或者元素不等。\n\n遍历结束,返回 `true`。", "2": "创建一个哈希表,键为 `pieces` 中每个数组项的首元素,值为数组项。\n\n遍历 `arr`,如果当前元素在哈希表中不存在,直接返回 `false`;否则,取出哈希表中对应的数组项,判断其与 `arr` 中的元素是否相等,如果不相等,直接返回 `false`。\n\n否则,遍历结束,返回 `true`。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为 `arr` 的长度。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1641, "explanations": { "1": "我们设计一个函数 $dfs(i, j)$,表示当前已经选了 $i$ 个元音字母,且最后一个元音字母是 $j$ 的方案数。那么答案就是 $dfs(0, 0)$。\n\n函数 $dfs(i, j)$ 的计算过程如下:\n\n- 如果 $i \\ge n$,说明已经选了 $n$ 个元音字母,返回 $1$。\n- 否则,枚举 $j$ 后面的元音字母,即 $k \\in [j, 4]$,并将 $dfs(i + 1, k)$ 的结果累加,即 $dfs(i, j) = \\sum_{k = j}^4 dfs(i + 1, k)$。\n\n过程中,我们可以使用记忆化搜索,将已经计算过的 $dfs(i, j)$ 的结果保存起来,避免重复计算。\n\n时间复杂度 $O(n \\times C^2)$,空间复杂度 $O(n \\times C)$。其中 $n$ 为题目给定的整数,而 $C$ 是元音字母的数量,本题中 $C = 5$。", "2": "定义 $f[i][j]$ 表示当前已经选了 $i$ 个元音字母,且最后一个元音字母是 $j$ 的方案数。初始时 $f[1][j]=1$。答案是 $\\sum_{j = 0}^4 f[n][j]$。\n\n我们可以发现 $f[i][j]$ 只与 $f[i - 1][j]$ 有关,因此可以将二维数组压缩为一维数组,从而优化空间复杂度。\n\n时间复杂度 $O(n \\times C)$,空间复杂度 $O(C)$。其中 $n$ 为题目给定的整数,而 $C$ 是元音字母的数量,本题中 $C = 5$。" }, "is_english": false, "time_complexity": "O(n \\times C^2)", "space_complexity": "O(n \\times C)" }, { "problem_id": 1642, "explanations": { "1": "梯子最好用在高度差较大的地方,因此我们可以将所有的高度差存入优先队列中,每次取出最小的高度差,如果梯子不够用,则用砖块填补,如果砖块不够用,则返回当前位置。\n\n时间复杂度 $O(n\\log n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 `heights` 的长度。" }, "is_english": false, "time_complexity": "O(n\\log n)", "space_complexity": "O(n)" }, { "problem_id": 1643, "explanations": { "1": "根据题目描述我们可以知道,最终的路径是由 $destination[0]$ 个 `'V'` 和 $destination[1]$ 个 `'H'` 组成的,且按字典序排列后的第 $k$ 条最小指令。\n\n我们首先考虑字典序的最高位,即最左边的字符。如果高位字符是 `'V'`,那么所有以 `'H'` 开头的路径的字典序都比它小,而以 `'H'` 开头的路径总数为 $x = C_{v+h-1}^{h-1}$。\n\n如果 $k \\lt x$,那么高位字符一定是 `'V'`,我们将 $k$ 减去 $x$,并将 $v$ 减 $1$,然后继续考虑下一位字符;否则,高位字符一定是 `'H'`,我们将 $h$ 减 $1$,然后继续考虑下一位字符。\n\n注意,如果 $h = 0$,那么高位字符一定是 `'V'`,因为剩下的字符都是 `'V'`。\n\n问题可以转换为求解 $C_{n}^{k}$,我们可以通过公式 $C_{n}^{k} = C_{n-1}^{k-1} + C_{n-1}^{k}$ 递推求解。\n\n时间复杂度 $O((h + v) \\times h)$,空间复杂度 $O((h + v) \\times h)$。其中 $h$ 和 $v$ 分别为 $destination[1]$ 和 $destination[0]$。" }, "is_english": false, "time_complexity": "O((h + v) \\times h)", "space_complexity": "O((h + v) \\times h)" }, { "problem_id": 1644, "explanations": { "1": "我们设计一个函数 $dfs(root, p, q)$,该函数返回以 $root$ 为根节点的二叉树中是否包含节点 $p$ 或节点 $q$,如果包含,则返回 `true`,否则返回 `false`。\n\n函数 $dfs(root, p, q)$ 的递归过程如下:\n\n如果当前节点 $root$ 为空,则返回 `false`。\n\n否则,我们递归地遍历左子树和右子树,得到 $l$ 和 $r$,分别表示左子树和右子树中是否包含节点 $p$ 或节点 $q$。\n\n如果 $l$ 和 $r$ 都为 `true`,说明当前节点 $root$ 就是我们要找的最近公共祖先节点,将其赋值给变量 $ans$。\n\n如果 $l$ 或 $r$ 为 `true`,并且当前节点 $root$ 的值等于节点 $p$ 或节点 $q$ 的值,说明当前节点 $root$ 就是我们要找的最近公共祖先节点,将其赋值给变量 $ans$。\n\n最后,我们判断 $l$ 或 $r$ 是否为 `true`,或者当前节点 $root$ 的值是否等于节点 $p$ 或节点 $q$ 的值,如果是,则返回 `true`,否则返回 `false`。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点个数。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1645, "explanations": { "1": "我们可以使用递归的方法生成 $1 \\sim 12$ 月的数据,记录在 `Month` 表中。\n\n接下来,我们用 `Month` 表与 `Drivers` 表进行左连接,连接的条件是 `year(d.join_date) < 2020 or (year(d.join_date) = 2020 and month(d.join_date) <= month)`,这样就可以得到每个月的活跃司机数。\n\n然后,我们再用 `Rides` 表与 `AcceptedRides` 表进行内连接,连接的条件是 `ride_id` 相等,并且我们只查出 `year(requested_at) = 2020` 的数据,这样就可以得到 $2020$ 年被接受的所有行程。\n\n最后,我们将上面两个表进行左连接,连接的条件是 `month` 相等、`driver_id` 相等,并且 `join_date` 小于等于 `requested_at`,这样就可以得到每个月被接受的行程数,按月份进行分组,就可以得到每个月的活跃司机数和被接受的行程数,从而计算出每个月的接单率。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1646, "explanations": { "1": "我们先判断 $n$ 的值,如果 $n < 2$,则直接返回 $n$。\n\n否则,我们创建一个长度为 $n + 1$ 的数组 $nums$,并初始化 $nums[0] = 0$ 以及 $nums[1] = 1$。\n\n然后从下标 $2$ 开始遍历,如果当前下标 $i$ 为偶数,则 $nums[i] = nums[i / 2]$,否则 $nums[i] = nums[i / 2] + nums[i / 2 + 1]$。\n\n最后返回数组 $nums$ 中的最大值即可。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为给定的整数。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1647, "explanations": { "1": "First, we use an array $\\textit{cnt}$ of length $26$ to count the occurrences of each letter in the string $s$.\n\nThen, we sort the array $\\textit{cnt}$ in descending order. We define a variable $\\textit{pre}$ to record the current number of occurrences of the letter.\n\nNext, we traverse each element $v$ in the array $\\textit{cnt}$. If the current $\\textit{pre}$ is $0$, we directly add $v$ to the answer. Otherwise, if $v \\geq \\textit{pre}$, we add $v - \\textit{pre} + 1$ to the answer and decrement $\\textit{pre}$ by $1$. Otherwise, we directly update $\\textit{pre}$ to $v$. Then, we continue to the next element.\n\nAfter traversing, we return the answer.\n\nThe time complexity is $O(n + |\\Sigma| \\times \\log |\\Sigma|)$, and the space complexity is $O(|\\Sigma|)$. Here, $n$ is the length of the string $s$, and $|\\Sigma|$ is the size of the alphabet. In this problem, $|\\Sigma| = 26$.", "2": "" }, "is_english": true, "time_complexity": "O(n + |\\Sigma| \\times \\log |\\Sigma|)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 1648, "explanations": { "1": "要使得总价值最大,我们可以贪心地每次卖出数量最多的一种颜色的球。由于 `orders` 值域较大,如果直接简单地模拟,会超时。因此,我们需要优化模拟的过程。\n\n实际上,我们不需要一次次进行模拟,我们可以跟踪数量最多的同色球的种类数 `cnt`,每一次可以卖出一批球,从而达到加速模拟的目的。\n\n时间复杂度 $O(n\\log n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 `inventory` 的长度。" }, "is_english": false, "time_complexity": "O(n\\log n)", "space_complexity": "O(1)" }, { "problem_id": 1649, "explanations": { "1": "树状数组,也称作“二叉索引树”(Binary Indexed Tree)或 Fenwick 树。 它可以高效地实现如下两个操作:\n\n1. **单点更新** `update(x, delta)`: 把序列 x 位置的数加上一个值 delta;\n1. **前缀和查询** `query(x)`:查询序列 `[1,...x]` 区间的区间和,即位置 x 的前缀和。\n\n这两个操作的时间复杂度均为 $O(\\log n)$。\n\n树状数组最基本的功能就是求比某点 x 小的点的个数(这里的比较是抽象的概念,可以是数的大小、坐标的大小、质量的大小等等)。\n\n比如给定数组 `a[5] = {2, 5, 3, 4, 1}`,求 `b[i] = 位置 i 左边小于等于 a[i] 的数的个数`。对于此例,`b[5] = {0, 1, 1, 2, 0}`。\n\n解决方案是直接遍历数组,每个位置先求出 `query(a[i])`,然后再修改树状数组 `update(a[i], 1)` 即可。当数的范围比较大时,需要进行离散化,即先进行去重并排序,然后对每个数字进行编号。", "2": "线段树将整个区间分割为多个不连续的子区间,子区间的数量不超过 `log(width)`。更新某个元素的值,只需要更新 `log(width)` 个区间,并且这些区间都包含在一个包含该元素的大区间内。\n\n- 线段树的每个节点代表一个区间;\n- 线段树具有唯一的根节点,代表的区间是整个统计范围,如 `[1, N]`;\n- 线段树的每个叶子节点代表一个长度为 1 的元区间 `[x, x]`;\n- 对于每个内部节点 `[l, r]`,它的左儿子是 `[l, mid]`,右儿子是 `[mid + 1, r]`, 其中 `mid = ⌊(l + r) / 2⌋` (即向下取整)。\n\n> 本题线段树 Python3 代码 TLE,Java、C++ 代码 AC。" }, "is_english": false, "time_complexity": "O(\\log n)", "space_complexity": null }, { "problem_id": 1650, "explanations": { "1": "We use a hash table $vis$ to record all nodes on the path from node $p$ to the root node. Then we start from node $q$ and traverse towards the root node. If we encounter a node that exists in the hash table $vis$, then this node is the nearest common ancestor of $p$ and $q$, and we can return it directly.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree.", "2": "We can use two pointers $a$ and $b$ to point to nodes $p$ and $q$ respectively, and then traverse towards the root node. When $a$ and $b$ meet, it is the nearest common ancestor of $p$ and $q$. Otherwise, if pointer $a$ traverses to the root node, then we let it point to node $q$, and do the same for pointer $b$. In this way, when the two pointers meet, it is the nearest common ancestor of $p$ and $q$.\n\nThe time complexity is $O(n)$, where $n$ is the number of nodes in the binary tree. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1651, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1652, "explanations": { "1": "We define an answer array `ans` of length `n`, initially all elements are `0`. According to the problem, if `k` is `0`, return `ans` directly.\n\nOtherwise, we traverse each position `i`:\n\n- If `k` is a positive number, then the value at position `i` is the sum of the values at the `k` positions after position `i`, that is:\n\n$$\nans[i] = \\sum_{j=i+1}^{i+k} code[j \\bmod n]\n$$\n\n- If `k` is a negative number, then the value at position `i` is the sum of the values at the `|k|` positions before position `i`, that is:\n\n$$\nans[i] = \\sum_{j=i+k}^{i-1} code[(j+n) \\bmod n]\n$$\n\nThe time complexity is $O(n \\times |k|)$, ignoring the space consumption of the answer, the space complexity is $O(1)$.", "2": "In Solution 1, for each position $i$, we need to traverse $k$ positions, which involves a lot of repeated calculations. We can optimize this by using prefix sums.\n\nWe duplicate the `code` array (this can be achieved without actually duplicating the array, but by cyclically traversing with modulo operation), resulting in an array of twice the length. We then calculate the prefix sum of this array, resulting in a prefix sum array $s$ of length $2 \\times n + 1$.\n\nIf $k$ is a positive number, then the value at position $i$ is the sum of the values at the $k$ positions after position $i$, i.e., $ans[i] = s[i + k + 1] - s[i + 1]$.\n\nIf $k$ is a negative number, then the value at position $i$ is the sum of the values at the $|k|$ positions before position $i$, i.e., $ans[i] = s[i + n] - s[i + k + n]$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the `code` array." }, "is_english": true, "time_complexity": "O(n \\times |k|)", "space_complexity": "O(1)" }, { "problem_id": 1653, "explanations": { "1": "We define $f[i]$ as the minimum number of characters to be deleted in the first $i$ characters to make the string balanced. Initially, $f[0]=0$. The answer is $f[n]$.\n\nWe traverse the string $s$, maintaining a variable $b$, which represents the number of character 'b' in the characters before the current position.\n\n- If the current character is 'b', it does not affect the balance of the first $i$ characters, so $f[i]=f[i-1]$, then we update $b \\leftarrow b+1$.\n- If the current character is 'a', we can choose to delete the current character, so $f[i]=f[i-1]+1$; or we can choose to delete the previous character 'b', so $f[i]=b$. Therefore, we take the minimum of the two, that is, $f[i]=\\min(f[i-1]+1,b)$.\n\nIn summary, we can get the state transition equation:\n\n$$\nf[i]=\\begin{cases}\nf[i-1], & s[i-1]='b'\\\\\n\\min(f[i-1]+1,b), & s[i-1]='a'\n\\end{cases}\n$$\n\nThe final answer is $f[n]$.\n\nWe notice that the state transition equation is only related to the previous state and the variable $b$, so we can just use an answer variable $ans$ to maintain the current $f[i]$, and there is no need to allocate an array $f$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$.", "2": "We can enumerate each position $i$ in the string $s$, dividing the string $s$ into two parts, namely $s[0,..,i-1]$ and $s[i+1,..n-1]$. To make the string balanced, the number of characters we need to delete at the current position $i$ is the number of character 'b' in $s[0,..,i-1]$ plus the number of character 'a' in $s[i+1,..n-1]$.\n\nTherefore, we maintain two variables $lb$ and $ra$ to represent the number of character 'b' in $s[0,..,i-1]$ and the number of character 'a' in $s[i+1,..n-1]$ respectively. The number of characters we need to delete is $lb+ra$. During the enumeration process, we update the variables $lb$ and $ra$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1654, "explanations": { "1": "We can use the position and jumping direction of the flea as the state, and use BFS to search for the shortest path. The key point of this problem is to determine the right boundary, that is, how far the flea can jump.\n\nIf $a \\geq b$, that is, the distance to jump forward is greater than the distance to jump backward, then if the flea is in a position greater than $x+b$, it can no longer jump forward, because the flea cannot jump backward consecutively. If it continues to jump forward, it will never be able to jump to the position $x$. Therefore, if $a \\geq b$, the right boundary can be $x+b$.\n\nIf $a < b$, that is, the distance to jump forward is less than the distance to jump backward, then if the position of the flea minus $b$ exceeds $2000$, choose to jump backward, otherwise jump forward. Therefore, if $a < b$, the right boundary does not exceed $6000$.\n\nIn summary, we can set the right boundary to $6000$.\n\nNext, we use BFS to search for the shortest path. We use a queue, initially adding the position and jumping direction of the flea as the state to the queue. Each time we take a state from the queue, if the position of this state is equal to $x$, then we have found a path from the initial state to the target state, and we can return the current number of steps. Otherwise, we add the next state of the current state to the queue. There are two cases for the next state:\n\n- Jump forward, the jumping direction is $1$;\n- When the current jumping direction is $1$, jump backward, the jumping direction is $0$.\n\nNote that we need to judge whether the next state is legal, that is, the position of the next state does not exceed the right boundary, is not in the forbidden position, and has not been visited.\n\nIf the queue is empty, it means that the target position cannot be reached, return $-1$.\n\nThe time complexity is $O(M)$, and the space complexity is $O(M)$. Here, $M$ is the right boundary, and in this problem, $M \\leq 6000$." }, "is_english": true, "time_complexity": "O(M)", "space_complexity": "O(M)" }, { "problem_id": 1655, "explanations": { "1": "First, we count the occurrence of each number in the array `nums`, and record it in the hash table `cnt`. Then we store the values in the hash table into the array `arr`. We denote the length of the array `arr` as `n`.\n\nNote that the length of the array `quantity` does not exceed 10, so we can use a binary number to represent a subset of `quantity`. That is, the number `j` represents a subset of `quantity`, where the `i`-th bit of the binary representation of `j` is `1` means the `i`-th number in `quantity` is selected, and `0` means the `i`-th number is not selected.\n\nWe can preprocess an array `s`, where `s[j]` represents the sum of all numbers in the subset `j` of `quantity`.\n\nNext, we define `f[i][j]` to represent whether the numbers in `arr[0,..i-1]` can be successfully allocated to the subset `j` of `quantity`, where `i` ranges from `[0,..n-1]`, and `j` ranges from `[0,2^m-1]`, where `m` is the length of `quantity`.\n\nConsidering `f[i][j]`, if there exists a subset `k` in `j` such that `s[k] <= arr[i]`, and `f[i-1][j XOR k]` is true, then `f[i][j]` is true, otherwise `f[i][j]` is false.\n\nThe answer is `f[n-1][2^m-1]`.\n\nThe time complexity is `O(n * 3^m)`, and the space complexity is `O(n * 2^m)`. Here, `n` is the number of different integers in the array `nums`, and `m` is the length of the array `quantity`." }, "is_english": true, "time_complexity": "O(n * 3^m)", "space_complexity": "O(n * 2^m)" }, { "problem_id": 1656, "explanations": { "1": "We can use an array $\\textit{data}$ of length $n + 1$ to simulate this stream, where $\\textit{data}[i]$ represents the value of $\\textit{id} = i$. At the same time, we use a pointer $\\textit{ptr}$ to represent the current position. Initially, $\\textit{ptr} = 1$.\n\nWhen inserting a new $(\\textit{idKey}, \\textit{value})$ pair, we update $\\textit{data}[\\textit{idKey}]$ to $\\textit{value}$. Then, starting from $\\textit{ptr}$, we sequentially add $\\textit{data}[\\textit{ptr}]$ to the answer until $\\textit{data}[\\textit{ptr}]$ is empty.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the data stream." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1657, "explanations": { "1": "According to the problem description, two strings are close if they meet the following two conditions simultaneously:\n\n1. The strings `word1` and `word2` must contain the same types of letters.\n2. The arrays obtained by sorting the counts of all characters in `word1` and `word2` must be the same.\n\nTherefore, we can first use an array or hash table to count the occurrences of each letter in `word1` and `word2` respectively, and then compare whether they are the same. If they are not the same, return `false` early.\n\nOtherwise, we sort the corresponding counts, and then compare whether the counts at the corresponding positions are the same. If they are not the same, return `false`.\n\nAt the end of the traversal, return `true`.\n\nThe time complexity is $O(m + n + C \\times \\log C)$, and the space complexity is $O(C)$. Here, $m$ and $n$ are the lengths of the strings `word1` and `word2` respectively, and $C$ is the number of letter types. In this problem, $C=26$." }, "is_english": true, "time_complexity": "O(m + n + C \\times \\log C)", "space_complexity": "O(C)" }, { "problem_id": 1658, "explanations": { "1": "According to the problem description, we need to remove elements from both ends of the array $nums$ so that the sum of the removed elements equals $x$, and the number of removed elements is minimized. We can transform the problem into: find the longest consecutive subarray in the array $nums$ such that the sum of the subarray $s = \\sum_{i=0}^{n} nums[i] - x$. In this way, we can transform the problem into finding the length $mx$ of the longest consecutive subarray in the array $nums$ with a sum of $s$, and the answer is $n - mx$.\n\nWe initialize $mx = -1$, and then use a hash table $vis$ to store the prefix sum, where the key is the prefix sum and the value is the index corresponding to the prefix sum.\n\nTraverse the array $nums$, for the current element $nums[i]$, calculate the prefix sum $t$, if $t$ is not in the hash table, add $t$ to the hash table; if $t - s$ is in the hash table, update $mx = \\max(mx, i - vis[t - s])$.\n\nFinally, if $mx = -1$, return $-1$, otherwise return $n - mx$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $nums$.", "2": "Based on the analysis of Solution 1, we need to find the length $mx$ of the longest consecutive subarray in the array $nums$ with a sum of $s$. Since all elements in the array $nums$ are positive integers, the prefix sum of the array will only increase monotonically, so we can use two pointers to solve this problem.\n\nWe initialize pointer $j = 0$, prefix sum $t = 0$, and the length of the longest consecutive subarray $mx = -1$.\n\nTraverse the array $nums$, for the current element $nums[i]$, calculate the prefix sum $t += nums[i]$. If $t > s$, then move the pointer $j$ until $t \\leq s$. If $t = s$, then update $mx = \\max(mx, i - j + 1)$.\n\nFinally, if $mx = -1$, return $-1$, otherwise return $n - mx$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1659, "explanations": { "1": "We notice that in the problem, $1 \\leq m, n \\leq 5$, and each grid cell has three states: no personnel assigned, introverted personnel assigned, and extroverted personnel assigned. Therefore, we can use $0$, $1$, $2$ to represent these three states, and each row in the grid can be represented by a ternary number of length $n$.\n\nWe define a function $dfs(i, pre, ic, ec)$, which represents the maximum happiness of the grid starting from the $i$-th row, with the state of the previous row being $pre$, $ic$ introverted people left, and $ec$ extroverted people left. The answer is $dfs(0, 0, introvertsCount, extrovertsCount)$.\n\nThe calculation process of the function $dfs(i, pre, ic, ec)$ is as follows:\n\nIf $i = m$, it means that all rows have been processed, so return $0$;\n\nIf $ic = 0$ and $ec = 0$, it means that all people have been assigned, so return $0$;\n\nOtherwise, enumerate the current row's state $cur$, where $cur \\in [0, 3^n)$, then calculate the happiness $f[cur]$ of the current row, and the contribution $g[pre][cur]$ to the happiness between the state $pre$ of the previous row, and recursively calculate $dfs(i + 1, cur, ic - ix[cur], ec - ex[cur])$, finally return the maximum value of $f[cur] + g[pre][cur] + dfs(i + 1, cur, ic - ix[cur], ec - ex[cur])$, that is:\n\n$$\ndfs(i, pre, ic, ec) = \\max_{cur} \\{f[cur] + g[pre][cur] + dfs(i + 1, cur, ic - ix[cur], ec - ex[cur])\\}\n$$\n\nWhere:\n\n- $ix[cur]$ represents the number of introverted people in state $cur$;\n- $ex[cur]$ represents the number of extroverted people in state $cur$;\n- $f[cur]$ represents the initial happiness of the people in state $cur$;\n- $g[pre][cur]$ represents the contribution to happiness of two adjacent state rows.\n\nThese values can be obtained through preprocessing. And we can use the method of memoization to avoid repeated calculations.\n\nThe time complexity is $O(3^{2n} \\times (m \\times ic \\times ec + n))$, and the space complexity is $O(3^{2n} + 3^n \\times m \\times ic \\times ec)$. Where $ic$ and $ec$ represent the number of introverted and extroverted people, respectively.", "2": "We can consider searching each grid cell, each time searching a position $(i, j)$, we denote $pos = i \\times n + j$. Then its left and upper adjacent grids will affect their happiness contribution.\n\nWe define a function $dfs(pos, pre, ic, ec)$, which represents the maximum happiness of the grid when we search to position $pos$, and the state of the previous $n$ grid cells is $pre$, with $ic$ introverted people left, and $ec$ extroverted people left. The answer is $dfs(0, 0, introvertsCount, extrovertsCount)$.\n\nThe calculation process of the function $dfs(pos, pre, ic, ec)$ is as follows:\n\nIf $pos = m \\times n$, it means that all grid cells have been processed, so return $0$;\n\nIf $ic = 0$ and $ec = 0$, it means that all people have been assigned, so return $0$;\n\nOtherwise, we calculate the state $up = \\frac{pre}{3^{n-1}}$ of the upper adjacent grid cell of the current grid cell based on $pre$, and the state $left = pre \\bmod 3$ of the left adjacent grid cell (note that if $pos$ is in the $0$-th column, then $left = 0$).\n\nNext, we enumerate the state $i$ of the current grid cell, where $i \\in [0, 3)$. Then the state of the current $n$ grid cells is $cur = pre \\bmod 3^{n-1} \\times 3 + i$, and the happiness contribution of the current grid cell and its left and upper adjacent grid cells is $h[up][i]+h[left][i]$; the happiness of the current grid cell itself depends on whether personnel are assigned to this position, and whether the assigned personnel are introverted or extroverted. If they are introverted, the happiness is $120$, if they are extroverted, the happiness is $40$, otherwise, the happiness is $0$; then, if personnel are assigned to the current grid cell, we need to update $ic$ or $ec$ when we recursively call the function. Accumulate these happiness values, and take the maximum value as the return value of the function.\n\nSimilar to Solution 1, we can also use the method of memoization to avoid repeated calculations.\n\nThe time complexity is $O(3^{n+1} \\times m \\times n \\times ic \\times ec)$, and the space complexity is $O(3^n \\times m \\times n \\times ic \\times ec)$. Where $ic$ and $ec$ represent the number of introverted and extroverted people, respectively." }, "is_english": true, "time_complexity": "O(3^{2n} \\times (m \\times ic \\times ec + n))", "space_complexity": "O(3^{2n} + 3^n \\times m \\times ic \\times ec)" }, { "problem_id": 1660, "explanations": { "1": "We design a function `dfs(root)` to handle the subtree with `root` as the root. If `root` is `null` or `root.right` has been visited, `root` is an invalid node, so we return `null`. Otherwise, we recursively process `root.right` and `root.left`, and return `root`.\n\nFinally, we return `dfs(root)`.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1661, "explanations": { "1": "We can group by `machine_id` and use the `AVG` function to calculate the average time consumption of all process tasks on each machine. Since each process task on the machine has a pair of start and end timestamps, the time consumption of each process task can be calculated by subtracting the `start` timestamp from the `end` timestamp. Therefore, we can use the `CASE WHEN` or `IF` function to calculate the time consumption of each process task, and then use the `AVG` function to calculate the average time consumption of all process tasks on each machine.\n\nNote that each machine has $2$ process tasks, so we need to multiply the calculated average time consumption by $2$.", "2": "" }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1662, "explanations": { "1": "Concatenate the strings in the two arrays into two strings, then compare whether the two strings are equal.\n\nThe time complexity is $O(m)$, and the space complexity is $O(m)$. Here, $m$ is the total length of the strings in the arrays.", "2": "In Solution 1, we concatenated the strings in the two arrays into two new strings, which has additional space overhead. We can also directly traverse the two arrays and compare the characters one by one.\n\nWe use two pointers $i$ and $j$ to point to the two string arrays, and another two pointers $x$ and $y$ to point to the corresponding characters in the strings. Initially, $i = j = x = y = 0$.\n\nEach time we compare $word1[i][x]$ and $word2[j][y]$. If they are not equal, we directly return `false`. Otherwise, we increment $x$ and $y$ by $1$. If $x$ or $y$ exceeds the length of the corresponding string, we increment the corresponding string pointer $i$ or $j$ by $1$, and then reset $x$ and $y$ to $0$.\n\nIf both string arrays are traversed, we return `true`, otherwise, we return `false`.\n\nThe time complexity is $O(m)$, and the space complexity is $O(1)$. Here, $m$ is the total length of the strings in the arrays." }, "is_english": true, "time_complexity": "O(m)", "space_complexity": "O(m)" }, { "problem_id": 1663, "explanations": { "1": "First, we initialize each character of the string to `'a'`, leaving a remaining value of $d=k-n$.\n\nThen, we traverse the string from back to front. In each iteration, we greedily replace the current character with the character `'z'` that can minimize the remaining number, until the remaining number does not exceed $25$. Finally, we add the remaining number to the position we have traversed.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string. Ignoring the space consumption of the answer, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1664, "explanations": { "1": "First, we preprocess to get the sum $s_1$ of the elements at even indices and the sum $s_2$ of the elements at odd indices in the array `nums`.\n\nThen, we enumerate each element $v$ in the array `nums` from front to back, using variables $t_1$ and $t_2$ to record the sum of the elements at even indices and the sum of the elements at odd indices that have been traversed, respectively.\n\nWe observe that for the current element $v$ being traversed, if it is removed, the sum of the elements at odd and even indices after this element will be swapped. At this point, we first determine whether the index $i$ of the current position is odd or even.\n\n- If it is an even index, after deleting the element, the sum of the elements at odd indices in the array is $t_2 + s_1 - t_1 - v$, and the sum of the elements at even indices is $t_1 + s_2 - t_2$. If these two sums are equal, it is a balanced array, and the answer is incremented by one.\n\n- If it is an odd index, after deleting the element, the sum of the elements at even indices in the array is $t_1 + s_2 - t_2 - v$, and the sum of the elements at odd indices is $t_2 + s_1 - t_1$. If these two sums are equal, it is a balanced array, and the answer is incremented by one.\n\nThen we update $t_1$ and $t_2$ and continue to traverse the next element. After traversing the array, we can get the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1665, "explanations": { "1": "Assume the number of tasks is $n$ and the initial energy level is $E$. Consider completing the last task. This requires that after completing the first $n-1$ tasks, the remaining energy level is not less than the energy level required to complete the last task $m_n$, i.e.,\n\n$$\nE-\\sum_{i=1}^{n-1} a_i \\geq m_n\n$$\n\nWe can express $m_n$ as $a_n+(m_n - a_n)$, and then transform the above formula to get:\n\n$$\nE-\\sum_{i=1}^{n-1} a_i \\geq a_n+(m_n - a_n)\n$$\n\nRearranging, we get:\n\n$$\nE \\geq \\sum_{i=1}^{n} a_i + (m_n - a_n)\n$$\n\nWhere $\\sum_{i=1}^{n} a_i$ is fixed. To minimize the initial energy level $E$, we need to minimize $m_n - a_n$, i.e., maximize $a_n-m_n$.\n\nTherefore, we can sort the tasks in ascending order of $a_i-m_i$. Then we traverse the tasks from front to back. For each task, if the current energy level $cur$ is less than $m_i$, we need to increase the energy level by $m_i - cur$ to make the current energy level exactly equal to $m_i$. Then we complete the task and update $cur = cur - a_i$. Continue traversing until all tasks are completed, and we can get the minimum initial energy level required.\n\nThe time complexity is $O(n\\times \\log n)$, where $n$ is the number of tasks. Ignoring the space overhead of sorting, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n\\times \\log n)", "space_complexity": "O(1)" }, { "problem_id": 1666, "explanations": { "1": "从叶节点 `leaf` 开始,向上模拟翻转操作。\n\n时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为二叉树节点个数。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1667, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1668, "explanations": { "1": "注意到字符串长度不超过 $100$,我们直接从大到小枚举 `word` 的重复次数 $k$,判断 `word` 重复该次数后是否是 `sequence` 的子串,是则直接返回当前的重复次数 $k$。\n\n时间复杂度为 $O(n^2)$,其中 $n$ 为 `sequence` 的长度。" }, "is_english": false, "time_complexity": "O(n^2)", "space_complexity": null }, { "problem_id": 1669, "explanations": { "1": "We can directly simulate the operations described in the problem.\n\nIn the implementation, we use two pointers $p$ and $q$, both initially pointing to the head node of `list1`.\n\nThen we move pointers $p$ and $q$ forward, until pointer $p$ points to the node before the $a$-th node in `list1`, and pointer $q$ points to the $b$-th node in `list1`. At this point, we set the `next` pointer of $p$ to the head node of `list2`, and set the `next` pointer of the tail node of `list2` to the node pointed to by the `next` pointer of $q$. This completes the operation required by the problem.\n\nThe time complexity is $O(m + n)$, and the space complexity is $O(1)$. Where $m$ and $n$ are the lengths of `list1` and `list2` respectively." }, "is_english": true, "time_complexity": "O(m + n)", "space_complexity": "O(1)" }, { "problem_id": 1670, "explanations": { "1": "We use two deques, where $q_1$ stores the first half, and $q_2$ stores the second half. The `rebalance` function is used to maintain the balance between the two queues, i.e., keeping the length of $q_2$ greater than or equal to the length of $q_1$, and the difference in length does not exceed $1$.\n\nIn the `pushFront`, `pushMiddle`, and `pushBack` functions, we only need to add elements to $q_1$ or $q_2$, and call the `rebalance` function.\n\nFor the `popFront` function, we need to check whether $q_1$ and $q_2$ are empty. If both are empty, return $-1$. Otherwise, we need to check whether $q_1$ is empty. If not, pop the front element of $q_1$, otherwise pop the front element of $q_2$, and call the `rebalance` function.\n\nFor the `popMiddle` function, we need to check whether $q_1$ and $q_2$ are empty. If both are empty, return $-1$. Otherwise, we need to check whether the lengths of $q_1$ and $q_2$ are equal. If they are equal, pop the last element of $q_1$, otherwise pop the front element of $q_2$, and call the `rebalance` function.\n\nFor the `popBack` function, we only need to check whether $q_2$ is empty. If it is empty, return $-1$. Otherwise, pop the last element of $q_2$, and call the `rebalance` function.\n\nThe time complexity of the above operations is $O(1)$, and the space complexity is $O(n)$, where $n$ is the number of elements in the queue." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(n)" }, { "problem_id": 1671, "explanations": { "1": "This problem can be transformed into finding the longest increasing subsequence and the longest decreasing subsequence.\n\nWe define $left[i]$ as the length of the longest increasing subsequence ending with $nums[i]$, and define $right[i]$ as the length of the longest decreasing subsequence starting with $nums[i]$.\n\nThen the final answer is $n - \\max(left[i] + right[i] - 1)$, where $1 \\leq i \\leq n$, and $left[i] \\gt 1$ and $right[i] \\gt 1$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 1672, "explanations": { "1": "We traverse `accounts` and find the maximum sum of each row.\n\nThe time complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns in the grid, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(1)" }, { "problem_id": 1673, "explanations": { "1": "We traverse the array `nums` from left to right, maintaining a stack `stk`. During the traversal, if the current element `nums[i]` is less than the top element of the stack, and the number of elements in the stack plus $n-i$ is greater than $k$, then we pop the top element of the stack until the above condition is no longer satisfied. At this point, if the number of elements in the stack is less than $k$, then we push the current element into the stack.\n\nAfter the traversal, the elements in the stack are the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(k)$. Where $n$ is the length of the array `nums`." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(k)" }, { "problem_id": 1674, "explanations": { "1": "Assume that in the final array, the sum of the pair $\\textit{nums}[i]$ and $\\textit{nums}[n-i-1]$ is $s$.\n\nLet's denote $x$ as the smaller value between $\\textit{nums}[i]$ and $\\textit{nums}[n-i-1]$, and $y$ as the larger value.\n\nFor each pair of numbers, we have the following scenarios:\n\n- If no replacement is needed, then $x + y = s$.\n- If one replacement is made, then $x + 1 \\le s \\le y + \\textit{limit}$.\n- If two replacements are made, then $2 \\le s \\le x$ or $y + \\textit{limit} + 1 \\le s \\le 2 \\times \\textit{limit}$.\n\nThat is:\n\n- In the range $[2,..x]$, $2$ replacements are needed.\n- In the range $[x+1,..x+y-1]$, $1$ replacement is needed.\n- At $[x+y]$, no replacement is needed.\n- In the range $[x+y+1,..y + \\textit{limit}]$, $1$ replacement is needed.\n- In the range $[y + \\textit{limit} + 1,..2 \\times \\textit{limit}]$, $2$ replacements are needed.\n\nWe enumerate each pair of numbers and use a difference array to update the number of replacements needed in different ranges for each pair.\n\nFinally, we find the minimum value among the prefix sums from index $2$ to $2 \\times \\textit{limit}$, which is the minimum number of replacements needed.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$.\n\nSimilar problems:\n\n- [3224. Minimum Array Changes to Make Differences Equal](https://github.com/doocs/leetcode/blob/main/solution/3200-3299/3224.Minimum%20Array%20Changes%20to%20Make%20Differences%20Equal/README_EN.md)" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1675, "explanations": { "1": "Intuitively, to get the minimum offset of the array, we need to decrease the maximum value of the array and increase the minimum value of the array.\n\nSince there are two operations that can be performed each time: multiply an odd number by $2$; divide an even number by $2$, the situation is more complex. We can multiply all odd numbers by $2$ to convert them into even numbers, which is equivalent to having only one division operation. The division operation can only reduce a certain number, and only by reducing the maximum value can the result be more optimal.\n\nTherefore, we use a priority queue (max heap) to maintain the maximum value of the array. Each time we take out the top element of the heap for division operation, put the new value into the heap, and update the minimum value and the minimum value of the difference between the top element of the heap and the minimum value.\n\nWhen the top element of the heap is an odd number, the operation stops.\n\nThe time complexity is $O(n\\log n \\times \\log m)$. Where $n$ and $m$ are the length of the array `nums` and the maximum element of the array, respectively. Since the maximum element in the array is divided by $2$ at most $O(\\log m)$ times, all elements are divided by $2$ at most $O(n\\log m)$ times. Each time the heap is popped and put into operation, the time complexity is $O(\\log n)$. Therefore, the total time complexity is $O(n\\log n \\times \\log m)$." }, "is_english": true, "time_complexity": "O(n\\log n \\times \\log m)", "space_complexity": null }, { "problem_id": 1676, "explanations": { "1": "We use a hash table $\\textit{s}$ to record the values of all nodes in the array $\\textit{nodes}$, and then use depth-first search. When the node being traversed is null or its value is in the hash table $\\textit{s}$, we return the current node. Otherwise, we recursively traverse the left and right subtrees. If the return values of both the left and right subtrees are not null, it means the current node is the lowest common ancestor. Otherwise, we return the non-null subtree's return value.\n\nThe time complexity is $O(n + m)$, and the space complexity is $O(n + m)$. Where $n$ and $m$ are the number of nodes in the binary tree and the length of the array $\\textit{nodes}$, respectively." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(n + m)" }, { "problem_id": 1677, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1678, "explanations": { "1": "According to the problem, we only need to replace `\"()\"` with `'o'` and `\"(al)\"` with `\"al\"` in the string `command`.", "2": "We can also iterate over the string `command`. For each character $c$:\n\n- If it is `'G'`, directly add $c$ to the result string;\n- If it is `'('`, check if the next character is `')'`. If it is, add `'o'` to the result string. Otherwise, add `\"al\"` to the result string.\n\nAfter the iteration, return the result string.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1679, "explanations": { "1": "We sort $nums$. Then $l$ and $r$ point to the first and last elements of $nums$ respectively, and we compare the sum $s$ of the two integers with $k$.\n\n- If $s = k$, it means that we have found two integers whose sum is $k$. We increment the answer and then move $l$ and $r$ towards the middle;\n- If $s > k$, then we move the $r$ pointer to the left;\n- If $s < k$, then we move the $l$ pointer to the right;\n- We continue the loop until $l \\geq r$.\n\nAfter the loop ends, we return the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of $nums$.", "2": "We use a hash table $cnt$ to record the current remaining integers and their occurrence counts.\n\nWe iterate over $nums$. For the current integer $x$, we check if $k - x$ is in $cnt$. If it exists, it means that we have found two integers whose sum is $k$. We increment the answer and then decrement the occurrence count of $k - x$; otherwise, we increment the occurrence count of $x$.\n\nAfter the iteration ends, we return the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of $nums$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 1680, "explanations": { "1": "By observing the pattern of number concatenation, we can find that when concatenating to the $i$-th number, the result $ans$ formed by concatenating the previous $i-1$ numbers is actually shifted to the left by a certain number of bits, and then $i$ is added. The number of bits shifted is the number of binary digits in $i$.\n\nThe time complexity is $O(n)$, where $n$ is the given integer. The space complexity is $O(1)$.", "2": "In Solution 1, we need to calculate the number of binary digits of $i$ each time, which adds some extra computation. We can use a variable $\\textit{shift}$ to record the current number of bits to shift. When $i$ is a power of $2$, $\\textit{shift}$ needs to be incremented by $1$.\n\nThe time complexity is $O(n)$, where $n$ is the given integer. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1681, "explanations": { "1": "Let's assume that the size of each subset after partitioning is $m$, so $m=\\frac{n}{k}$, where $n$ is the length of the array.\n\nWe can enumerate all subsets $i$, where $i \\in [0, 2^n)$, if the binary representation of subset $i$ has $m$ ones, and the elements in subset $i$ are not repeated, then we can calculate the incompatibility of subset $i$, denoted as $g[i]$, i.e., $g[i]=\\max_{j \\in i} \\{nums[j]\\} - \\min_{j \\in i} \\{nums[j]\\}$.\n\nNext, we can use dynamic programming to solve.\n\nWe define $f[i]$ as the minimum sum of incompatibilities when the current partitioned subset state is $i$. Initially, $f[0]=0$, which means no elements are partitioned into the subset, and the rest $f[i]=+\\infty$.\n\nFor state $i$, we find all undivided and non-repeated elements, represented by a state $mask$. If the number of elements in state $mask$ is greater than or equal to $m$, then we enumerate all subsets $j$ of $mask$, and satisfy $j \\subset mask$, then $f[i \\cup j]=\\min \\{f[i \\cup j], f[i]+g[j]\\}$.\n\nFinally, if $f[2^n-1]=+\\infty$, it means that it cannot be partitioned into $k$ subsets, return $-1$, otherwise return $f[2^n-1]$.\n\nThe time complexity is $O(3^n)$, and the space complexity is $O(2^n)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(3^n)", "space_complexity": "O(2^n)" }, { "problem_id": 1682, "explanations": { "1": "We design a function $dfs(i, j, x)$ to represent the length of the longest \"good\" palindrome subsequence ending with character $x$ in the index range $[i, j]$ of string $s$. The answer is $dfs(0, n - 1, 26)$.\n\nThe calculation process of the function $dfs(i, j, x)$ is as follows:\n\n- If $i >= j$, then $dfs(i, j, x) = 0$;\n- If $s[i] = s[j]$ and $s[i] \\neq x$, then $dfs(i, j, x) = dfs(i + 1, j - 1, s[i]) + 2$;\n- If $s[i] \\neq s[j]$, then $dfs(i, j, x) = max(dfs(i + 1, j, x), dfs(i, j - 1, x))$.\n\nDuring the process, we can use memorization search to avoid repeated calculations.\n\nThe time complexity is $O(n^2 \\times C)$. Where $n$ is the length of the string $s$, and $C$ is the size of the character set. In this problem, $C = 26$." }, "is_english": true, "time_complexity": "O(n^2 \\times C)", "space_complexity": null }, { "problem_id": 1683, "explanations": { "1": "The `CHAR_LENGTH()` function returns the length of a string, where Chinese characters, numbers, and letters are all counted as $1$ byte.\n\nThe `LENGTH()` function returns the length of a string, where under utf8 encoding, Chinese characters are counted as $3$ bytes, while numbers and letters are counted as $1$ byte; under gbk encoding, Chinese characters are counted as $2$ bytes, while numbers and letters are counted as $1$ byte.\n\nFor this problem, we can directly use the `CHAR_LENGTH` function to get the length of the string, and filter out the tweet IDs with a length greater than $15$." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1684, "explanations": { "1": "A straightforward approach is to use a hash table or array $s$ to record the characters in `allowed`. Then iterate over the `words` array, for each string $w$, determine whether it is composed of characters in `allowed`. If so, increment the answer.\n\nThe time complexity is $O(m)$, and the space complexity is $O(C)$. Here, $m$ is the total length of all strings, and $C$ is the size of the character set `allowed`. In this problem, $C \\leq 26$.", "2": "We can also use a single integer to represent the occurrence of characters in each string. In this integer, each bit in the binary representation indicates whether a character appears.\n\nWe simply define a function $f(w)$ that can convert a string $w$ into an integer. Each bit in the binary representation of the integer indicates whether a character appears. For example, the string `ab` can be converted into the integer $3$, which is represented in binary as $11$. The string `abd` can be converted into the integer $11$, which is represented in binary as $1011$.\n\nBack to the problem, to determine whether a string $w$ is composed of characters in `allowed`, we can check whether the result of the bitwise OR operation between $f(allowed)$ and $f(w)$ is equal to $f(allowed)$. If so, increment the answer.\n\nThe time complexity is $O(m)$, where $m$ is the total length of all strings. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m)", "space_complexity": "O(C)" }, { "problem_id": 1685, "explanations": { "1": "First, we calculate the sum of all elements in the array $nums$, denoted as $s$. We use a variable $t$ to record the sum of the elements that have been enumerated so far.\n\nNext, we enumerate $nums[i]$. Then $ans[i] = nums[i] \\times i - t + s - t - nums[i] \\times (n - i)$. After that, we update $t$, i.e., $t = t + nums[i]$. We continue to enumerate the next element until all elements are enumerated.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1686, "explanations": { "1": "The optimal strategy for picking stones is to maximize one's own score while making the opponent lose as much as possible. Therefore, we create an array $vals$, where $vals[i] = (aliceValues[i] + bobValues[i], i)$ represents the total value and index of the $i$-th stone. Then we sort $vals$ in descending order by total value.\n\nNext, we let Alice and Bob pick stones alternately according to the order of $vals$. Alice picks the stones at even positions in $vals$, and Bob picks the stones at odd positions in $vals$. Finally, we compare the scores of Alice and Bob and return the corresponding result.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$, where $n$ is the length of the arrays `aliceValues` and `bobValues`." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1687, "explanations": { "1": "We define $f[i]$ as the minimum number of trips required to transport the first $i$ boxes from the warehouse to the corresponding docks, so the answer is $f[n]$.\n\nThe boxes need to be transported in the order of the array. Each time, the truck will take out several consecutive boxes in order, then deliver them to the corresponding docks one by one. After all are delivered, it returns to the warehouse.\n\nTherefore, we can enumerate the index $j$ of the last box transported in the last trip. Then $f[i]$ can be transferred from $f[j]$. During the transfer, we need to consider the following issues:\n\n- When transferring from $f[j]$, the number of boxes on the truck cannot exceed $maxBoxes$\n- When transferring from $f[j]$, the total weight of the boxes on the truck cannot exceed $maxWeight$\n\nThe state transition equation is:\n\n$$\nf[i] = \\min_{j \\in [i - maxBoxes, i - 1]} \\left(f[j] + \\sum_{k = j + 1}^i \\textit{cost}(k)\\right)\n$$\n\nWhere $\\sum_{k = j + 1}^i \\textit{cost}(k)$ represents the number of trips required to deliver the boxes in $[j+1,..i]$ to their corresponding docks in one trip. This part of the trip count can be quickly calculated using prefix sums.\n\nFor example, suppose we take out boxes $1, 2, 3$ and need to deliver them to docks $4, 4, 5$. We first go from the warehouse to dock $4$, then from dock $4$ to dock $5$, and finally from dock $5$ back to the warehouse. It can be seen that it takes $2$ trips to go from the warehouse to the dock and from the dock back to the warehouse. The number of trips from dock to dock depends on whether the two adjacent docks are the same. If they are not the same, the number of trips will increase by $1$, otherwise it remains the same. Therefore, we can calculate the number of trips between docks using prefix sums, and add two trips for the start and end, to calculate the number of trips required to deliver the boxes in $[j+1,..i]$ to their corresponding docks.\n\nThe code implementation is as follows:\n\n```python\n# 33/39\nclass Solution:\n def boxDelivering(\n self, boxes: List[List[int]], portsCount: int, maxBoxes: int, maxWeight: int\n ) -> int:\n n = len(boxes)\n ws = list(accumulate((box[1] for box in boxes), initial=0))\n c = [int(a != b) for a, b in pairwise(box[0] for box in boxes)]\n cs = list(accumulate(c, initial=0))\n f = [inf] * (n + 1)\n f[0] = 0\n for i in range(1, n + 1):\n for j in range(max(0, i - maxBoxes), i):\n if ws[i] - ws[j] <= maxWeight:\n f[i] = min(f[i], f[j] + cs[i - 1] - cs[j] + 2)\n return f[n]\n```\n\n```java\n// 35/39\nclass Solution {\n public int boxDelivering(int[][] boxes, int portsCount, int maxBoxes, int maxWeight) {\n int n = boxes.length;\n long[] ws = new long[n + 1];\n int[] cs = new int[n];\n for (int i = 0; i < n; ++i) {\n int p = boxes[i][0], w = boxes[i][1];\n ws[i + 1] = ws[i] + w;\n if (i < n - 1) {\n cs[i + 1] = cs[i] + (p != boxes[i + 1][0] ? 1 : 0);\n }\n }\n int[] f = new int[n + 1];\n Arrays.fill(f, 1 << 30);\n f[0] = 0;\n for (int i = 1; i <= n; ++i) {\n for (int j = Math.max(0, i - maxBoxes); j < i; ++j) {\n if (ws[i] - ws[j] <= maxWeight) {\n f[i] = Math.min(f[i], f[j] + cs[i - 1] - cs[j] + 2);\n }\n }\n }\n return f[n];\n }\n}\n```\n\n```cpp\n// 35/39\nclass Solution {\npublic:\n int boxDelivering(vector>& boxes, int portsCount, int maxBoxes, int maxWeight) {\n int n = boxes.size();\n long ws[n + 1];\n int cs[n];\n ws[0] = cs[0] = 0;\n for (int i = 0; i < n; ++i) {\n int p = boxes[i][0], w = boxes[i][1];\n ws[i + 1] = ws[i] + w;\n if (i < n - 1) cs[i + 1] = cs[i] + (p != boxes[i + 1][0]);\n }\n int f[n + 1];\n memset(f, 0x3f, sizeof f);\n f[0] = 0;\n for (int i = 1; i <= n; ++i) {\n for (int j = max(0, i - maxBoxes); j < i; ++j) {\n if (ws[i] - ws[j] <= maxWeight) {\n f[i] = min(f[i], f[j] + cs[i - 1] - cs[j] + 2);\n }\n }\n }\n return f[n];\n }\n};\n```\n\n```go\n// 35/39\nfunc boxDelivering(boxes [][]int, portsCount int, maxBoxes int, maxWeight int) int {\n\tn := len(boxes)\n\tws := make([]int, n+1)\n\tcs := make([]int, n)\n\tfor i, box := range boxes {\n\t\tp, w := box[0], box[1]\n\t\tws[i+1] = ws[i] + w\n\t\tif i < n-1 {\n\t\t\tt := 0\n\t\t\tif p != boxes[i+1][0] {\n\t\t\t\tt++\n\t\t\t}\n\t\t\tcs[i+1] = cs[i] + t\n\t\t}\n\t}\n\tf := make([]int, n+1)\n\tfor i := 1; i <= n; i++ {\n\t\tf[i] = 1 << 30\n\t\tfor j := max(0, i-maxBoxes); j < i; j++ {\n\t\t\tif ws[i]-ws[j] <= maxWeight {\n\t\t\t\tf[i] = min(f[i], f[j]+cs[i-1]-cs[j]+2)\n\t\t\t}\n\t\t}\n\t}\n\treturn f[n]\n}\n```\n\nThe data scale of this problem reaches $10^5$, and the time complexity of the above code is $O(n^2)$, which will exceed the time limit. If we observe carefully:\n\n$$\nf[i] = \\min(f[i], f[j] + cs[i - 1] - cs[j] + 2)\n$$\n\nIn fact, we are looking for a $j$ in the window $[i-maxBoxes,..i-1]$ that minimizes the value of $f[j] - cs[j]$. To find the minimum value in a sliding window, a common method is to use a monotonic queue, which can get the minimum value that meets the condition in $O(1)$ time.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of boxes in the problem." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 1688, "explanations": { "1": "From the problem description, we know that there are $n$ teams in total. Each pairing will eliminate one team. Therefore, the number of pairings is equal to the number of teams eliminated, which is $n - 1$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 1689, "explanations": { "1": "The problem is equivalent to finding the maximum number in the string.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1690, "explanations": { "1": "First, we preprocess to get the prefix sum array $s$, where $s[i]$ represents the total sum of the first $i$ stones.\n\nNext, we design a function $dfs(i, j)$, which represents the score difference between the first and second players when the remaining stones are $stones[i], stones[i + 1], \\dots, stones[j]$. The answer is $dfs(0, n - 1)$.\n\nThe calculation process of the function $dfs(i, j)$ is as follows:\n\n- If $i > j$, it means there are no stones currently, so return $0$;\n- Otherwise, the first player has two choices, which are to remove $stones[i]$ or $stones[j]$, and then calculate the score difference, i.e., $a = s[j + 1] - s[i + 1] - dfs(i + 1, j)$ and $b = s[j] - s[i] - dfs(i, j - 1)$. We take the larger of the two as the return value of $dfs(i, j)$.\n\nDuring the process, we use memorization search, i.e., use an array $f$ to record the return value of the function $dfs(i, j)$, to avoid repeated calculations.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ is the number of stones.", "2": "We can convert the memoization search in Solution 1 into dynamic programming. We define $f[i][j]$ as the score difference between the first and second players when the remaining stones are $stones[i], stones[i + 1], \\dots, stones[j]$. Therefore, the answer is $f[0][n - 1]$.\n\nThe state transition equation is as follows:\n\n$$\nf[i][j] = \\max(s[j + 1] - s[i + 1] - f[i + 1][j], s[j] - s[i] - f[i][j - 1])\n$$\n\nWhen calculating $f[i][j]$, we need to ensure that $f[i + 1][j]$ and $f[i][j - 1]$ have been calculated. Therefore, we need to enumerate $i$ in descending order and $j$ in ascending order.\n\nFinally, the answer is $f[0][n - 1]$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ is the number of stones." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 1691, "explanations": { "1": "According to the problem description, box $j$ can be placed on box $i$ if and only if the \"length, width, and height\" of box $j$ are less than or equal to the \"length, width, and height\" of box $i$.\n\nThis problem allows us to rotate the boxes, which means we can choose any side of the box as the \"height\". For any legal stacking, if we rotate each box in it to \"length <= width <= height\", the stacking is still legal and can ensure the maximum height of the stacking.\n\nTherefore, we can sort all the sides of the boxes so that each box satisfies \"length <= width <= height\". Then we sort each box in ascending order.\n\nNext, we can use dynamic programming to solve this problem.\n\nWe define $f[i]$ as the maximum height when box $i$ is at the bottom. We can enumerate each box $j$ above box $i$, where $0 \\leq j < i$. If $j$ can be placed on top of $i$, then we can get the state transition equation:\n\n$$\nf[i] = \\max_{0 \\leq j < i} \\{f[j] + h[i]\\}\n$$\n\nwhere $h[i]$ represents the height of box $i$.\n\nThe final answer is the maximum value of $f[i]$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ is the number of boxes." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 1692, "explanations": { "1": "We define $f[i][j]$ as the number of different ways to distribute $i$ candies to $j$ bags. Initially, $f[0][0]=1$, and the answer is $f[n][k]$.\n\nWe consider how to distribute the $i$-th candy. If the $i$-th candy is distributed to a new bag, then $f[i][j]=f[i-1][j-1]$. If the $i$-th candy is distributed to an existing bag, then $f[i][j]=f[i-1][j]\\times j$. Therefore, the state transition equation is:\n\n$$\nf[i][j]=f[i-1][j-1]+f[i-1][j]\\times j\n$$\n\nThe final answer is $f[n][k]$.\n\nThe time complexity is $O(n \\times k)$, and the space complexity is $O(n \\times k)$. Here, $n$ and $k$ are the number of candies and bags, respectively." }, "is_english": true, "time_complexity": "O(n \\times k)", "space_complexity": "O(n \\times k)" }, { "problem_id": 1693, "explanations": { "1": "We can use the `GROUP BY` statement to group the data by the `date_id` and `make_name` fields, and then use the `COUNT(DISTINCT)` function to count the number of distinct values for `lead_id` and `partner_id`." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1694, "explanations": { "1": "First, according to the problem description, we remove all spaces and hyphens from the string.\n\nLet the current string length be $n$. Then we traverse the string from the beginning, grouping every $3$ characters together and adding them to the result string. We take a total of $n / 3$ groups.\n\nIf there is $1$ character left in the end, we form a new group of two characters with the last character of the last group and this character, and add it to the result string. If there are $2$ characters left, we directly form a new group with these two characters and add it to the result string.\n\nFinally, we add hyphens between all groups and return the result string.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1695, "explanations": { "1": "We use an array or hash table $\\text{d}$ to record the last occurrence position of each number, and use a prefix sum array $\\text{s}$ to record the sum from the starting point to the current position. We use a variable $j$ to record the left endpoint of the current non-repeating subarray.\n\nWe iterate through the array. For each number $v$, if $\\text{d}[v]$ exists, we update $j$ to $\\max(j, \\text{d}[v])$, which ensures that the current non-repeating subarray does not contain $v$. Then we update the answer to $\\max(\\text{ans}, \\text{s}[i] - \\text{s}[j])$, and finally update $\\text{d}[v]$ to $i$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $\\text{nums}$.", "2": "The problem is essentially asking us to find the longest subarray where all elements are distinct. We can use two pointers $i$ and $j$ to point to the left and right boundaries of the subarray, initially $i = 0$ and $j = 0$. Additionally, we use a hash table $\\text{vis}$ to record the elements in the subarray.\n\nWe iterate through the array. For each number $x$, if $x$ is in $\\text{vis}$, we continuously remove $\\text{nums}[i]$ from $\\text{vis}$ until $x$ is no longer in $\\text{vis}$. This way, we find a subarray that contains no duplicate elements. We add $x$ to $\\text{vis}$, update the subarray sum $s$, and then update the answer $\\text{ans} = \\max(\\text{ans}, s)$.\n\nAfter the iteration, we can get the maximum subarray sum.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $\\text{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1696, "explanations": { "1": "We define $f[i]$ as the maximum score when reaching index $i$. The value of $f[i]$ can be transferred from $f[j]$, where $j$ satisfies $i - k \\leq j \\leq i - 1$. Therefore, we can use dynamic programming to solve this problem.\n\nThe state transition equation is:\n\n$$\nf[i] = \\max_{j \\in [i - k, i - 1]} f[j] + nums[i]\n$$\n\nWe can use a monotonic queue to optimize the state transition equation. Specifically, we maintain a monotonically decreasing queue, which stores the index $j$, and the $f[j]$ values corresponding to the indices in the queue are monotonically decreasing. When performing state transition, we only need to take out the index $j$ at the front of the queue to get the maximum value of $f[j]$, and then update the value of $f[i]$ to $f[j] + nums[i]$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1697, "explanations": { "1": "According to the problem requirements, we need to judge each query $queries[i]$, that is, to determine whether there is a path with edge weight less than or equal to $limit$ between the two points $a$ and $b$ of the current query.\n\nThe connectivity of two points can be determined by a union-find set. Moreover, since the order of queries does not affect the result, we can sort all queries in ascending order by $limit$, and also sort all edges in ascending order by edge weight.\n\nThen for each query, we start from the edge with the smallest weight, add all edges with weights strictly less than $limit$ to the union-find set, and then use the query operation of the union-find set to determine whether the two points are connected.\n\nThe time complexity is $O(m \\times \\log m + q \\times \\log q)$, where $m$ and $q$ are the number of edges and queries, respectively." }, "is_english": true, "time_complexity": "O(m \\times \\log m + q \\times \\log q)", "space_complexity": null }, { "problem_id": 1698, "explanations": { "1": "Enumerate all substrings and use a hash table to record the count of different substrings.\n\nThe time complexity is $O(n^3)$, and the space complexity is $O(n^2)$. Here, $n$ is the length of the string.", "2": "**String hashing** is a method to map a string of any length to a non-negative integer, and the probability of collision is almost zero. String hashing is used to calculate the hash value of a string, which can quickly determine whether two strings are equal.\n\nWe take a fixed value BASE, treat the string as a number in BASE radix, and assign a value greater than 0 to represent each character. Generally, the values we assign are much smaller than BASE. For example, for a string composed of lowercase letters, we can set a=1, b=2, ..., z=26. We take a fixed value MOD, calculate the remainder of the BASE radix number to MOD, and use it as the hash value of the string.\n\nGenerally, we take BASE=131 or BASE=13331, at which point the probability of collision of the hash value is extremely low. As long as the hash values of two strings are the same, we consider the two strings to be equal. Usually, MOD is taken as 2^64. In C++, we can directly use the unsigned long long type to store this hash value. When calculating, we do not handle arithmetic overflow. When overflow occurs, it is equivalent to automatically taking the modulus of 2^64, which can avoid inefficient modulus operations.\n\nExcept for extremely specially constructed data, the above hash algorithm is unlikely to cause collisions. In general, the above hash algorithm can appear in the standard answer of the problem. We can also take some appropriate BASE and MOD values (such as large prime numbers), perform several groups of hash operations, and only consider the original strings equal when the results are all the same, making it even more difficult to construct data that causes this hash to produce errors.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ is the length of the string." }, "is_english": true, "time_complexity": "O(n^3)", "space_complexity": "O(n^2)" }, { "problem_id": 1699, "explanations": { "1": "We can use the `if` function or the `least` and `greatest` functions to convert `from_id` and `to_id` into `person1` and `person2`, and then group by `person1` and `person2` and sum the values." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1700, "explanations": { "1": "We observe that the positions of the students can be adjusted, but the positions of the sandwiches cannot be adjusted. That is to say, if the sandwich in front is not taken, then all the sandwiches behind cannot be taken.\n\nTherefore, we first use a counter $cnt$ to count the types of sandwiches that students like and their corresponding quantities.\n\nThen we traverse the sandwiches. If we cannot find a student who likes this sandwich in $cnt$, it means that the sandwiches behind cannot be taken, and we return the current number of remaining students.\n\nIf the traversal is over, it means that all students have sandwiches to eat, and we return $0$.\n\nThe time complexity is $O(n)$, where $n$ is the number of sandwiches. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1701, "explanations": { "1": "We use a variable `tot` to record the total waiting time of the customers, and a variable `t` to record the time when each customer's order is completed. The initial values of both are $0$.\n\nWe traverse the customer array `customers`. For each customer:\n\nIf the current time `t` is less than or equal to the customer's arrival time `customers[i][0]`, it means that the chef is not cooking, so the chef can start cooking immediately. The time to complete this dish is $t = customers[i][0] + customers[i][1]$, and the customer's waiting time is `customers[i][1]`.\n\nOtherwise, it means that the chef is cooking, so the customer needs to wait for the chef to finish the previous dishes before starting to cook their own dishes. The time to complete this dish is $t = t + customers[i][1]$, and the customer's waiting time is $t - customers[i][0]$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the customer array `customers`. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1702, "explanations": { "1": "We observe that operation $2$ can move all $1$s to the end of the string, and operation $1$ can change all `0000..000` strings to `111..110`.\n\nTherefore, to get the maximum binary string, we should move all $1$s that are not at the beginning to the end of the string, making the string in the form of `111..11...000..00..11`. Then, with the help of operation $1$, we change the middle `000..00` to `111..10`. In this way, we can finally get a binary string that contains at most one $0$, which is the maximum binary string we are looking for.\n\nIn the code implementation, we first judge whether the string contains $0$. If it does not, we directly return the original string. Otherwise, we find the position $k$ of the first $0$, add the number of $0$s after this position, and the position of $0$ in the modified string is obtained. The rest of the positions are all $1$s.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1703, "explanations": { "1": "We can store the indices of $1$s in the array $nums$ into an array $arr$. Next, we preprocess the prefix sum array $s$ of the array $arr$, where $s[i]$ represents the sum of the first $i$ elements in the array $arr$.\n\nFor a subarray of length $k$, the number of elements on the left (including the median) is $x=\\frac{k+1}{2}$, and the number of elements on the right is $y=k-x$.\n\nWe enumerate the index $i$ of the median, where $x-1\\leq i\\leq len(arr)-y$. The prefix sum of the left array is $ls=s[i+1]-s[i+1-x]$, and the prefix sum of the right array is $rs=s[i+1+y]-s[i+1]$. The current median index in $nums$ is $j=arr[i]$. The number of operations required to move the left $x$ elements to $[j-x+1,..j]$ is $a=(j+j-x+1)\\times\\frac{x}{2}-ls$, and the number of operations required to move the right $y$ elements to $[j+1,..j+y]$ is $b=rs-(j+1+j+y)\\times\\frac{y}{2}$. The total number of operations is $a+b$, and we take the minimum of all total operation counts.\n\nThe time complexity is $O(n)$, and the space complexity is $O(m)$. Here, $n$ and $m$ are the length of the array $nums$ and the number of $1$s in the array $nums$, respectively." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(m)" }, { "problem_id": 1704, "explanations": { "1": "Traverse the string. If the number of vowels in the first half of the string is equal to the number of vowels in the second half, return `true`. Otherwise, return `false`.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(C)$, where $C$ is the number of vowel characters." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(C)" }, { "problem_id": 1705, "explanations": { "1": "We can greedily choose the apples that are closest to rotting among the unrotten apples, so that we can eat as many apples as possible.\n\nTherefore, we can use a priority queue (min-heap) to store the rotting time of the apples and the corresponding number of apples. Each time, we take out the apples with the smallest rotting time from the priority queue, then decrement their quantity by one. If the quantity is not zero after decrementing, we put them back into the priority queue. If the apples have already rotted, we remove them from the priority queue.\n\nThe time complexity is $O(n \\times \\log n + M)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{days}$, and $M = \\max(\\textit{days})$." }, "is_english": true, "time_complexity": "O(n \\times \\log n + M)", "space_complexity": "O(n)" }, { "problem_id": 1706, "explanations": { "1": "We can use DFS to simulate the movement of the ball. Design a function $\\textit{dfs}(i, j)$, which represents the column where the ball will fall when it starts from row $i$ and column $j$. The ball will get stuck in the following cases:\n\n1. The ball is in the leftmost column, and the cell's diagonal directs the ball to the left.\n2. The ball is in the rightmost column, and the cell's diagonal directs the ball to the right.\n3. The cell's diagonal directs the ball to the right, and the adjacent cell to the right directs the ball to the left.\n4. The cell's diagonal directs the ball to the left, and the adjacent cell to the left directs the ball to the right.\n\nIf any of the above conditions are met, we can determine that the ball will get stuck and return $-1$. Otherwise, we can continue to recursively find the next position of the ball. Finally, if the ball reaches the last row, we can return the current column index.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m)$. Here, $m$ and $n$ are the number of rows and columns of the grid, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m)" }, { "problem_id": 1707, "explanations": { "1": "From the problem description, we know that each query is independent and the result of the query is irrelevant to the order of elements in $nums$. Therefore, we consider sorting all queries in ascending order of $m_i$, and also sorting $nums$ in ascending order.\n\nNext, we use a binary trie to maintain the elements in $nums$. We use a pointer $j$ to record the current elements in the trie, initially $j=0$. For each query $[x_i, m_i]$, we continuously insert elements from $nums$ into the trie until $nums[j] > m_i$. At this point, we can query all elements not exceeding $m_i$ in the trie, and we take the XOR value of the element with the maximum XOR value with $x_i$ as the answer.\n\nThe time complexity is $O(m \\times \\log m + n \\times (\\log n + \\log M))$, and the space complexity is $O(n \\times \\log M)$. Where $m$ and $n$ are the lengths of the arrays $nums$ and $queries$ respectively, and $M$ is the maximum value in the array $nums$. In this problem, $M \\le 10^9$." }, "is_english": true, "time_complexity": "O(m \\times \\log m + n \\times (\\log n + \\log M))", "space_complexity": "O(n \\times \\log M)" }, { "problem_id": 1708, "explanations": { "1": "All integers in the array are distinct, so we can first find the index of the maximum element in the range $[0,..n-k]$, and then take $k$ elements starting from this index.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. Ignoring the space consumption of the answer, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1709, "explanations": { "1": "We can use the window function `LEAD` to obtain the date of the next visit for each user (if the date of the next visit does not exist, it is considered as `2021-1-1`), and then use the `DATEDIFF` function to calculate the number of days between two visits. Finally, we can take the maximum value of the number of days between visits for each user." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1710, "explanations": { "1": "According to the problem, we should choose as many units as possible. Therefore, we first sort `boxTypes` in descending order of the number of units.\n\nThen we traverse `boxTypes` from front to back, choose up to `truckSize` boxes, and accumulate the number of units.\n\nThe time complexity is $O(n \\times \\log n)$, where $n$ is the length of the two-dimensional array `boxTypes`.", "2": "We can also use the idea of counting sort, create an array $cnt$ of length $1001$, where $cnt[b]$ represents the number of boxes with $b$ units.\n\nThen starting from the box with the maximum number of units, choose up to `truckSize` boxes, and accumulate the number of units.\n\nThe time complexity is $O(M)$, where $M$ is the maximum number of units. In this problem, $M=1000$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": null }, { "problem_id": 1711, "explanations": { "1": "According to the problem, we need to count the number of combinations in the array where the sum of two numbers is a power of $2$. Directly enumerating all combinations has a time complexity of $O(n^2)$, which will definitely time out.\n\nWe can traverse the array and use a hash table $cnt$ to maintain the number of occurrences of each element $d$ in the array.\n\nFor each element, we enumerate the powers of two $s$ as the sum of two numbers from small to large, and add the number of occurrences of $s - d$ in the hash table to the answer. Then increase the number of occurrences of the current element $d$ by one.\n\nAfter the traversal ends, return the answer.\n\nThe time complexity is $O(n \\times \\log M)$, where $n$ is the length of the array `deliciousness`, and $M$ is the upper limit of the elements. For this problem, the upper limit $M=2^{20}$.\n\nWe can also use a hash table $cnt$ to count the number of occurrences of each element in the array first.\n\nThen enumerate the powers of two $s$ as the sum of two numbers from small to large. For each $s$, traverse each key-value pair $(a, m)$ in the hash table. If $s - a$ is also in the hash table, and $s - a \\neq a$, then add $m \\times cnt[s - a]$ to the answer; if $s - a = a$, then add $m \\times (m - 1)$ to the answer.\n\nFinally, divide the answer by $2$, modulo $10^9 + 7$, and return.\n\nThe time complexity is the same as the method above.", "2": "" }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": null }, { "problem_id": 1712, "explanations": { "1": "First, we preprocess the prefix sum array $s$ of the array $nums$, where $s[i]$ represents the sum of the first $i+1$ elements of the array $nums$.\n\nSince all elements of the array $nums$ are non-negative integers, the prefix sum array $s$ is a monotonically increasing array.\n\nWe enumerate the index $i$ that the `left` subarray can reach in the range $[0,..n-2)$, and then use the monotonically increasing characteristic of the prefix sum array to find the reasonable range of the `mid` subarray split by binary search, denoted as $[j, k)$, and accumulate the number of schemes $k-j$.\n\nIn the binary search details, the subarray split must satisfy $s[j] \\geq s[i]$ and $s[n - 1] - s[k] \\geq s[k] - s[i]$. That is, $s[j] \\geq s[i]$ and $s[k] \\leq \\frac{s[n - 1] + s[i]}{2}$.\n\nFinally, return the number of schemes modulo $10^9+7$.\n\nThe time complexity is $O(n \\times \\log n)$, where $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": null }, { "problem_id": 1713, "explanations": { "1": "According to the problem statement, the longer the common subsequence between `target` and `arr`, the fewer elements need to be added. Therefore, the minimum number of elements to be added equals the length of `target` minus the length of the longest common subsequence between `target` and `arr`.\n\nHowever, the time complexity of [finding the longest common subsequence](https://github.com/doocs/leetcode/blob/main/solution/1100-1199/1143.Longest%20Common%20Subsequence/README.md) is $O(m \\times n)$, which cannot pass this problem. We need to change our approach.\n\nWe can use a hash table to record the index of each element in the `target` array, then iterate through the `arr` array. For each element in the `arr` array, if the hash table contains that element, we add the index of that element to an array. This gives us a new array `nums`, which represents the indices in the `target` array of elements from `arr` (excluding elements not in `target`). The length of the longest increasing subsequence of this array `nums` is the length of the longest common subsequence between `target` and `arr`.\n\nTherefore, the problem is transformed into finding the length of the longest increasing subsequence of the `nums` array. Refer to [300. Longest Increasing Subsequence](https://github.com/doocs/leetcode/blob/main/solution/0300-0399/0300.Longest%20Increasing%20Subsequence/README.md).\n\nThe time complexity is $O(n \\times \\log m)$, and the space complexity is $O(m)$. Here, $m$ and $n$ are the lengths of `target` and `arr`, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m)" }, { "problem_id": 1714, "explanations": { "1": "This problem is a typical block decomposition problem. For queries with a large step size, we can directly brute force the solution; for queries with a small step size, we can preprocess the suffix sum of each position and then directly query.\n\nIn this problem, we limit the step size of the large step size query to $\\sqrt{n}$, which can ensure that the time complexity of each query is $O(\\sqrt{n})$.\n\nWe define a two-dimensional array $suf$, where $suf[i][j]$ represents the suffix sum starting from position $j$ with a step size of $i$. Then for each query $[x, y]$, we can divide it into two cases:\n\n- If $y \\le \\sqrt{n}$, then we can directly query $suf[y][x]$;\n- If $y > \\sqrt{n}$, then we can directly brute force the solution.\n\nThe time complexity is $O((n + m) \\times \\sqrt{n})$, and the space complexity is $O(n \\times \\sqrt{n})$. Here, $n$ is the length of the array, and $m$ is the number of queries." }, "is_english": true, "time_complexity": "O(\\sqrt{n})", "space_complexity": "O(n \\times \\sqrt{n})" }, { "problem_id": 1715, "explanations": { "1": "We can perform a left join on the `Boxes` table and the `Chests` table based on `chest_id`, and then calculate the total number of apples and oranges respectively. Note that if a box does not contain any small boxes, then the corresponding `chest_id` will be `null`. In this case, we need to consider the number of apples and oranges in the small boxes within that box to be 0." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1716, "explanations": { "1": "According to the problem description, the deposit situation for each week is as follows:\n\n```bash\nWeek 1: 1, 2, 3, 4, 5, 6, 7\nWeek 2: 2, 3, 4, 5, 6, 7, 8\nWeek 3: 3, 4, 5, 6, 7, 8, 9\n...\nWeek k: k, k+1, k+2, k+3, k+4, k+5, k+6\n```\n\nGiven $n$ days of deposits, the number of complete weeks is $k = \\lfloor n / 7 \\rfloor$, and the remaining days is $b = n \\mod 7$.\n\nThe total deposit for the complete $k$ weeks can be calculated using the arithmetic sequence sum formula:\n\n$$\nS_1 = \\frac{k}{2} \\times (28 + 28 + 7 \\times (k - 1))\n$$\n\nThe total deposit for the remaining $b$ days can also be calculated using the arithmetic sequence sum formula:\n\n$$\nS_2 = \\frac{b}{2} \\times (k + 1 + k + 1 + b - 1)\n$$\n\nThe final total deposit amount is $S = S_1 + S_2$.\n\nThe time complexity is $O(1)$ and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 1717, "explanations": { "1": "We can assume that the score of substring \"ab\" is always no less than the score of substring \"ba\". If not, we can swap \"a\" and \"b\", and simultaneously swap $x$ and $y$.\n\nNext, we only need to consider the case where the string contains only \"a\" and \"b\". If the string contains other characters, we can treat them as split points, dividing the string into several substrings that contain only \"a\" and \"b\", and then calculate the score for each substring separately.\n\nWe observe that for a substring containing only \"a\" and \"b\", no matter what operations we take, we will eventually be left with only one type of character, or an empty string. Since each operation removes one \"a\" and one \"b\" simultaneously, the total number of operations is fixed. We can greedily remove \"ab\" first, then remove \"ba\", which ensures the maximum score.\n\nTherefore, we can use two variables $\\textit{cnt1}$ and $\\textit{cnt2}$ to record the counts of \"a\" and \"b\" respectively, then traverse the string and update $\\textit{cnt1}$ and $\\textit{cnt2}$ according to different cases of the current character, while calculating the score.\n\nFor the current character $c$ being traversed:\n\n- If $c$ is \"a\", since we want to remove \"ab\" first, we don't eliminate this character at this time, only increment $\\textit{cnt1}$;\n- If $c$ is \"b\", if $\\textit{cnt1} > 0$ at this time, we can eliminate one \"ab\" and add $x$ points; otherwise, we can only increment $\\textit{cnt2}$;\n- If $c$ is another character, then for this substring, we have $\\textit{cnt2}$ \"b\"s and $\\textit{cnt1}$ \"a\"s left. We can eliminate $\\min(\\textit{cnt1}, \\textit{cnt2})$ \"ba\"s and add several $y$ points.\n\nAfter traversal, we need to handle the remaining \"ba\"s and add several $y$ points.\n\nThe time complexity is $O(n)$, where $n$ is the length of string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1718, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1719, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1720, "explanations": { "1": "Based on the problem description, we have:\n\n$$\n\\textit{encoded}[i] = \\textit{arr}[i] \\oplus \\textit{arr}[i + 1]\n$$\n\nIf we XOR both sides of the equation with $\\textit{arr}[i]$, we get:\n\n$$\n\\textit{arr}[i] \\oplus \\textit{arr}[i] \\oplus \\textit{arr}[i + 1] = \\textit{arr}[i] \\oplus \\textit{encoded}[i]\n$$\n\nWhich simplifies to:\n\n$$\n\\textit{arr}[i + 1] = \\textit{arr}[i] \\oplus \\textit{encoded}[i]\n$$\n\nFollowing the derivation above, we can start with $\\textit{first}$ and sequentially calculate every element of the array $\\textit{arr}$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1721, "explanations": { "1": "We can first use a fast pointer `fast` to find the $k$th node of the linked list, and use a pointer `p` to point to it. Then, we use a slow pointer `slow` to start from the head node of the linked list, and move both pointers forward at the same time. When the fast pointer reaches the last node of the linked list, the slow pointer `slow` points to the $k$th node from the end of the linked list, and we use a pointer `q` to point to it. At this point, we only need to swap the values of `p` and `q`.\n\nThe time complexity is $O(n)$, where $n$ is the length of the linked list. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1722, "explanations": { "1": "We can consider each index as a node, and the element corresponding to each index as the value of the node. Then each element `[a_i, b_i]` in the given `allowedSwaps` represents an edge between index `a_i` and `b_i`. Therefore, we can use a union-find set to maintain these connected components.\n\nAfter obtaining each connected component, we use a two-dimensional hash table $cnt$ to count the number of occurrences of each element in each connected component. Finally, for each element in the array `target`, if its occurrence count in the corresponding connected component is greater than 0, we decrease its count by 1, otherwise, we increase the answer by 1.\n\nThe time complexity is $O(n \\times \\log n)$ or $O(n \\times \\alpha(n))$, and the space complexity is $O(n)$. Here, $n$ is the length of the array, and $\\alpha$ is the inverse Ackermann function." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1723, "explanations": { "1": "本题与 [2305. 公平分发饼干](https://github.com/doocs/leetcode/blob/main/solution/2300-2399/2305.Fair%20Distribution%20of%20Cookies/README.md) 基本一致,不同的地方仅在于 $k$ 值的大小。\n\n剪枝优化:优化分配花费时间较大的工作,因此可以先对 $jobs$ 按照降序排列。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1724, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1725, "explanations": { "1": "We define a variable $ans$ to record the count of squares with the current maximum side length, and another variable $mx$ to record the current maximum side length.\n\nWe traverse the array $rectangles$. For each rectangle $[l, w]$, we take $x = \\min(l, w)$. If $mx < x$, it means we have found a larger side length, so we update $mx$ to $x$ and update $ans$ to $1$. If $mx = x$, it means we have found a side length equal to the current maximum side length, so we increase $ans$ by $1$.\n\nFinally, we return $ans$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $rectangles$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1726, "explanations": { "1": "Assuming there are $n$ pairs of numbers, for any two pairs of numbers $a, b$ and $c, d$ that satisfy the condition $a \\times b = c \\times d$, there are a total of $\\mathrm{C}_n^2 = \\frac{n \\times (n-1)}{2}$ such combinations.\n\nAccording to the problem description, each combination that satisfies the above condition can form $8$ tuples that satisfy the problem requirements. Therefore, we can multiply the number of combinations with the same product by $8$ (equivalent to left shifting by $3$ bits) and add them up to get the result.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 1727, "explanations": { "1": "Since the matrix can be rearranged by columns, we can preprocess each column of the matrix first.\n\nFor each element with value $1$, we update its value to the maximum number of consecutive $1$s above it (including itself), i.e., $\\text{matrix}[i][j] = \\text{matrix}[i-1][j] + 1$.\n\nNext, we sort each row of the updated matrix. Then we traverse each row and compute the maximum area of an all-$1$ submatrix with that row as the bottom edge. The detailed calculation is as follows:\n\nFor a given row, let the $k$-th largest element be $\\text{val}_k$, where $k \\geq 1$. Then there are at least $k$ elements in that row no less than $\\text{val}_k$, forming an all-$1$ submatrix with area $\\text{val}_k \\times k$. We iterate through the elements of the row from largest to smallest, take the maximum value of $\\text{val}_k \\times k$, and update the answer.\n\nThe time complexity is $O(m \\times n \\times \\log n)$ and the space complexity is $O(\\log n)$, where $m$ and $n$ are the number of rows and columns of the matrix, respectively." }, "is_english": true, "time_complexity": "O(m \\times n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 1728, "explanations": { "1": "According to the problem description, the state of the game is determined by the mouse's position, the cat's position, and whose turn it is. The following states can be determined directly:\n\n- When the cat and the mouse are at the same position, the cat wins — this is a winning state for the cat and a losing state for the mouse.\n- When the cat reaches the food first, the cat wins — this is a winning state for the cat and a losing state for the mouse.\n- When the mouse reaches the food first, the mouse wins — this is a winning state for the mouse and a losing state for the cat.\n\nTo determine the result of the initial state, we need to traverse all states starting from the boundary states. Each state contains the mouse's position, the cat's position, and whose turn it is. From the current state, we can derive all possible previous states: the mover in the previous state is the opposite of the current mover, and the mover's position in the previous state differs from that in the current state.\n\nWe use the tuple $(m, c, t)$ to represent the current state, and $(pm, pc, pt)$ to represent a possible previous state. All possible previous states are:\n\n- If the current mover is the mouse, then the previous mover was the cat, the mouse's position in the previous state equals the current mouse position, and the cat's position in the previous state is any neighbor of the current cat position.\n- If the current mover is the cat, then the previous mover was the mouse, the cat's position in the previous state equals the current cat position, and the mouse's position in the previous state is any neighbor of the current mouse position.\n\nInitially, except for the boundary states, the results of all other states are unknown. Starting from the boundary states, for each state we derive all possible previous states and update their results according to the following logic:\n\n1. If the previous mover is the same as the current winner, then the previous mover can reach the current state and win — directly update the previous state to the current winner.\n2. If the previous mover is different from the current winner, and all states reachable by the previous mover are losing states for the previous mover, then we update the previous state to the current winner.\n\nFor the second update rule, we need to record the degree of each state. Initially, the degree of a state represents the number of nodes the mover of that state can move to, i.e., the number of neighbors of the node where the mover is located. If the mover is the cat and the cat's node is adjacent to the hole, the degree of that state should be decremented by $1$.\n\nWhen all states have been updated, the result of the initial state is the final answer.\n\nThe time complexity is $O(m^2 \\times n^2 \\times (m + n))$ and the space complexity is $O(m^2 \\times n^2)$, where $m$ and $n$ are the number of rows and columns of the grid, respectively." }, "is_english": true, "time_complexity": "O(m^2 \\times n^2 \\times (m + n))", "space_complexity": "O(m^2 \\times n^2)" }, { "problem_id": 1729, "explanations": { "1": "We can directly group the `Followers` table by `user_id`, and use the `COUNT` function to count the number of followers for each user." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1730, "explanations": { "1": "According to the problem, we need to start from `*`, find the nearest `#`, and return the shortest path length.\n\nFirst, we traverse the entire two-dimensional array to find the position of `*`, which will be the starting point for BFS, and put it into the queue.\n\nThen, we start BFS, traversing the elements in the queue. Each time we traverse an element, we add the elements in the four directions (up, down, left, and right) of it into the queue, until we encounter `#`, and return the current layer number.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(1)$. Here, $m$ and $n$ are the number of rows and columns of the two-dimensional array, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(1)" }, { "problem_id": 1731, "explanations": { "1": "We can use self-join to connect the information of each employee's superior manager to the information of each employee, and then use grouping and aggregation to count the number of subordinates and the average age of each manager." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1732, "explanations": { "1": "We assume the altitude of each point is $h_i$. Since $gain[i]$ represents the altitude difference between the $i$th point and the $(i + 1)$th point, we have $gain[i] = h_{i + 1} - h_i$. Therefore:\n\n$$\n\\sum_{i = 0}^{n-1} gain[i] = h_1 - h_0 + h_2 - h_1 + \\cdots + h_n - h_{n - 1} = h_n - h_0 = h_n\n$$\n\nwhich implies:\n\n$$\nh_{i+1} = \\sum_{j = 0}^{i} gain[j]\n$$\n\nWe can see that the altitude of each point can be calculated through the prefix sum. Therefore, we only need to traverse the array once, find the maximum value of the prefix sum, which is the highest altitude.\n\n> In fact, the $gain$ array in the problem is a difference array. The prefix sum of the difference array gives the original altitude array. Then find the maximum value of the original altitude array.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the array `gain`." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1733, "explanations": { "1": "For each friendship, if the sets of languages known by the two people do not intersect, we need to teach one language so that they can communicate. We add these people to a hash set $s$.\n\nThen, for each language, we count how many people in set $s$ know that language and find the maximum count, denoted as $mx$. The answer is $|s| - mx$, where $|s|$ is the size of set $s$.\n\nThe time complexity is $O(m^2 \\times k)$. Here, $m$ is the number of languages, and $k$ is the number of friendships." }, "is_english": true, "time_complexity": "O(m^2 \\times k)", "space_complexity": null }, { "problem_id": 1734, "explanations": { "1": "We notice that the array $perm$ is a permutation of the first $n$ positive integers, so the XOR of all elements in $perm$ is $1 \\oplus 2 \\oplus \\cdots \\oplus n$, denoted as $a$. And $encode[i]=perm[i] \\oplus perm[i+1]$, if we denote the XOR of all elements $encode[0],encode[2],\\cdots,encode[n-3]$ as $b$, then $perm[n-1]=a \\oplus b$. Knowing the last element of $perm$, we can find all elements of $perm$ by traversing the array $encode$ in reverse order.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $perm$. Ignoring the space consumption of the answer, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1735, "explanations": { "1": "We can perform prime factorization on $k$, i.e., $k = p_1^{x_1} \\times p_2^{x_2} \\times \\cdots \\times p_m^{x_m}$, where $p_i$ is a prime number, and $x_i$ is the exponent of $p_i$. The problem is equivalent to: placing $x_1$ $p_1$s, $x_2$ $p_2$s, $\\cdots$, $x_m$ $p_m$s into $n$ positions respectively, where a single position can be empty. The question is how many schemes are there.\n\nAccording to combinatorial mathematics, there are two cases when we put $x$ balls into $n$ boxes:\n\nIf the box cannot be empty, the number of schemes is $C_{x-1}^{n-1}$. This is using the partition method, i.e., there are a total of $x$ balls, and we insert $n-1$ partitions at $x-1$ positions, thereby dividing the $x$ balls into $n$ groups.\n\nIf the box can be empty, we can add $n$ virtual balls, and then use the partition method, i.e., there are a total of $x+n$ balls, and we insert $n-1$ partitions at $x+n-1$ positions, thereby dividing the actual $x$ balls into $n$ groups and allowing the box to be empty. Therefore, the number of schemes is $C_{x+n-1}^{n-1}$.\n\nTherefore, for each query $queries[i]$, we can first perform prime factorization on $k$ to get the exponents $x_1, x_2, \\cdots, x_m$, then calculate $C_{x_1+n-1}^{n-1}, C_{x_2+n-1}^{n-1}, \\cdots, C_{x_m+n-1}^{n-1}$, and finally multiply all the scheme numbers.\n\nSo, the problem is transformed into how to quickly calculate $C_m^n$. According to the formula $C_m^n = \\frac{m!}{n!(m-n)!}$, we can pre-process $m!$, and then use the inverse element to quickly calculate $C_m^n$.\n\nThe time complexity is $O(K \\times \\log \\log K + N + m \\times \\log K)$, and the space complexity is $O(N)$." }, "is_english": true, "time_complexity": "O(K \\times \\log \\log K + N + m \\times \\log K)", "space_complexity": "O(N)" }, { "problem_id": 1736, "explanations": { "1": "We process each digit of the string in order, following these rules:\n\n1. First digit: If the value of the second digit is determined and falls within the range $[4, 9]$, then the first digit can only be $1$. Otherwise, the first digit can be up to $2$.\n1. Second digit: If the value of the first digit is determined and is $2$, then the second digit can be up to $3$. Otherwise, the second digit can be up to $9$.\n1. Third digit: The third digit can be up to $5$.\n1. Fourth digit: The fourth digit can be up to $9$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 1737, "explanations": { "1": "First, we count the number of occurrences of each letter in strings $a$ and $b$, denoted as $cnt_1$ and $cnt_2$.\n\nThen, we consider condition $3$, i.e., every letter in $a$ and $b$ is the same. We just need to enumerate the final letter $c$, and then count the number of letters in $a$ and $b$ that are not $c$. This is the number of characters that need to be changed.\n\nNext, we consider conditions $1$ and $2$, i.e., every letter in $a$ is less than every letter in $b$, or every letter in $b$ is less than every letter in $a$. For condition $1$, we make all characters in string $a$ less than character $c$, and all characters in string $b$ not less than $c$. We enumerate $c$ to find the smallest answer. Condition $2$ is similar.\n\nThe final answer is the minimum of the above three cases.\n\nThe time complexity is $O(m + n + C^2)$, where $m$ and $n$ are the lengths of strings $a$ and $b$ respectively, and $C$ is the size of the character set. In this problem, $C = 26$." }, "is_english": true, "time_complexity": "O(m + n + C^2)", "space_complexity": null }, { "problem_id": 1738, "explanations": { "1": "We define a two-dimensional prefix XOR array $s$, where $s[i][j]$ represents the XOR result of the elements in the first $i$ rows and the first $j$ columns of the matrix, i.e.,\n\n$$\ns[i][j] = \\bigoplus_{0 \\leq x \\leq i, 0 \\leq y \\leq j} matrix[x][y]\n$$\n\nAnd $s[i][j]$ can be calculated from the three elements $s[i - 1][j]$, $s[i][j - 1]$ and $s[i - 1][j - 1]$, i.e.,\n\n$$\ns[i][j] = s[i - 1][j] \\oplus s[i][j - 1] \\oplus s[i - 1][j - 1] \\oplus matrix[i - 1][j - 1]\n$$\n\nWe traverse the matrix, calculate all $s[i][j]$, then sort them, and finally return the $k$th largest element. If you don't want to use sorting, you can also use the quick selection algorithm, which can optimize the time complexity.\n\nThe time complexity is $O(m \\times n \\times \\log (m \\times n))$ or $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the number of rows and columns of the matrix, respectively." }, "is_english": true, "time_complexity": "O(m \\times n \\times \\log (m \\times n))", "space_complexity": "O(m \\times n)" }, { "problem_id": 1739, "explanations": { "1": "According to the problem description, the box with the highest number of layers needs to be placed in the corner of the wall, and the arrangement of the boxes is in a step-like shape, which can minimize the number of boxes touching the ground.\n\nAssume that the boxes are arranged in $k$ layers. From top to bottom, if each layer is filled, then the number of boxes in each layer is $1, 1+2, 1+2+3, \\cdots, 1+2+\\cdots+k$.\n\nIf there are still remaining boxes at this point, they can continue to be placed from the lowest layer. Assume that $i$ boxes are placed, then the cumulative number of boxes that can be placed is $1+2+\\cdots+i$.\n\nThe time complexity is $O(\\sqrt{n})$, where $n$ is the number of boxes given in the problem. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\sqrt{n})", "space_complexity": "O(1)" }, { "problem_id": 1740, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1741, "explanations": { "1": "We can first group by `emp_id` and `event_day`, and then calculate the total time for each group. The total time is equal to the sum of the differences between `out_time` and `in_time` for each record in the group." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1742, "explanations": { "1": "Observing the problem's data range, the maximum number of balls does not exceed $10^5$, so the maximum sum of the digits of each number is less than $50$. Therefore, we can directly create an array $\\textit{cnt}$ of length $50$ to count the number of occurrences of each digit sum.\n\nThe answer is the maximum value in the array $\\textit{cnt}$.\n\nThe time complexity is $O(n \\times \\log_{10}m)$. Here, $n = \\textit{highLimit} - \\textit{lowLimit} + 1$, and $m = \\textit{highLimit}$." }, "is_english": true, "time_complexity": "O(n \\times \\log_{10}m)", "space_complexity": null }, { "problem_id": 1743, "explanations": { "1": "从度为一的点开始遍历图,可以用 DFS,也可以直接遍历。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。", "2": "" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1744, "explanations": { "1": "时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 `candiesCount` 的长度。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1745, "explanations": { "1": "We define $f[i][j]$ to indicate whether the substring of $s$ from the $i$-th character to the $j$-th character is a palindrome, initially $f[i][j] = \\textit{true}$.\n\nThen we can calculate $f[i][j]$ using the following state transition equation:\n\n$$\nf[i][j] = \\begin{cases}\n\\textit{true}, & \\text{if } s[i] = s[j] \\text{ and } (i + 1 = j \\text{ or } f[i + 1][j - 1]) \\\\\n\\textit{false}, & \\text{otherwise}\n\\end{cases}\n$$\n\nSince $f[i][j]$ depends on $f[i + 1][j - 1]$, we need to enumerate $i$ from large to small and $j$ from small to large, so that when calculating $f[i][j]$, $f[i + 1][j - 1]$ has already been calculated.\n\nNext, we enumerate the right endpoint $i$ of the first substring and the right endpoint $j$ of the second substring. The left endpoint of the third substring can be enumerated in the range $[j + 1, n - 1]$, where $n$ is the length of the string $s$. If the first substring $s[0..i]$, the second substring $s[i+1..j]$, and the third substring $s[j+1..n-1]$ are all palindromes, then we have found a feasible partitioning scheme and return $\\textit{true}$.\n\nAfter enumerating all partitioning schemes, if no valid partitioning scheme is found, return $\\textit{false}$.\n\nTime complexity is $O(n^2)$, and space complexity is $O(n^2)$. Where $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 1746, "explanations": { "1": "我们定义 $f[i]$ 表示以 $nums[i]$ 结尾,且没有进行替换的最大子数组和,另外定义 $g[i]$ 表示以 $nums[i]$ 结尾,且进行了替换的最大子数组和。那么有如下状态转移方程:\n\n$$\n\\begin{aligned}\nf[i] &= \\max(f[i - 1], 0) + nums[i] \\\\\ng[i] &= \\max(\\max(f[i - 1], 0) + nums[i] \\times nums[i], g[i - 1] + nums[i])\n\\end{aligned}\n$$\n\n最终答案即为所有 $max(f[i], g[i])$ 的最大值。\n\n由于 $f[i]$ 只与 $f[i - 1]$ 有关,因此我们可以只用两个变量来维护 $f[i]$ 和 $g[i]$ 的值,从而将空间复杂度降低到 $O(1)$。\n\n时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 $nums$ 的长度。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1747, "explanations": { "1": "We can use a self-join to find out the cases where each account logs in from different IP addresses on the same day. The conditions for joining are:\n\n- The account numbers are the same.\n- The IP addresses are different.\n- The login time of one record is within the login-logout time range of another record." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1748, "explanations": { "1": "我们可以用数组或哈希表 `cnt` 统计数组 `nums` 中每个数字出现的次数,然后遍历 `cnt`,对于出现次数为 1 的数字,将其加入答案。\n\n遍历结束后,返回答案即可。\n\n时间复杂度 $O(n)$,空间复杂度 $O(M)$。其中 $n$ 和 $m$ 分别是数组 `nums` 的长度和 `nums` 中的最大值。", "2": "" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(M)" }, { "problem_id": 1749, "explanations": { "1": "We define $f[i]$ to represent the maximum value of the subarray ending with $nums[i]$, and define $g[i]$ to represent the minimum value of the subarray ending with $nums[i]$. Then the state transition equation of $f[i]$ and $g[i]$ is as follows:\n\n$$\n\\begin{aligned}\nf[i] &= \\max(f[i - 1], 0) + nums[i] \\\\\ng[i] &= \\min(g[i - 1], 0) + nums[i]\n\\end{aligned}\n$$\n\nThe final answer is the maximum value of $max(f[i], |g[i]|)$.\n\nSince $f[i]$ and $g[i]$ are only related to $f[i - 1]$ and $g[i - 1]$, we can use two variables to replace the array, reducing the space complexity to $O(1)$.\n\nTime complexity $O(n)$, space complexity $O(1)$, where $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1750, "explanations": { "1": "We define two pointers $i$ and $j$ to point to the head and tail of the string $s$ respectively, then move them to the middle until the characters pointed to by $i$ and $j$ are not equal, then $\\max(0, j - i + 1)$ is the answer.\n\nThe time complexity is $O(n)$ and the space complexity is $O(1)$. Where $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1751, "explanations": { "1": "First, we sort the events by their start time in ascending order. Then, we define a function $\\text{dfs}(i, k)$, which represents the maximum total value achievable by attending at most $k$ events starting from the $i$-th event. The answer is $\\text{dfs}(0, k)$.\n\nThe calculation process of the function $\\text{dfs}(i, k)$ is as follows:\n\nIf we do not attend the $i$-th event, the maximum value is $\\text{dfs}(i + 1, k)$. If we attend the $i$-th event, we can use binary search to find the first event whose start time is greater than the end time of the $i$-th event, denoted as $j$. Then, the maximum value is $\\text{dfs}(j, k - 1) + \\text{value}[i]$. We take the maximum of the two options:\n\n$$\n\\text{dfs}(i, k) = \\max(\\text{dfs}(i + 1, k), \\text{dfs}(j, k - 1) + \\text{value}[i])\n$$\n\nHere, $j$ is the index of the first event whose start time is greater than the end time of the $i$-th event, which can be found using binary search.\n\nSince the calculation of $\\text{dfs}(i, k)$ involves calls to $\\text{dfs}(i + 1, k)$ and $\\text{dfs}(j, k - 1)$, we can use memoization to store the computed values and avoid redundant calculations.\n\nThe time complexity is $O(n \\times \\log n + n \\times k)$, and the space complexity is $O(n \\times k)$, where $n$ is the number of events.", "2": "We can convert the memoization approach in Solution 1 to dynamic programming.\n\nFirst, sort the events, this time by end time in ascending order. Then define $f[i][j]$ as the maximum total value by attending at most $j$ events among the first $i$ events. The answer is $f[n][k]$.\n\nFor the $i$-th event, we can choose to attend it or not. If we do not attend, the maximum value is $f[i][j]$. If we attend, we can use binary search to find the last event whose end time is less than the start time of the $i$-th event, denoted as $h$. Then the maximum value is $f[h + 1][j - 1] + \\text{value}[i]$. We take the maximum of the two options:\n\n$$\nf[i + 1][j] = \\max(f[i][j], f[h + 1][j - 1] + \\text{value}[i])\n$$\n\nHere, $h$ is the last event whose end time is less than the start time of the $i$-th event, which can be found by binary search.\n\nThe time complexity is $O(n \\times \\log n + n \\times k)$, and the space complexity is $O(n \\times k)$, where $n$ is the number of events.\n\nRelated problems:\n\n- [1235. Maximum Profit in Job Scheduling](https://github.com/doocs/leetcode/blob/main/solution/1200-1299/1235.Maximum%20Profit%20in%20Job%20Scheduling/README_EN.md)\n- [2008. Maximum Earnings From Taxi](https://github.com/doocs/leetcode/blob/main/solution/2000-2099/2008.Maximum%20Earnings%20From%20Taxi/README_EN.md)" }, "is_english": true, "time_complexity": "O(n \\times \\log n + n \\times k)", "space_complexity": "O(n \\times k)" }, { "problem_id": 1752, "explanations": { "1": "要满足题目要求,那么数组 `nums` 中最多只能存在一个元素,其值大于下一个元素,即 $nums[i] \\gt nums[i + 1]$。如果存在多个这样的元素,那么数组 `nums` 无法通过轮转得到。\n\n注意,数组 `nums` 最后一个元素的下一个元素是数组 `nums` 的第一个元素。\n\n时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 `nums` 的长度。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1753, "explanations": { "1": "每次贪心地从最大的两堆石子中取石头,直到至少有两堆石子为空。\n\n时间复杂度 $O(n)$,其中 $n$ 为石子总数。", "2": "我们不妨设 $a \\le b \\le c$,那么:\n\n- 当 $a + b \\le c$ 时,我们可以先从 $a$, $c$ 两堆中取石头,得到分数 $a$;再从 $b$, $c$ 两堆中取石头,得到分数 $b$,总分数为 $a + b$;\n- 当 $a + b \\gt c$ 时,这时我们每次会从 $c$ 以及 $a$ 和 $b$ 中较大的那一堆中取石头,最终将 $c$ 取空。此时 $a$ 和 $b$ 的大小差最多为 $1$。我们再从 $a$, $b$ 两堆中取石头,直到不能取为止,总分数为 $\\left \\lfloor \\frac{a + b + c}{2} \\right \\rfloor$。\n\n时间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": null }, { "problem_id": 1754, "explanations": { "1": "我们用指针 $i$ 和 $j$ 分别指向字符串 `word1` 和 `word2` 的第一个字符。然后循环,每次比较 $word1[i:]$ 和 $word2[j:]$ 的大小,如果 $word1[i:]$ 比 $word2[j:]$ 大,那么我们就将 $word1[i]$ 加入答案,否则我们就将 $word2[j]$ 加入答案。循环,直至 $i$ 到达字符串 `word1` 的末尾,或者 $j$ 到达字符串 `word2` 的末尾。\n\n然后我们将剩余的字符串加入答案即可。\n\n时间复杂度 $O(n^2)$。其中 $n$ 是字符串 `word1` 和 `word2` 的长度之和。" }, "is_english": false, "time_complexity": "O(n^2)", "space_complexity": null }, { "problem_id": 1755, "explanations": { "1": "每个数选或不选两种可能,所以 $n$ 个数就有 $2^n$ 种组合,由于 $n$ 最大为 $40$,枚举 $2^{40}$ 种组合显然会超时。\n\n我们可以把数组分成左右两部分,分别求出两部分所有子序列和,记为 $left$ 和 $right$。最后,只需找到最接近 $goal$ 的 $left[i] + right[j]$。\n\n时间复杂度 $O(n\\times 2^{n/2})$。\n\n相似题目:\n\n- [1774. 最接近目标价格的甜点成本](https://github.com/doocs/leetcode/blob/main/solution/1700-1799/1774.Closest%20Dessert%20Cost/README.md)", "2": "" }, "is_english": false, "time_complexity": "O(n\\times 2^{n/2})", "space_complexity": null }, { "problem_id": 1756, "explanations": { "1": "我们用一个数组 $q$ 维护当前队列中的元素,移动第 $k$ 个元素时,我们考虑不删除该元素,而是直接将其追加到数组末尾。如果不删除,我们如何知道第 $k$ 个元素在数组 $q$ 中的位置呢?\n\n我们可以用一个树状数组维护数组 $q$ 中每个位置的元素是否被删除,如果第 $i$ 个位置的元素被删除,那么我们更新树状数组中的第 $i$ 个位置,表示该位置被移动的次数增加 $1$。这样,我们每次要删除第 $k$ 个元素时,可以用二分查找,找到第一个满足 $i - tree.query(i) \\geq k$ 的位置 $i$,即为第 $k$ 个元素在数组 $q$ 中的位置。不妨记 $x=q[i]$,那么我们将 $x$ 追加到数组 $q$ 的末尾,同时更新树状数组中第 $i$ 个位置的值,表示该位置被移动的次数增加 $1$。最后,我们返回 $x$ 即可。\n\n时间复杂度 $(\\log ^2 n)$,空间复杂度 $O(n)$。其中 $n$ 为队列的长度。", "2": "" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1757, "explanations": { "1": "We can directly filter the product IDs where `low_fats` is `Y` and `recyclable` is `Y`." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1758, "explanations": { "1": "According to the problem, if the number of operations needed to obtain the alternating string `01010101...` is $\\textit{cnt}$, then the number of operations needed to obtain the alternating string `10101010...` is $n - \\textit{cnt}$.\n\nTherefore, we only need to traverse the string $s$ once, count the value of $\\textit{cnt}$, and the answer is $\\min(\\textit{cnt}, n - \\textit{cnt})$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1759, "explanations": { "1": "遍历字符串 $s$,用指针 $i$ 指向当前字符,指针 $j$ 指向下一个不同的字符,那么 $[i,..j-1]$ 区间内的字符都是相同的,假设 $cnt=j-i$,那么该区间内的同构子字符串个数为 $\\frac{(1 + cnt) \\times cnt}{2}$,将其累加到答案中即可。继续遍历,直到指针 $i$ 到达字符串末尾。\n\n遍历完字符串 $s$ 后,返回答案即可。注意答案的取模操作。\n\n时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为字符串 $s$ 的长度。", "2": "" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1760, "explanations": { "1": "This problem requires us to minimize the cost, which is the maximum number of balls in a single bag. As the maximum value increases, the number of operations decreases, making it easier to meet the condition.\n\nTherefore, we can use binary search to enumerate the maximum number of balls in a single bag and determine if it can be achieved within $\\textit{maxOperations}$ operations.\n\nSpecifically, we define the left boundary of the binary search as $l = 1$ and the right boundary as $r = \\max(\\textit{nums})$. Then we continuously perform binary search on the middle value $\\textit{mid} = \\frac{l + r}{2}$. For each $\\textit{mid}$, we calculate the number of operations needed. If the number of operations is less than or equal to $\\textit{maxOperations}$, it means $\\textit{mid}$ meets the condition, and we update the right boundary $r$ to $\\textit{mid}$. Otherwise, we update the left boundary $l$ to $\\textit{mid} + 1$.\n\nFinally, we return the left boundary $l$.\n\nThe time complexity is $O(n \\times \\log M)$, where $n$ and $M$ are the length and the maximum value of the array $\\textit{nums}$, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(1)" }, { "problem_id": 1761, "explanations": { "1": "We first store all edges in the adjacency matrix $\\textit{g}$, and then store the degree of each node in the array $\\textit{deg}$. Initialize the answer $\\textit{ans} = +\\infty$.\n\nThen enumerate all triplets $(i, j, k)$, where $i \\lt j \\lt k$. If $\\textit{g}[i][j] = \\textit{g}[j][k] = \\textit{g}[i][k] = 1$, it means these three nodes form a connected trio. In this case, update the answer to $\\textit{ans} = \\min(\\textit{ans}, \\textit{deg}[i] + \\textit{deg}[j] + \\textit{deg}[k] - 6)$.\n\nAfter enumerating all triplets, if the answer is still $+\\infty$, it means there is no connected trio in the graph, return $-1$. Otherwise, return the answer.\n\nThe time complexity is $O(n^3)$, and the space complexity is $O(n^2)$. Here, $n$ is the number of nodes." }, "is_english": true, "time_complexity": "O(n^3)", "space_complexity": "O(n^2)" }, { "problem_id": 1762, "explanations": { "1": "We traverse the array $\\textit{height}$ in reverse order for each element $v$, comparing $v$ with the maximum element $mx$ on the right. If $mx \\lt v$, it means all elements to the right are smaller than the current element, so the current position can see the ocean and is added to the result array $\\textit{ans}$. Then we update $mx$ to $v$.\n\nAfter the traversal, return $\\textit{ans}$ in reverse order.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. Ignoring the space consumption of the answer array, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1763, "explanations": { "1": "我们可以直接枚举所有子串的起点位置 $i$,找到以该位置所在的字符为首字符的所有子串,用哈希表 $s$ 记录子串的所有字符。\n\n如果子串中存在一个字母找不到对应的大写字母或者小写字母,那么不满足条件,否则取最长的且最早出现的子串。\n\n时间复杂度 $O(n^2 \\times C)$,空间复杂度 $O(C)$。其中 $n$ 为字符串 $s$ 的长度,而 $C$ 为字符集的大小。", "2": "与方法一类似,我们可以直接枚举所有子串的起点位置 $i$,找到以该位置所在的字符为首字符的所有子串,用两个整数 $lower$ 和 $upper$ 分别记录子串中小写字母和大写字母的出现情况。\n\n判断子串是否满足条件,只需要判断 $lower$ 和 $upper$ 中对应的位是否都为 $1$ 即可。\n\n时间复杂度 $O(n^2)$,空间复杂度 $O(1)$。其中 $n$ 为字符串 $s$ 的长度。" }, "is_english": false, "time_complexity": "O(n^2 \\times C)", "space_complexity": "O(C)" }, { "problem_id": 1764, "explanations": { "1": "我们贪心地枚举 `nums` 中每一个数 $nums[j]$ 作为子数组的开始,判断其是否与当前 $groups[i]$ 匹配,是则将指针 $i$ 往后移一位,将指针 $j$ 往后移动 $groups[i].length$ 位,否则将指针 $j$ 往后移动一位。\n\n如果 $i$ 走到了 $groups.length$,说明所有的子数组都匹配上了,返回 `true`,否则返回 `false`。\n\n时间复杂度 $O(n \\times m)$,空间复杂度 $O(1)$。其中 $n$ 和 $m$ 分别为 `groups` 和 `nums` 的长度。" }, "is_english": false, "time_complexity": "O(n \\times m)", "space_complexity": "O(1)" }, { "problem_id": 1765, "explanations": { "1": "根据题目描述,水域的高度必须是 $0$,而任意相邻格子的高度差至多为 $1$。因此,我们可以从所有水域格子出发,用 BFS 搜索相邻且未访问过的格子,将其高度置为当前格子的高度再加一。\n\n最后返回结果矩阵即可。\n\n时间复杂度 $O(m \\times n)$,空间复杂度 $O(m \\times n)$。其中 $m$ 和 $n$ 分别是整数矩阵 `isWater` 的行数和列数。", "2": "" }, "is_english": false, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 1766, "explanations": { "1": "Since the range of $nums[i]$ in the problem is $[1, 50]$, we can preprocess all the coprime numbers for each number and record them in the array $f$, where $f[i]$ represents all the coprime numbers of $i$.\n\nNext, we can use a backtracking method to traverse the entire tree from the root node. For each node $i$, we can get all the coprime numbers of $nums[i]$ through the array $f$. Then we enumerate all the coprime numbers of $nums[i]$, find the ancestor node $t$ that has appeared and has the maximum depth, which is the nearest coprime ancestor node of $i$. Here we can use a stack array $stks$ of length $51$ to get each appeared value $v$ and its depth. The top element of each stack $stks[v]$ is the nearest ancestor node with the maximum depth.\n\nThe time complexity is $O(n \\times M)$, and the space complexity is $O(M^2 + n)$. Where $n$ is the number of nodes, and $M$ is the maximum value of $nums[i]$, in this problem $M = 50$." }, "is_english": true, "time_complexity": "O(n \\times M)", "space_complexity": "O(M^2 + n)" }, { "problem_id": 1767, "explanations": { "1": "We can generate a table recursively that contains all pairs of (parent task, child task), and then use a left join to find the pairs that have not been executed." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1768, "explanations": { "1": "We traverse the two strings `word1` and `word2`, take out the characters one by one, and append them to the result string. The Python code can be simplified into one line.\n\nThe time complexity is $O(m + n)$, where $m$ and $n$ are the lengths of the two strings respectively. Ignoring the space consumption of the answer, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m + n)", "space_complexity": "O(1)" }, { "problem_id": 1769, "explanations": { "1": "我们可以预处理出每个位置 $i$ 左边的小球移动到 $i$ 的操作数,记为 $left[i]$;每个位置 $i$ 右边的小球移动到 $i$ 的操作数,记为 $right[i]$。那么答案数组的第 $i$ 个元素就是 $left[i] + right[i]$。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为 `boxes` 的长度。\n\n我们还可以进一步优化空间复杂度,只用一个答案数组 $ans$ 以及若干个变量即可。\n\n时间复杂度 $O(n)$,忽略答案数组的空间消耗,空间复杂度 $O(1)$。其中 $n$ 为 `boxes` 的长度。", "2": "", "3": "" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1770, "explanations": { "1": "我们设计一个函数 $dfs(i, j)$,表示从 `nums` 数组头部第 $i$ 个元素开始,从 `nums` 数组尾部第 $j$ 个元素开始,能够获得的最大分数。那么答案就是 $dfs(0, 0)$。\n\n函数 $dfs(i, j)$ 的计算过程如下:\n\n- 如果 $i \\geq m$ 或者 $j \\geq m$,或者 $i + j \\geq m$,说明已经没有元素可以选择了,返回 $0$。\n- 否则,我们可以选择 `nums` 数组头部第 $i$ 个元素,那么能够获取的最大分数为 $nums[i] \\times multipliers[i + j] + dfs(i + 1, j)$;或者我们可以选择 `nums` 数组尾部第 $j$ 个元素,那么能够获取的最大分数为 $nums[n - j - 1] \\times multipliers[i + j] + dfs(i, j + 1)$。我们取两者的最大值作为 $dfs(i, j)$ 的返回值。\n\n我们可以使用记忆化搜索来实现上述递归过程,其中 `f` 数组用于存储函数 $dfs(i, j)$ 的返回值,防止重复计算。\n\n时间复杂度 $O(m^2)$,空间复杂度 $O(m^2)$。其中 $m$ 为 `multipliers` 数组的长度。", "2": "我们可以将方法一中的记忆化搜索改写为动态规划的形式。\n\n我们用 $f[i][j]$ 表示取数组 $nums$ 的前 $i$ 个元素,以及取数组 $nums$ 的后 $j$ 个元素,能够获得的最大分数。初始时 $f[0][0] = 0$,其余元素均为 $-\\infty$。答案为 $\\max_{0 \\leq i \\leq m} f[i][m-i]$。\n\n考虑 $f[i][j]$,那么当前我们可以选择 `nums` 数组头部的第 $i$ 个元素,或者选择 `nums` 数组尾部的第 $j$ 个元素。如果选择了 `nums` 数组头部的第 $i$ 个元素,那么能够获得的最大分数为 $f[i-1][j] + nums[i-1] \\times multipliers[i+j-1]$;如果选择了 `nums` 数组尾部的第 $j$ 个元素,那么能够获得的最大分数为 $f[i][j-1] + nums[n-j] \\times multipliers[i+j-1]$。我们取两者的最大值作为 $f[i][j]$ 的值。如果 $i + j = m$,我们我们更新答案 $ans = \\max(ans, f[i][j])$。\n\n最后返回答案 $ans$ 即可。\n\n时间复杂度 $O(m^2)$,空间复杂度 $O(m^2)$。其中 $m$ 为 `multipliers` 数组的长度。" }, "is_english": false, "time_complexity": "O(m^2)", "space_complexity": "O(m^2)" }, { "problem_id": 1771, "explanations": { "1": "First, we concatenate strings `word1` and `word2` to get string $s$. Then we can transform the problem into finding the length of the longest palindromic subsequence in string $s$. However, when calculating the final answer, we need to ensure that at least one character in the palindrome string comes from `word1` and another character comes from `word2`.\n\nWe define $f[i][j]$ as the length of the longest palindromic subsequence in the substring of string $s$ with index range $[i, j]$.\n\nIf $s[i] = s[j]$, then $s[i]$ and $s[j]$ must be in the longest palindromic subsequence, at this time $f[i][j] = f[i + 1][j - 1] + 2$. At this point, we also need to judge whether $s[i]$ and $s[j]$ come from `word1` and `word2`. If so, we update the maximum value of the answer to $ans=\\max(ans, f[i][j])$.\n\nIf $s[i] \\neq s[j]$, then $s[i]$ and $s[j]$ will definitely not appear in the longest palindromic subsequence at the same time, at this time $f[i][j] = max(f[i + 1][j], f[i][j - 1])$.\n\nFinally, we return the answer.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ is the length of string $s$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 1772, "explanations": { "1": "We traverse `responses`, and for each word in `responses[i]`, we temporarily store it in a hash table `vis`. Next, we record the words in `vis` into the hash table `cnt`, recording the number of times each word appears.\n\nNext, we use custom sorting to sort the words in `features` in descending order of occurrence. If the number of occurrences is the same, we sort them in ascending order of the index where they appear.\n\nThe time complexity is $O(n \\times \\log n)$, where $n$ is the length of `features`." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": null }, { "problem_id": 1773, "explanations": { "1": "由于 `ruleKey` 只可能是 `\"type\"`、`\"color\"` 或 `\"name\"`,我们可以直接取 `ruleKey` 的第一个字符来确定 `item` 的下标 $i$。然后遍历 `items` 数组,统计 `item[i] == ruleValue` 的个数即可。\n\n时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为 `items` 的长度。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1774, "explanations": { "1": "每种类型的配料最多可以选两份,因此,我们可以复制一份配料,然后利用 `DFS` 枚举子集之和。在实现上,我们可以只枚举一半的配料的所有子集和,然后在另一半配料子集和中,利用二分查找找到最接近的配料。\n\n时间复杂度 $O(n \\times 2^m \\times \\log {2^m})$。\n\n相似题目:\n\n- [1755. 最接近目标值的子序列和](https://github.com/doocs/leetcode/blob/main/solution/1700-1799/1755.Closest%20Subsequence%20Sum/README.md)" }, "is_english": false, "time_complexity": "O(n \\times 2^m \\times \\log {2^m})", "space_complexity": null }, { "problem_id": 1775, "explanations": { "1": "我们用 $s_1$ 和 $s_2$ 分别表示数组 `nums1` 和 `nums2` 的和。\n\n如果 $s_1 = s_2$,则不需要任何操作,直接返回 $0$。否则,我们不妨设 $s_1 \\lt s_2$,即 $nums_1$ 中的元素和小于 $nums_2$ 中的元素和,那么两个数组元素和的差值 $d=s_2-s_1$。\n\n要使得两个数组元素和相等,我们需要对 `nums1` 中的元素进行增大操作,对 `nums2` 中的元素进行减小操作。\n\n对于 `nums1` 中的每个元素 $v$,我们最多可以将其增大到 $6$,那么 $v$ 可以增大的量为 $6-v$。对于 `nums2` 中的每个元素 $v$,我们最多可以将其减小到 $1$,那么 $v$ 可以减小的量为 $v-1$。\n\n我们将每个元素的变化量放入数组 `arr` 中,然后对数组 `arr` 进行降序排列。\n\n接下来,我们从数组 `arr` 的第一个元素开始,贪心地将 $d$ 减去每个元素的变化量,直到 $d \\leq 0$,返回此时的操作次数即可。\n\n遍历结束后,如果 $d \\gt 0$,说明无法使得两个数组元素和相等,返回 $-1$。\n\n时间复杂度 $O((m+n) \\times \\log (m + n))$,空间复杂度 $O(m+n)$。其中 $m$ 和 $n$ 分别为数组 `nums1` 和 `nums2` 的长度。", "2": "方法一中,我们需要创建数组 `arr` 并进行排序,时空复杂度较高。由于数组 `arr` 中元素的范围为 $[0,..5]$,因此我们创建一个长度为 $6$ 的数组 `cnt`,用于统计数组 `arr` 中每个元素的数量,也即每个最大变化量的元素的数量。\n\n接下来,我们从最大变化量 $i=5$ 开始,贪心地将 $d$ 减去最大变化量,直到 $d \\leq 0$,返回此时的操作次数即可。\n\n时间复杂度 $O(m+n)$,空间复杂度 $O(C)$。其中 $m$ 和 $n$ 分别为数组 `nums1` 和 `nums2` 的长度。本题中 $C=6$。" }, "is_english": false, "time_complexity": "O((m+n) \\times \\log (m + n))", "space_complexity": "O(m+n)" }, { "problem_id": 1776, "explanations": { "1": "由于每一辆车最终追上其右边第一辆车的时间与其左边的车没有关系,因此,我们可以从右往左遍历,计算每辆车与其右边第一辆车相遇的时间。\n\n具体地,我们维护一个栈,栈中存放的是车辆的编号,栈顶元素表示当前最慢的车辆编号,栈底元素表示当前最快的车辆编号。\n\n当我们遍历到第 $i$ 辆车时,如果第 $i$ 辆车的速度大于栈顶元素对应的车辆 $j$ 的速度,此时我们计算两车相遇的时间,记为 $t$。如果车辆 $j$ 与右边车辆不会相遇,或者 $t$ 小于等于 $j$ 与右辆车相遇的时间,说明车辆 $i$ 可以在 $t$ 时间追上车辆 $j$,更新答案。否则,说明车辆 $i$ 不会与车辆 $j$ 相遇,我们将车辆 $j$ 出栈,继续判断车辆 $i$ 与栈顶元素对应的车辆相遇的时间。如果栈为空,说明车辆 $i$ 不会与任何车辆相遇,更新答案为 $-1$。最后,将车辆 $i$ 入栈。\n\n遍历完所有车辆后,即可得到答案。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为车辆数量。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1777, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1778, "explanations": { "1": "We can assume that the robot starts from the coordinate $(0, 0)$. Then, we can use DFS to find all reachable coordinates and record them in the hash table $vis$. In addition, we also need to record the coordinates of the endpoint $target$.\n\nIf the endpoint cannot be found, we directly return $-1$. Otherwise, we can use BFS to find the shortest path.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Where $m$ and $n$ are the number of rows and columns of the grid, respectively.\n\nSimilar problems:\n\n- [1810. Minimum Path Cost in a Hidden Grid](https://github.com/doocs/leetcode/blob/main/solution/1800-1899/1810.Minimum%20Path%20Cost%20in%20a%20Hidden%20Grid/README_EN.md)" }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 1779, "explanations": { "1": "直接遍历 `points` 数组,对于 $points[i]$,如果 $points[i][0] = x$ 或者 $points[i][1] = y$,则说明 $points[i]$ 是有效点,计算曼哈顿距离,更新最小距离和最小距离的下标。\n\n时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为 `points` 数组的长度。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1780, "explanations": { "1": "We find that if a number $n$ can be expressed as the sum of several \"different\" powers of three, then in the ternary representation of $n$, each digit can only be $0$ or $1$.\n\nTherefore, we convert $n$ to ternary and then check whether each digit is $0$ or $1$. If not, then $n$ cannot be expressed as the sum of several powers of three, and we directly return $\\textit{false}$; otherwise, $n$ can be expressed as the sum of several powers of three, and we return $\\textit{true}$.\n\nThe time complexity is $O(\\log_3 n)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log_3 n)", "space_complexity": "O(1)" }, { "problem_id": 1781, "explanations": { "1": "Enumerate the starting position $i$ of each substring, find all substrings with the character at this starting position as the left endpoint, then calculate the beauty value of each substring, and accumulate it to the answer.\n\nThe time complexity is $O(n^2 \\times C)$, and the space complexity is $O(C)$. Here, $n$ is the length of the string, and $C$ is the size of the character set. In this problem, $C = 26$.", "2": "" }, "is_english": true, "time_complexity": "O(n^2 \\times C)", "space_complexity": "O(C)" }, { "problem_id": 1782, "explanations": { "1": "From the problem, we know that the number of edges connected to the point pair $(a, b)$ is equal to the \"number of edges connected to $a$\" plus the \"number of edges connected to $b$\", minus the number of edges connected to both $a$ and $b$.\n\nTherefore, we can first use the array $cnt$ to count the number of edges connected to each point, and use the hash table $g$ to count the number of each point pair.\n\nThen, for each query $q$, we can enumerate $a$. For each $a$, we can find the first $b$ that satisfies $cnt[a] + cnt[b] > q$ through binary search, add the number to the current query answer, and then subtract some duplicate edges.\n\nThe time complexity is $O(q \\times (n \\times \\log n + m))$, and the space complexity is $O(n + m)$. Where $n$ and $m$ are the number of points and edges respectively, and $q$ is the number of queries." }, "is_english": true, "time_complexity": "O(q \\times (n \\times \\log n + m))", "space_complexity": "O(n + m)" }, { "problem_id": 1783, "explanations": { "1": "We can use `UNION ALL` to merge all player IDs who won Grand Slam titles into a table `T`, then use an equi-join `JOIN` to join `T` table with `Players` table on `player_id`, and finally use `GROUP BY` and `COUNT` to count the number of Grand Slam titles won by each player.", "2": "" }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1784, "explanations": { "1": "Since the string $s$ has no leading zeros, $s$ starts with `'1'`.\n\nIf the string $s$ contains the substring `\"01\"`, then $s$ is of the form `\"1...01...\"`, which means $s$ has at least two separate segments of consecutive `'1'`s, violating the condition — return $\\textit{false}$.\n\nIf the string $s$ does not contain the substring `\"01\"`, then $s$ can only be of the form `\"1..1000...\"`, which means $s$ has exactly one segment of consecutive `'1'`s, satisfying the condition — return $\\textit{true}$.\n\nTherefore, we only need to check whether the string $s$ contains the substring `\"01\"`.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1785, "explanations": { "1": "First, we calculate the sum of the array elements $s$, and then calculate the difference $d$ between $s$ and $goal$.\n\nThe number of elements to be added is the absolute value of $d$ divided by $limit$ and rounded up, that is, $\\lceil \\frac{|d|}{limit} \\rceil$.\n\nNote that in this problem, the data range of array elements is $[-10^6, 10^6]$, the maximum number of elements is $10^5$, the total sum $s$ and the difference $d$ may exceed the range of 32-bit integers, so we need to use 64-bit integers.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1786, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1787, "explanations": { "1": "Notice that after modifying the array `nums`, the XOR result of any interval of length $k$ is equal to $0$. Therefore, for any $i$, we have:\n\n$$\nnums[i] \\oplus nums[i+1] \\oplus ... \\oplus nums[i+k-1] = 0\n$$\n\nand\n\n$$\nnums[i+1] \\oplus nums[i+2] \\oplus ... \\oplus nums[i+k] = 0\n$$\n\nCombining the two equations and the properties of XOR operation, we can get $nums[i] \\oplus nums[i+k] = 0$, which means $nums[i]=nums[i+k]$. We find that the elements in the modified array `nums` are cyclic with a period of $k$. The numbers congruent modulo $k$ can only take a fixed value, and the XOR result of the first $k$ numbers must be $0$.\n\nFirst, we count each group $i$, the number of elements in each group is $size[i]$, and the number of elements with value $v$ in each group is $cnt[i][v]$.\n\nNext, we can use dynamic programming to solve it. Let $f[i][j]$ represent the minimum number of modifications with the XOR sum of the first $i+1$ groups being $j$. Since the value of each group is only related to the value of the previous group, we can use a rolling array to optimize the space complexity.\n\nRedefine $f[j]$ to represent the minimum number of modifications with the XOR sum being $j$ when processing to the current group.\n\nWhen transitioning states, there are two choices: one is to modify all the numbers in the current group to the same value, then we can choose the one with the smallest previous cost, plus the number of elements $size[i]$ in this group, the cost is $\\min{f[0..n]} + size[i]$; the second is to modify all the numbers in the current group to some value $j$ of the current group, enumerate $j$ and the element $v$ of the current group, then the previous cost is $f[j \\oplus v]$, the cost is $f[j \\oplus v] + size[i] - cnt[i][v]$. Take the minimum value.\n\nThe final answer is $f[0]$.\n\nThe time complexity is $O(2^{C}\\times k + n)$. Where $n$ is the length of the array `nums`, and $C$ is the maximum number of bits in the binary representation of the elements in `nums`, in this problem $C=10$." }, "is_english": true, "time_complexity": "O(2^{C}\\times k + n)", "space_complexity": null }, { "problem_id": 1788, "explanations": { "1": "We use a hash table $d$ to record the first occurrence of each aesthetic value, and a prefix sum array $s$ to record the sum of the aesthetic values before the current position. If an aesthetic value $v$ appears at positions $i$ and $j$ (where $i \\lt j$), then we can get a valid garden $[i+1,j]$, whose aesthetic value is $s[i] - s[j + 1] + v \\times 2$. We use this value to update the answer. Otherwise, we record the current position $i$ of the aesthetic value in the hash table $d$. Next, we update the prefix sum. If the aesthetic value $v$ is negative, we treat it as $0$.\n\nAfter traversing all the aesthetic values, we can get the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of flowers." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1789, "explanations": { "1": "We can first query all employees who already have a direct department, and then query all employees who belong to only one department. Finally, we can merge the two results using `UNION`." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1790, "explanations": { "1": "We use a variable $cnt$ to record the number of characters at the same position in the two strings that are different. If the two strings meet the requirements of the problem, then $cnt$ must be $0$ or $2$. We also use two character variables $c1$ and $c2$ to record the characters that are different at the same position in the two strings.\n\nWhile traversing the two strings simultaneously, for two characters $a$ and $b$ at the same position, if $a \\ne b$, then $cnt$ is incremented by $1$. If at this time $cnt$ is greater than $2$, or $cnt$ is $2$ and $a \\ne c2$ or $b \\ne c1$, then we directly return `false`. Note to record $c1$ and $c2$.\n\nAt the end of the traversal, if $cnt \\neq 1$, return `true`.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1791, "explanations": { "1": "The characteristic of the center point is that it is connected to all other points. Therefore, as long as we compare the points of the first two edges, if there are the same points, then this point is the center point.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 1792, "explanations": { "1": "Suppose a class currently has a pass rate of $\\frac{a}{b}$. If we arrange a smart student into this class, then the pass rate of the class will become $\\frac{a+1}{b+1}$. We can find that the increment of the pass rate is $\\frac{a+1}{b+1} - \\frac{a}{b}$.\n\nWe maintain a max-heap, which stores the increment of the pass rate for each class.\n\nPerform `extraStudents` operations, each time taking a class from the top of the heap, adding $1$ to both the number of students and the number of passes in this class, then recalculating the increment of the pass rate of this class and putting it back into the heap. Repeat this process until all students are allocated.\n\nFinally, we sum up the pass rates of all classes, and then divide by the number of classes to get the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the number of classes." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1793, "explanations": { "1": "We can enumerate each element $nums[i]$ in $nums$ as the minimum value of the subarray, and use a monotonic stack to find the first position $left[i]$ on the left that is less than $nums[i]$ and the first position $right[i]$ on the right that is less than or equal to $nums[i]$. Then, the score of the subarray with $nums[i]$ as the minimum value is $nums[i] \\times (right[i] - left[i] - 1)$.\n\nIt should be noted that the answer can only be updated when the left and right boundaries $left[i]$ and $right[i]$ satisfy $left[i]+1 \\leq k \\leq right[i]-1$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1794, "explanations": { "1": "The problem actually asks us to find a smallest index $i$ and a largest index $j$ such that $firstString[i]$ equals $secondString[j]$, and the value of $i - j$ is the smallest among all index pairs that meet the conditions.\n\nTherefore, we first use a hash table $last$ to record the index of the last occurrence of each character in $secondString$. Then we traverse $firstString$. For each character $c$, if $c$ has appeared in $secondString$, we calculate $i - last[c]$. If the value of $i - last[c]$ is less than the current minimum value, we update the minimum value and set the answer to 1. If the value of $i - last[c]$ equals the current minimum value, we increment the answer by 1.\n\nThe time complexity is $O(m + n)$, and the space complexity is $O(C)$. Here, $m$ and $n$ are the lengths of $firstString$ and $secondString$ respectively, and $C$ is the size of the character set. In this problem, $C = 26$." }, "is_english": true, "time_complexity": "O(m + n)", "space_complexity": "O(C)" }, { "problem_id": 1795, "explanations": { "1": "We can select the products and prices for each store, and then use the `UNION` operator to combine the results." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1796, "explanations": { "1": "We define $a$ and $b$ to represent the largest and second largest numbers in the string, initially $a = b = -1$.\n\nWe traverse the string $s$. If the current character is a digit, we convert it to a number $v$. If $v > a$, it means that $v$ is the largest number currently appearing, we update $b$ to $a$, and update $a$ to $v$; if $v < a$, it means that $v$ is the second largest number currently appearing, we update $b$ to $v$.\n\nAfter the traversal, we return $b$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$.", "2": "We can use an integer $mask$ to mark the numbers that appear in the string, where the $i$-th bit of $mask$ indicates whether the number $i$ has appeared.\n\nWe traverse the string $s$. If the current character is a digit, we convert it to a number $v$, and set the $v$-th bit of $mask$ to $1$.\n\nFinally, we traverse $mask$ from high to low, find the second bit that is $1$, and the corresponding number is the second largest number. If there is no second largest number, return $-1$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1797, "explanations": { "1": "We can simply maintain a hash table $d$, where the key is `tokenId` and the value is the expiration time.\n\n- During the `generate` operation, we store `tokenId` as the key and `currentTime + timeToLive` as the value in the hash table $d$.\n- During the `renew` operation, if `tokenId` is not in the hash table $d$, or `currentTime >= d[tokenId]`, we ignore this operation; otherwise, we update `d[tokenId]` to `currentTime + timeToLive`.\n- During the `countUnexpiredTokens` operation, we traverse the hash table $d$ and count the number of unexpired `tokenId`.\n\nIn terms of time complexity, both `generate` and `renew` operations have a time complexity of $O(1)$, and the `countUnexpiredTokens` operation has a time complexity of $O(n)$, where $n$ is the number of key-value pairs in the hash table $d$.\n\nThe space complexity is $O(n)$, where $n$ is the number of key-value pairs in the hash table $d$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(n)" }, { "problem_id": 1798, "explanations": { "1": "First, we sort the array. Then we define $ans$ as the current number of consecutive integers that can be constructed, initialized to $1$.\n\nWe traverse the array, for the current element $v$, if $v > ans$, it means that we cannot construct $ans+1$ consecutive integers, so we directly break the loop and return $ans$. Otherwise, it means that we can construct $ans+v$ consecutive integers, so we update $ans$ to $ans+v$.\n\nFinally, we return $ans$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 1799, "explanations": { "1": "We can preprocess to get the greatest common divisor of any two numbers in the array `nums`, stored in the two-dimensional array $g$, where $g[i][j]$ represents the greatest common divisor of $nums[i]$ and $nums[j]$.\n\nThen define $f[k]$ to represent the maximum score that can be obtained when the state after the current operation is $k$. Suppose $m$ is the number of elements in the array `nums`, then there are a total of $2^m$ states, that is, the range of $k$ is $[0, 2^m - 1]$.\n\nEnumerate all states from small to large, for each state $k$, first determine whether the number of $1$s in the binary bits of this state $cnt$ is even, if so, perform the following operations:\n\nEnumerate the positions where the binary bits in $k$ are 1, suppose they are $i$ and $j$, then the elements at positions $i$ and $j$ can perform one operation, and the score that can be obtained at this time is $\\frac{cnt}{2} \\times g[i][j]$, update the maximum value of $f[k]$.\n\nThe final answer is $f[2^m - 1]$.\n\nThe time complexity is $O(2^m \\times m^2)$, and the space complexity is $O(2^m)$. Here, $m$ is the number of elements in the array `nums`." }, "is_english": true, "time_complexity": "O(2^m \\times m^2)", "space_complexity": "O(2^m)" }, { "problem_id": 1800, "explanations": { "1": "We use a variable $t$ to record the current sum of the ascending subarray, and a variable $ans$ to record the maximum sum of the ascending subarray.\n\nTraverse the array $nums$:\n\nIf the current element is the first element of the array, or the current element is greater than the previous one, then add the current element to the sum of the current ascending subarray, i.e., $t = t + nums[i]$, and update the maximum sum of the ascending subarray $ans = \\max(ans, t)$. Otherwise, the current element does not satisfy the condition of the ascending subarray, so reset the sum $t$ of the current ascending subarray to the current element, i.e., $t = nums[i]$.\n\nAfter the traversal, return the maximum sum of the ascending subarray $ans$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1801, "explanations": { "1": "We can use a priority queue (max-min heap) to maintain the current backlog of orders, where the max heap `buy` maintains the backlog of purchase orders, and the min heap `sell` maintains the backlog of sales orders. Each element in the heap is a tuple $(price, amount)$, indicating that the number of orders at price `price` is `amount`.\n\nNext, we traverse the order array `orders`, and simulate according to the problem's requirements.\n\nAfter the traversal, we add the order quantities in `buy` and `sell`, which is the final backlog of orders. Note that the answer may be very large, so we need to take the modulus of $10^9 + 7$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of `orders`." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1802, "explanations": { "1": "According to the problem description, if we determine the value of $nums[index]$ as $x$, we can find a minimum array sum. That is, the elements on the left side of $index$ in the array decrease from $x-1$ to $1$, and if there are remaining elements, the remaining elements are all $1$; similarly, the elements at $index$ and on the right side of the array decrease from $x$ to $1$, and if there are remaining elements, the remaining elements are all $1$.\n\nIn this way, we can calculate the sum of the array. If the sum is less than or equal to $maxSum$, then the current $x$ is valid. As $x$ increases, the sum of the array will also increase, so we can use the binary search method to find the maximum $x$ that meets the conditions.\n\nTo facilitate the calculation of the sum of the elements on the left and right sides of the array, we define a function $sum(x, cnt)$, which represents the sum of an array with $cnt$ elements and a maximum value of $x$. The function $sum(x, cnt)$ can be divided into two cases:\n\n- If $x \\geq cnt$, then the sum of the array is $\\frac{(x + x - cnt + 1) \\times cnt}{2}$\n- If $x \\lt cnt$, then the sum of the array is $\\frac{(x + 1) \\times x}{2} + cnt - x$\n\nNext, define the left boundary of the binary search as $left = 1$, the right boundary as $right = maxSum$, and then binary search for the value $mid$ of $nums[index]$. If $sum(mid - 1, index) + sum(mid, n - index) \\leq maxSum$, then the current $mid$ is valid, we can update $left$ to $mid$, otherwise we update $right$ to $mid - 1$.\n\nFinally, return $left$ as the answer.\n\nThe time complexity is $O(\\log M)$, where $M=maxSum$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log M)", "space_complexity": "O(1)" }, { "problem_id": 1803, "explanations": { "1": "For this kind of problem that counts the interval $[low, high]$, we can consider converting it into counting $[0, high]$ and $[0, low - 1]$, and then subtracting the latter from the former to get the answer.\n\nIn this problem, we can count how many pairs of numbers have an XOR value less than $high+1$, and then count how many pairs of numbers have an XOR value less than $low$. The difference between these two counts is the number of pairs whose XOR value is in the interval $[low, high]$.\n\nMoreover, for array XOR counting problems, we can usually use a \"0-1 Trie\" to solve them.\n\nThe definition of the Trie node is as follows:\n\n- `children[0]` and `children[1]` represent the left and right child nodes of the current node, respectively;\n- `cnt` represents the number of numbers ending with the current node.\n\nIn the Trie, we also define the following two functions:\n\nOne function is $insert(x)$, which inserts the number $x$ into the Trie. This function inserts the number $x$ into the \"0-1 Trie\" in the order of binary bits from high to low. If the current binary bit is $0$, it is inserted into the left child node, otherwise, it is inserted into the right child node. Then the count value $cnt$ of the node is increased by $1$.\n\nAnother function is $search(x, limit)$, which searches for the count of numbers in the Trie that have an XOR value with $x$ less than $limit$. This function starts from the root node `node` of the Trie, traverses the binary bits of $x$ from high to low, and denotes the current binary bit of $x$ as $v$. If the current binary bit of $limit$ is $1$, we can directly add the count value $cnt$ of the child node that has the same binary bit $v$ as $x$ to the answer, and then move the current node to the child node that has a different binary bit $v$ from $x$, i.e., `node = node.children[v ^ 1]`. Continue to traverse the next bit. If the current binary bit of $limit$ is $0$, we can only move the current node to the child node that has the same binary bit $v$ as $x$, i.e., `node = node.children[v]`. Continue to traverse the next bit. After traversing the binary bits of $x$, return the answer.\n\nWith the above two functions, we can solve this problem.\n\nWe traverse the array `nums`. For each number $x$, we first search in the Trie for the count of numbers that have an XOR value with $x$ less than $high+1$, and then search in the Trie for the count of pairs that have an XOR value with $x$ less than $low$, and add the difference between the two counts to the answer. Then insert $x$ into the Trie. Continue to traverse the next number $x$ until the array `nums` is traversed. Finally, return the answer.\n\nThe time complexity is $O(n \\times \\log M)$, and the space complexity is $O(n \\times \\log M)$. Here, $n$ is the length of the array `nums`, and $M$ is the maximum value in the array `nums`. In this problem, we directly take $\\log M = 16$." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(n \\times \\log M)" }, { "problem_id": 1804, "explanations": { "1": "Each node in the Trie includes three parts:\n\n1. An array of pointers `children` pointing to child nodes. For this problem, the array length is 26, which is the number of lowercase English letters. `children[0]` corresponds to the lowercase letter a, ..., `children[25]` corresponds to the lowercase letter z.\n1. An int variable `v`, representing the number of strings ending with this node.\n1. An int variable `pv`, representing the number of strings with this node as the prefix node.\n\n### 1. Insert String\n\nWe start from the root of the Trie and insert the string. For the child node corresponding to the current character, there are two cases:\n\n- The child node exists. Move to the child node along the pointer and continue to process the next character.\n- The child node does not exist. Create a new child node, record it in the corresponding position of the `children` array, then move to the child node along the pointer, and increase the `pv` value of the child node by 1. Continue to search for the next character.\n\nRepeat the above steps until the last character of the string is processed, then increase the `v` value of the current node by 1.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string.\n\n### 2. Search Prefix\n\nWe start from the root of the Trie and search for the prefix. For the child node corresponding to the current character, there are two cases:\n\n- The child node exists. Move to the child node along the pointer and continue to search for the next character.\n- The child node does not exist. This means that the Trie does not contain this prefix, return a null pointer.\n\nRepeat the above steps until a null pointer is returned or the last character of the prefix is searched.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string.\n\n### 3. Remove String\n\nWe start from the root node of the Trie, and sequentially reduce the `pv` value of the corresponding child node by 1, until the last character of the string is searched. Then reduce the `v` value of the current node by 1.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": null }, { "problem_id": 1805, "explanations": { "1": "Traverse the string `word`, find the start and end positions of each integer, cut out this substring, and store it in the hash set $s$.\n\nAfter the traversal, return the size of the hash set $s$.\n\n> Note, the integer represented by each substring may be very large, we cannot directly convert it to an integer. Therefore, we can remove the leading zeros of each substring before storing it in the hash set.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string `word`." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1806, "explanations": { "1": "We observe the change pattern of the numbers and find that:\n\n1. The even-indexed numbers of the new array are the numbers in the first half of the original array in order;\n1. The odd-indexed numbers of the new array are the numbers in the second half of the original array in order.\n\nThat is, if the index $i$ of a number in the original array is in the range `[0, n >> 1)`, then the new index of this number is `i << 1`; otherwise, the new index is `(i - (n >> 1)) << 1 | 1`.\n\nIn addition, the path of number movement is the same in each round of operation. As long as a number (except for numbers $0$ and $n-1$) returns to its original position, the entire sequence will be consistent with the previous one.\n\nTherefore, we choose the number $1$, whose initial index is also $1$. Each time we move the number $1$ to a new position, until the number $1$ returns to its original position, we can get the minimum number of operations.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1807, "explanations": { "1": "First, we use a hash table $d$ to record the key-value pairs in `knowledge`.\n\nThen we traverse the string $s$. If the current character is an open parenthesis `'('`, we start traversing from the current position until we encounter a close parenthesis `')'`. At this point, the string within the parentheses is the key. We look for the corresponding value of this key in the hash table $d$. If found, we replace the value within the parentheses with it, otherwise, we replace it with `'?'`.\n\nThe time complexity is $O(n + m)$, and the space complexity is $O(L)$. Here, $n$ and $m$ are the lengths of the string $s$ and the list `knowledge` respectively, and $L$ is the sum of the lengths of all strings in `knowledge`." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(L)" }, { "problem_id": 1808, "explanations": { "1": "We can factorize $n$ into prime factors, i.e., $n = a_1^{k_1} \\times a_2^{k_2} \\times\\cdots \\times a_m^{k_m}$, where $a_i$ is a prime factor and $k_i$ is the exponent of the prime factor $a_i$. Since the number of prime factors of $n$ does not exceed `primeFactors`, we have $k_1 + k_2 + \\cdots + k_m \\leq primeFactors$.\n\nAccording to the problem description, we know that a good factor of $n$ must be divisible by all prime factors, which means that a good factor of $n$ needs to include $a_1 \\times a_2 \\times \\cdots \\times a_m$ as a factor. Then the number of good factors $k= k_1 \\times k_2 \\times \\cdots \\times k_m$, i.e., $k$ is the product of $k_1, k_2, \\cdots, k_m$. To maximize the number of good factors, we need to split `primeFactors` into $k_1, k_2, \\cdots, k_m$ to make $k_1 \\times k_2 \\times \\cdots \\times k_m$ the largest. Therefore, the problem is transformed into: split the integer `primeFactors` into the product of several integers to maximize the product.\n\nNext, we just need to discuss different cases.\n\n- If $primeFactors \\lt 4$, then directly return `primeFactors`.\n- If $primeFactors$ is a multiple of $3$, then we split `primeFactors` into multiples of $3$, i.e., $3^{\\frac{primeFactors}{3}}$.\n- If $primeFactors$ modulo $3$ equals $1$, then we split `primeFactors` into $\\frac{primeFactors}{3} - 1$ multiples of $3$, and then multiply by $4$, i.e., $3^{\\frac{primeFactors}{3} - 1} \\times 4$.\n- If $primeFactors$ modulo $3$ equals $2$, then we split `primeFactors` into $\\frac{primeFactors}{3}$ multiples of $3$, and then multiply by $2$, i.e., $3^{\\frac{primeFactors}{3}} \\times 2$.\n\nIn the above process, we use fast power to calculate the modulus.\n\nThe time complexity is $O(\\log n)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 1809, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1810, "explanations": { "1": "We observe that the grid size is $m \\times n$, where $m, n \\leq 100$. Therefore, we can initialize the starting coordinates as $(sx, sy) = (100, 100)$ and assume the grid size is $200 \\times 200$. Then, we can use depth-first search (DFS) to explore the entire grid and construct a 2D array $g$ representing the grid, where $g[i][j]$ represents the movement cost from the starting point $(sx, sy)$ to coordinates $(i, j)$. If a cell is unreachable, we set its value to $-1$. We store the target coordinates in $\\textit{target}$, and if the target cannot be reached, then $\\textit{target} = (-1, -1)$.\n\nNext, we can use the heap-optimized Dijkstra algorithm to calculate the minimum cost path from the starting point $(sx, sy)$ to the target $\\textit{target}$. We use a priority queue to store the current path cost and coordinates, and use a 2D array $\\textit{dist}$ to record the minimum cost from the starting point to each cell. When we pop a node from the priority queue, if that node is the target, we return the current path cost as the answer. If the path cost of that node is greater than the value recorded in $\\textit{dist}$, we skip that node. Otherwise, we traverse the four neighbors of that node. If a neighbor is reachable and the path cost to reach the neighbor through this node is smaller, we update the neighbor's path cost and add it to the priority queue.\n\nThe time complexity is $O(m \\times n \\log(m \\times n))$, and the space complexity is $O(m \\times n)$. Where $m$ and $n$ are the number of rows and columns in the grid, respectively." }, "is_english": true, "time_complexity": "O(m \\times n \\log(m \\times n))", "space_complexity": "O(m \\times n)" }, { "problem_id": 1811, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1812, "explanations": { "1": "Observing the chessboard, we find that two squares $(x_1, y_1)$ and $(x_2, y_2)$ with the same color satisfy that both $x_1 + y_1$ and $x_2 + y_2$ are either odd or even.\n\nTherefore, we can get the corresponding coordinates $(x, y)$ from $\\textit{coordinates}$. If $x + y$ is odd, the square is white, and we return $\\textit{true}$; otherwise, we return $\\textit{false}$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 1813, "explanations": { "1": "We split the two sentences into two word arrays `words1` and `words2` by spaces. Let the lengths of `words1` and `words2` be $m$ and $n$, respectively, and assume that $m \\ge nn.\n\nWe use two pointers $i$ and $j$, initially $i = j = 0$. Next, we loop to check whether `words1[i]` is equal to `words2[i]`, and if so, pointer $i$ continues to move right; then we loop to check whether `words1[m - 1 - j]` is equal to `words2[n - 1 - j]`, and if so, pointer $j$ continues to move right.\n\nAfter the loop, if $i + j \\ge n$, it means that the two sentences are similar, and we return `true`; otherwise, we return `false`.\n\nThe time complexity is $O(L)$, and the space complexity is $O(L)$, where $L$ is the sum of the lengths of the two sentences." }, "is_english": true, "time_complexity": "O(L)", "space_complexity": "O(L)" }, { "problem_id": 1814, "explanations": { "1": "For the index pair $(i, j)$, if it satisfies the condition, then we have $nums[i] + rev(nums[j]) = nums[j] + rev(nums[i])$, which means $nums[i] - nums[j] = rev(nums[j]) - rev(nums[i])$.\n\nTherefore, we can use $nums[i] - rev(nums[i])$ as the key of a hash table and count the number of occurrences of each key. Finally, we calculate the combination of values corresponding to each key, add them up, and get the final answer.\n\nNote that we need to perform modulo operation on the answer.\n\nThe time complexity is $O(n \\times \\log M)$, where $n$ and $M$ are the length of the $nums$ array and the maximum value in the $nums$ array, respectively. The space complexity is $O(n)$.", "2": "" }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(n)" }, { "problem_id": 1815, "explanations": { "1": "The problem actually asks us to find an arrangement order that maximizes the number of groups whose prefix sum (referring to \"number of people\" here) modulo $batchSize$ equals $0$. Therefore, we can divide all customers into two categories:\n\n- Customers whose number is a multiple of $batchSize$. These customers will not affect the donuts of the next group of customers. We can greedily arrange these groups of customers first, so these groups of customers will be happy. The \"initial answer\" is the number of these groups.\n- Customers whose number is not a multiple of $batchSize$. The arrangement order of these customers will affect the donuts of the next group of customers. We can take the modulo $batchSize$ for the number of people $v$ in each group here, and the remainders form a set. The range of element values in the set is $[1,2...,batchSize-1]$. The maximum length of the $groups$ array is $30$, so the maximum number of each remainder does not exceed $30$. We can use $5$ binary bits to represent the quantity of a remainder, and the maximum $batchSize$ is $9$, so the total number of binary bits required to represent these remainders and their quantities is $5\\times (9-1)=40$. We can use a $64$-bit integer $state$ to represent it.\n\nNext, we design a function $dfs(state, mod)$, which represents the number of groups that can be happy when the arrangement state is $state$ and the current prefix remainder is $mod$. Then our \"initial answer\" plus $dfs(state, 0)$ is the final answer.\n\nThe implementation logic of the function $dfs(state, mod)$ is as follows:\n\nWe enumerate each remainder $i$ from $1$ to $batchSize-1$. If the quantity of the remainder $i$ is not $0$, we can subtract $1$ from the quantity of the remainder $i$, add $i$ to the current prefix remainder and take modulo $batchSize$, then recursively call the function $dfs$ to find the optimal solution of the sub-state, and take the maximum value. Finally, check whether $mod$ is $0$. If it is $0$, we return after adding $1$ to the maximum value, otherwise we directly return the maximum value.\n\nDuring the process, we can use memorized search to avoid repeated calculation of states.\n\nThe time complexity does not exceed $O(10^7)$, and the space complexity does not exceed $O(10^6)$.", "2": "" }, "is_english": true, "time_complexity": "O(10^7)", "space_complexity": "O(10^6)" }, { "problem_id": 1816, "explanations": { "1": "We traverse the string $s$ from the beginning. For the current character $s[i]$, if it is a space, we decrement $k$. When $k$ becomes $0$, it means that we have extracted $k$ words, so we return the substring $s[0..i)$.\n\nAfter the traversal, we return $s$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. Ignoring the space complexity of the answer, the space complexity is $O(1)$.", "2": "" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1817, "explanations": { "1": "We use a hash table $d$ to record all the unique operation times of each user, and then traverse the hash table to count the number of active minutes for each user. Finally, we count the distribution of the number of active minutes for each user.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the $logs$ array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1818, "explanations": { "1": "According to the problem, we can first calculate the absolute difference sum of `nums1` and `nums2` without any replacements, denoted as $s$.\n\nNext, we enumerate each element $nums1[i]$ in `nums1`, replacing it with the element closest to $nums2[i]$ that also exists in `nums1`. Therefore, before the enumeration, we can make a copy of `nums1`, resulting in the array `nums`, and sort `nums`. Then, we perform a binary search in `nums` for the element closest to $nums2[i]$, denoted as $nums[j]$, and calculate $|nums1[i] - nums2[i]| - |nums[j] - nums2[i]|$, updating the maximum value of the difference $mx$.\n\nFinally, we subtract $mx$ from $s$, which is the answer. Note the modulus operation.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array `nums1`." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1819, "explanations": { "1": "For all sub-sequences of the array $nums$, their greatest common divisor (GCD) will not exceed the maximum value $mx$ in the array.\n\nTherefore, we can enumerate each number $x$ in $[1,.. mx]$, and determine whether $x$ is the GCD of a sub-sequence of the array $nums$. If it is, then we increment the answer by one.\n\nSo the problem is transformed into: determining whether $x$ is the GCD of a sub-sequence of the array $nums$. We can do this by enumerating the multiples $y$ of $x$, and checking whether $y$ exists in the array $nums$. If $y$ exists in the array $nums$, then we calculate the GCD $g$ of $y$. If $g = x$ occurs, then $x$ is the GCD of a sub-sequence of the array $nums$.\n\nThe time complexity is $O(n + M \\times \\log M)$, and the space complexity is $O(M)$. Here, $n$ and $M$ are the length of the array $nums$ and the maximum value in the array $nums$, respectively." }, "is_english": true, "time_complexity": "O(n + M \\times \\log M)", "space_complexity": "O(M)" }, { "problem_id": 1820, "explanations": { "1": "This problem belongs to the maximum matching problem of bipartite graphs, which is suitable for solving with the Hungarian algorithm.\n\nThe core idea of the Hungarian algorithm is to continuously start from unmatched points, look for augmenting paths, and stop when there are no augmenting paths. This gives the maximum match.\n\nThe time complexity is $O(m \\times n)$." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": null }, { "problem_id": 1821, "explanations": { "1": "We can directly use the `WHERE` clause to filter out the customers whose `year` is `2021` and `revenue` is greater than $0$." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1822, "explanations": { "1": "The problem requires us to return the sign of the product of the array elements, i.e., return $1$ for positive numbers, $-1$ for negative numbers, and $0$ if it equals $0$.\n\nWe can define an answer variable `ans`, initially set to $1$.\n\nThen we traverse each element $v$ in the array. If $v$ is a negative number, we multiply `ans` by $-1$. If $v$ is $0$, we return $0$ in advance.\n\nAfter the traversal is over, we return `ans`.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1823, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1824, "explanations": { "1": "We define $f[i][j]$ as the minimum number of sidesteps for the frog to reach the $i$-th point and be on the $j$-th lane (index starts from $0$).\n\nNote that the frog starts on the second lane (the problem index starts from $1$), so the value of $f[0][1]$ is $0$, and the values of $f[0][0]$ and $f[0][2]$ are both $1$. The answer is $min(f[n][0], f[n][1], f[n][2])$.\n\nFor each position $i$ from $1$ to $n$, we can enumerate the current lane $j$ of the frog. If $obstacles[i] = j + 1$, it means that there is an obstacle on the $j$-th lane, and the value of $f[i][j]$ is infinity. Otherwise, the frog can choose not to jump, in which case the value of $f[i][j]$ is $f[i - 1][j]$, or the frog can sidestep from other lanes, in which case $f[i][j] = min(f[i][j], min(f[i][0], f[i][1], f[i][2]) + 1)$.\n\nIn the code implementation, we can optimize the first dimension of space and only use an array $f$ of length $3$ for maintenance.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $obstacles$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1825, "explanations": { "1": "We can maintain the following data structures or variables:\n\n- A queue $q$ of length $m$, where the head of the queue is the earliest added element, and the tail of the queue is the most recently added element;\n- Three ordered sets, namely $lo$, $mid$, $hi$, where $lo$ and $hi$ store the smallest $k$ elements and the largest $k$ elements respectively, and $mid$ stores the remaining elements;\n- A variable $s$, maintaining the sum of all elements in $mid$;\n- Some programming languages (such as Java, Go) additionally maintain two variables $size1$ and $size3$, representing the number of elements in $lo$ and $hi$ respectively.\n\nWhen calling the $addElement(num)$ function, perform the following operations in order:\n\n1. If $lo$ is empty, or $num \\leq max(lo)$, then add $num$ to $lo$; otherwise if $hi$ is empty, or $num \\geq min(hi)$, then add $num$ to $hi$; otherwise add $num$ to $mid$, and add the value of $num$ to $s$.\n1. Next, add $num$ to the queue $q$. If the length of the queue $q$ is greater than $m$ at this time, remove the head element $x$ from the queue $q$, then choose one of $lo$, $mid$ or $hi$ that contains $x$, and remove $x$ from this set. If the set is $mid$, subtract the value of $x$ from $s$.\n1. If the length of $lo$ is greater than $k$, then repeatedly remove the maximum value $max(lo)$ from $lo$, add $max(lo)$ to $mid$, and add the value of $max(lo)$ to $s$.\n1. If the length of $hi$ is greater than $k$, then repeatedly remove the minimum value $min(hi)$ from $hi$, add $min(hi)$ to $mid$, and add the value of $min(hi)$ to $s$.\n1. If the length of $lo$ is less than $k$ and $mid$ is not empty, then repeatedly remove the minimum value $min(mid)$ from $mid$, add $min(mid)$ to $lo$, and subtract the value of $min(mid)$ from $s$.\n1. If the length of $hi$ is less than $k$ and $mid$ is not empty, then repeatedly remove the maximum value $max(mid)$ from $mid$, add $max(mid)$ to $hi$, and subtract the value of $max(mid)$ from $s$.\n\nWhen calling the $calculateMKAverage()$ function, if the length of $q$ is less than $m$, return $-1$, otherwise return $\\frac{s}{m - 2k}$.\n\nIn terms of time complexity, each call to the $addElement(num)$ function has a time complexity of $O(\\log m)$, and each call to the $calculateMKAverage()$ function has a time complexity of $O(1)$. The space complexity is $O(m)$.", "2": "" }, "is_english": true, "time_complexity": "O(\\log m)", "space_complexity": "O(m)" }, { "problem_id": 1826, "explanations": { "1": "Traverse both arrays, find the first unequal position $i$. If $i \\lt n - 1$, loop to compare $sensor1[i + 1]$ and $sensor2[i]$, if they are not equal, it indicates that sensor $1$ is defective, return $1$; otherwise compare $sensor1[i]$ and $sensor2[i + 1]$, if they are not equal, it indicates that sensor $2$ is defective, return $2$.\n\nIf the traversal ends, it means that the defective sensor cannot be determined, return $-1$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1827, "explanations": { "1": "We use a variable $mx$ to record the maximum value of the current strictly increasing array, initially $mx = 0$.\n\nTraverse the array `nums` from left to right. For the current element $v$, if $v \\lt mx + 1$, we need to increase it to $mx + 1$ to ensure the array is strictly increasing. Therefore, the number of operations we need to perform this time is $max(0, mx + 1 - v)$, which is added to the answer, and then we update $mx=max(mx + 1, v)$. Continue to traverse the next element until the entire array is traversed.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array `nums`. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1828, "explanations": { "1": "Enumerate all the circles $(x, y, r)$. For each circle, calculate the number of points within the circle to get the answer.\n\nThe time complexity is $O(m \\times n)$, where $m$ and $n$ are the lengths of the arrays `queries` and `points` respectively. Ignoring the space consumption of the answer, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(1)" }, { "problem_id": 1829, "explanations": { "1": "First, we preprocess the XOR sum $xs$ of the array `nums`, i.e., $xs=nums[0] \\oplus nums[1] \\oplus \\cdots \\oplus nums[n-1]$.\n\nNext, we enumerate each element $x$ in the array `nums` from back to front. The current XOR sum is $xs$. We need to find a number $k$ such that the value of $xs \\oplus k$ is as large as possible, and $k \\lt 2^{maximumBit}$.\n\nThat is to say, we start from the $maximumBit - 1$ bit of $xs$ and enumerate to the lower bit. If a bit of $xs$ is $0$, then we set the corresponding bit of $k$ to $1$. Otherwise, we set the corresponding bit of $k$ to $0$. In this way, the final $k$ is the answer to each query. Then, we update $xs$ to $xs \\oplus x$ and continue to enumerate the next element.\n\nThe time complexity is $O(n \\times m)$, where $n$ and $m$ are the values of the array `nums` and `maximumBit` respectively. Ignoring the space consumption of the answer, the space complexity is $O(1)$.", "2": "Similar to Solution 1, we first preprocess the XOR sum $xs$ of the array `nums`, i.e., $xs=nums[0] \\oplus nums[1] \\oplus \\cdots \\oplus nums[n-1]$.\n\nNext, we calculate $2^{maximumBit} - 1$, which is $2^{maximumBit}$ minus $1$, denoted as $mask$. Then, we enumerate each element $x$ in the array `nums` from back to front. The current XOR sum is $xs$, then $k=xs \\oplus mask$ is the answer to each query. Then, we update $xs$ to $xs \\oplus x$ and continue to enumerate the next element.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array `nums`. Ignoring the space consumption of the answer, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times m)", "space_complexity": "O(1)" }, { "problem_id": 1830, "explanations": { "1": "The operation in the problem is actually to find the previous permutation in lexicographical order of the current permutation. Therefore, we only need to find the number of permutations smaller than the current permutation, which is the answer.\n\nHere we need to consider a problem: given the frequency of each letter, how many different permutations can we construct?\n\nSuppose there are a total of $n$ letters, among which there are $n_1$ letters $a$, $n_2$ letters $b$, and $n_3$ letters $c$. Then we can construct $\\frac{n!}{n_1! \\times n_2! \\times n_3!}$ different permutations. Where $n=n_1+n_2+n_3$.\n\nWe can pre-calculate all factorials $f$ and the inverse of the factorials $g$ through preprocessing. The inverse of the factorial can be obtained through Fermat's little theorem.\n\nNext, we traverse the string $s$ from left to right. For each position $i$, we need to find out how many letters are smaller than $s[i]$, denoted as $m$. Then, we can construct $m \\times \\frac{(n - i - 1)!}{n_1! \\times n_2! \\cdots \\times n_k!}$ different permutations, where $k$ is the number of types of letters, and add them to the answer. Next, we reduce the frequency of $s[i]$ by one and continue to traverse the next position.\n\nAfter traversing the entire string, we can get the answer. Note the modulo operation of the answer.\n\nThe time complexity is $O(n \\times k)$, and the space complexity is $O(n)$. Where $n$ and $k$ are the length of the string and the number of types of letters, respectively." }, "is_english": true, "time_complexity": "O(n \\times k)", "space_complexity": "O(n)" }, { "problem_id": 1831, "explanations": { "1": "We can use the window function `RANK()`, which assigns a rank to each transaction based on its amount in descending order, and then select the transactions with a rank of $1$." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1832, "explanations": { "1": "Traverse the string `sentence`, use an array or hash table to record the letters that have appeared, and finally check whether there are $26$ letters in the array or hash table.\n\nThe time complexity is $O(n)$, and the space complexity is $O(C)$. Where $n$ is the length of the string `sentence`, and $C$ is the size of the character set. In this problem, $C = 26$.", "2": "We can also use an integer $mask$ to record the letters that have appeared, where the $i$-th bit of $mask$ indicates whether the $i$-th letter has appeared.\n\nFinally, check whether there are $26$ $1$s in the binary representation of $mask$, that is, check whether $mask$ is equal to $2^{26} - 1$. If so, return `true`, otherwise return `false`.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string `sentence`. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(C)" }, { "problem_id": 1833, "explanations": { "1": "To buy as many ice creams as possible, and they can be purchased in any order, we should prioritize choosing ice creams with lower prices.\n\nSort the $costs$ array, and then start buying from the ice cream with the lowest price, one by one, until it is no longer possible to buy, and return the number of ice creams that can be bought.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$, where $n$ is the length of the $costs$ array." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 1834, "explanations": { "1": "First, we sort the tasks by `enqueueTime` in ascending order. Next, we use a priority queue (min heap) to maintain the currently executable tasks. The elements in the queue are `(processingTime, index)`, which represent the execution time and the index of the task. We also use a variable $t$ to represent the current time, initially set to $0$.\n\nNext, we simulate the execution process of the tasks.\n\nIf the current queue is empty, it means there are no executable tasks at the moment. We update $t$ to the larger value between the `enqueueTime` of the next task and the current time $t$. Then, we add all tasks with `enqueueTime` less than or equal to $t$ to the queue.\n\nThen, we take out a task from the queue, add its index to the answer array, and update $t$ to the sum of the current time $t$ and the execution time of the current task.\n\nWe repeat the above process until the queue is empty and all tasks have been added to the queue.\n\nThe time complexity is $O(n \\times \\log n)$, where $n$ is the number of tasks." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": null }, { "problem_id": 1835, "explanations": { "1": "Assume that the elements of array $arr1$ are $a_1, a_2, ..., a_n$, and the elements of array $arr2$ are $b_1, b_2, ..., b_m$. Then, the answer to the problem is:\n\n$$\n\\begin{aligned}\n\\textit{ans} &= (a_1 \\wedge b_1) \\oplus (a_1 \\wedge b_2) ... (a_1 \\wedge b_m) \\\\\n&\\quad \\oplus (a_2 \\wedge b_1) \\oplus (a_2 \\wedge b_2) ... (a_2 \\wedge b_m) \\\\\n&\\quad \\oplus \\cdots \\\\\n&\\quad \\oplus (a_n \\wedge b_1) \\oplus (a_n \\wedge b_2) ... (a_n \\wedge b_m) \\\\\n\\end{aligned}\n$$\n\nSince in Boolean algebra, the XOR operation is addition without carry, and the AND operation is multiplication, the above formula can be simplified as:\n\n$$\n\\textit{ans} = (a_1 \\oplus a_2 \\oplus \\cdots \\oplus a_n) \\wedge (b_1 \\oplus b_2 \\oplus \\cdots \\oplus b_m)\n$$\n\nThat is, the bitwise AND of the XOR sum of array $arr1$ and the XOR sum of array $arr2$.\n\nThe time complexity is $O(n + m)$, where $n$ and $m$ are the lengths of arrays $arr1$ and $arr2$, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(1)" }, { "problem_id": 1836, "explanations": { "1": "We can use a hash table $cnt$ to count the number of occurrences of each element in the linked list, and then traverse the linked list to delete elements that appear more than once.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the linked list." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1837, "explanations": { "1": "We divide $n$ by $k$ and take the remainder until it is $0$. The sum of the remainders gives the result.\n\nThe time complexity is $O(\\log_{k}n)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log_{k}n)", "space_complexity": "O(1)" }, { "problem_id": 1838, "explanations": { "1": "According to the problem description, we can draw three conclusions:\n\n1. After several operations, the element with the highest frequency in the array must be an element in the original array. Why? Suppose the elements operated are $a_1, a_2, \\cdots, a_m$, where the maximum is $a_m$. These elements have all been changed to the same value $x$, where $x \\geq a_m$. Then we can also change these elements all to $a_m$, and the number of operations will not increase.\n2. The elements operated must be a continuous subarray in the sorted array.\n3. If a frequency $m$ satisfies the condition, then all $m' < m$ also satisfy the condition. This inspires us to consider using binary search to find the maximum frequency that satisfies the condition.\n\nTherefore, we can sort the array $nums$ and then calculate the prefix sum array $s$ of the sorted array, where $s[i]$ represents the sum of the first $i$ elements.\n\nNext, we define the left boundary of the binary search as $l = 1$, and the right boundary as $r = n$. For each binary search, we take the middle value $m = (l + r + 1) / 2$, and then check whether there exists a continuous subarray of length $m$ such that all elements in the subarray can be changed to an element in the array, and the number of operations does not exceed $k$. If such a subarray exists, we can update the left boundary $l$ to $m$, otherwise update the right boundary $r$ to $m - 1$.\n\nFinally, return the left boundary $l$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $nums$.", "2": "We can also use two pointers to maintain a sliding window, where all elements in the window can be changed to the maximum value in the window. The number of operations for the elements in the window is $s$, and $s \\leq k$.\n\nInitially, we set the left pointer $j$ to point to the first element of the array, and the right pointer $i$ also points to the first element of the array. Next, we move the right pointer $i$ each time, changing all elements in the window to $nums[i]$. At this time, the number of operations to be increased is $(nums[i] - nums[i - 1]) \\times (i - j)$. If this number of operations exceeds $k$, then we need to move the left pointer $j$ until the number of operations for the elements in the window does not exceed $k$. Then, we update the answer to the maximum length of the window.\n\nThe time complexity is $O(n \\log n)$, and the space complexity is $O(\\log n)$. Where $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1839, "explanations": { "1": "We can first transform the string `word`. For example, for `word=\"aaaeiouu\"`, we can transform it into data items `('a', 3)`, `('e', 1)`, `('i', 1)`, `('o', 1)`, `('u', 2)` and store them in an array `arr`. Each data item's first element represents a vowel, and the second element represents the number of times the vowel appears consecutively. This transformation can be implemented using two pointers.\n\nNext, we traverse the array `arr`, each time taking $5$ adjacent data items, and judge whether the vowels in these data items are `'a'`, `'e'`, `'i'`, `'o'`, `'u'` respectively. If so, calculate the total number of times the vowels appear in these $5$ data items, which is the length of the current beautiful substring, and update the maximum value of the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string `word`." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1840, "explanations": { "1": "First, we sort all the constraints by the building number in ascending order.\n\nThen we traverse all the constraints from left to right. For each constraint, we can get an upper bound on the maximum height, i.e., $r_i[1] = \\min(r_i[1], r_{i-1}[1] + r_i[0] - r_{i-1}[0])$, where $r_i$ represents the $i$-th constraint, and $r_i[0]$ and $r_i[1]$ represent the building number and the upper bound on the maximum height of the building, respectively.\n\nNext, we traverse all the constraints from right to left. For each constraint, we can get an upper bound on the maximum height, i.e., $r_i[1] = \\min(r_i[1], r_{i+1}[1] + r_{i+1}[0] - r_i[0])$.\n\nIn this way, we obtain the upper bound on the maximum height for each constrained building.\n\nThe problem asks for the height of the tallest building. We can enumerate the buildings between two adjacent constraints $i$ and $i+1$. To maximize the height, the height should first increase and then decrease. Suppose the maximum height is $t$, then $t - r_i[1] + t - r_{i+1}[1] \\leq r_{i+1}[0] - r_i[0]$, i.e., $t \\leq \\frac{r_i[1] + r_{i+1}[1] + r_{i+1}[0] - r_{i}[0]}{2}$. We take the maximum value of all such $t$.\n\nThe time complexity is $O(m \\times \\log m)$, and the space complexity is $O(m)$. Here, $m$ is the number of constraints." }, "is_english": true, "time_complexity": "O(m \\times \\log m)", "space_complexity": "O(m)" }, { "problem_id": 1841, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1842, "explanations": { "1": "According to the problem description, we only need to find the next permutation of the first half of the string, then traverse the first half and symmetrically assign values to the second half.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1843, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1844, "explanations": { "1": "Traverse the string, for characters at odd indices, replace them with the character that is a certain number of positions after the previous character.\n\nFinally, return the replaced string.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. Ignoring the space consumption of the answer, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1845, "explanations": { "1": "We define a priority queue (min-heap) $\\textit{q}$ to store all the available seat numbers. Initially, we add all seat numbers from $1$ to $n$ into $\\textit{q}$.\n\nWhen calling the `reserve` method, we pop the top element from $\\textit{q}$, which is the smallest available seat number.\n\nWhen calling the `unreserve` method, we add the seat number back into $\\textit{q}$.\n\nIn terms of time complexity, the initialization time complexity is $O(n)$ or $O(n \\times \\log n)$, and the time complexity of the `reserve` and `unreserve` methods is both $O(\\log n)$. The space complexity is $O(n)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1846, "explanations": { "1": "First, we sort the array and then set the first element of the array to $1$.\n\nNext, we start traversing the array from the second element. If the difference between the current element and the previous one is more than $1$, we greedily reduce the current element to the previous element plus $1$.\n\nFinally, we return the maximum element in the array.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 1847, "explanations": { "1": "We notice that the order of queries does not affect the answer, and the problem involves the size relationship of room areas. Therefore, we can sort the queries in ascending order of minimum area, so that we can process each query from small to large. Also, we sort the rooms in ascending order of area.\n\nNext, we create an ordered list and add all room numbers to the ordered list.\n\nThen, we process each query from small to large. For each query, we first remove all rooms with an area less than or equal to the current query's minimum area from the ordered list. Then, in the remaining rooms, we use binary search to find the room number closest to the current query. If there is no such room, we return $-1$.\n\nThe time complexity is $O(n \\times \\log n + k \\times \\log k)$, and the space complexity is $O(n + k)$. Where $n$ and $k$ are the number of rooms and queries, respectively." }, "is_english": true, "time_complexity": "O(n \\times \\log n + k \\times \\log k)", "space_complexity": "O(n + k)" }, { "problem_id": 1848, "explanations": { "1": "Traverse the array, find all indices equal to $target$, then calculate $|i - start|$, and take the minimum value.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1849, "explanations": { "1": "We can start from the first character of the string and try to split it into one or more substrings, then recursively process the remaining part.\n\nSpecifically, we design a function $\\textit{dfs}(i, x)$, where $i$ represents the current position being processed, and $x$ represents the last split value. Initially, $x = -1$, indicating that we have not split out any value yet.\n\nIn $\\textit{dfs}(i, x)$, we first calculate the current split value $y$. If $x = -1$, or $x - y = 1$, then we can try to use $y$ as the next value and continue to recursively process the remaining part. If the result of the recursion is $\\textit{true}$, we have found a valid split method and return $\\textit{true}$.\n\nAfter traversing all possible split methods, if no valid split method is found, we return $\\textit{false}$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$, where $n$ is the length of the string." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 1850, "explanations": { "1": "We can call the `next_permutation` function $k$ times to get the $k$th smallest permutation $s$.\n\nNext, we just need to calculate how many swaps are needed for $num$ to become $s$.\n\nLet's first consider a simple situation where all the digits in $num$ are different. In this case, we can directly map the digit characters in $num$ to indices. For example, if $num$ is `\"54893\"` and $s$ is `\"98345\"`. We map each digit in $num$ to an index, that is:\n\n$$\n\\begin{aligned}\nnum[0] &= 5 &\\rightarrow& \\quad 0 \\\\\nnum[1] &= 4 &\\rightarrow& \\quad 1 \\\\\nnum[2] &= 8 &\\rightarrow& \\quad 2 \\\\\nnum[3] &= 9 &\\rightarrow& \\quad 3 \\\\\nnum[4] &= 3 &\\rightarrow& \\quad 4 \\\\\n\\end{aligned}\n$$\n\nThen, mapping each digit in $s$ to an index results in `\"32410\"`. In this way, the number of swaps needed to change $num$ to $s$ is equal to the number of inversion pairs in the index array after $s$ is mapped.\n\nIf there are identical digits in $num$, we can use an array $d$ to record the indices where each digit appears, where $d[i]$ represents the list of indices where the digit $i$ appears. To minimize the number of swaps, when mapping $s$ to an index array, we only need to greedily select the index of the corresponding digit in $d$ in order.\n\nFinally, we can directly use a double loop to calculate the number of inversion pairs, or we can optimize it with a Binary Indexed Tree.\n\nThe time complexity is $O(n \\times (k + n))$, and the space complexity is $O(n)$. Where $n$ is the length of $num$." }, "is_english": true, "time_complexity": "O(n \\times (k + n))", "space_complexity": "O(n)" }, { "problem_id": 1851, "explanations": { "1": "We notice that the order of queries does not affect the answer, and the intervals involved do not change. Therefore, we consider sorting all queries in ascending order, and sorting all intervals in ascending order of the left endpoint.\n\nWe use a priority queue (min heap) $pq$ to maintain all current intervals. Each element in the queue is a pair $(v, r)$, representing an interval with length $v$ and right endpoint $r$. Initially, the priority queue is empty. In addition, we define a pointer $i$ that points to the current interval being traversed, and initially $i=0$.\n\nWe traverse each query $(x, j)$ in ascending order and perform the following operations:\n\n- If the pointer $i$ has not traversed all intervals, and the left endpoint of the current interval $[a, b]$ is less than or equal to $x$, then we add this interval to the priority queue and move the pointer $i$ one step forward. Repeat this process.\n- If the priority queue is not empty, and the right endpoint of the heap top element is less than $x$, then we pop the heap top element. Repeat this process.\n- At this point, if the priority queue is not empty, then the heap top element is the smallest interval containing $x$. We add its length $v$ to the answer array $ans$.\n\nAfter the above process is over, we return the answer array $ans$.\n\nThe time complexity is $O(n \\times \\log n + m \\times \\log m)$, and the space complexity is $O(n + m)$. Where $n$ and $m$ are the lengths of the arrays `intervals` and `queries` respectively." }, "is_english": true, "time_complexity": "O(n \\times \\log n + m \\times \\log m)", "space_complexity": "O(n + m)" }, { "problem_id": 1852, "explanations": { "1": "We use a hash table $cnt$ to record the occurrence times of each number in the subarray of length $k$.\n\nNext, we first traverse the first $k$ elements of the array, record the occurrence times of each element, and after the traversal, we take the size of the hash table as the first element of the answer array.\n\nThen, we continue to traverse the array from the index $k$. Each time we traverse, we increase the occurrence times of the current element by one, and decrease the occurrence times of the element on the left of the current element by one. If the occurrence times of the left element become $0$ after subtraction, we remove it from the hash table. Then we take the size of the hash table as the next element of the answer array, and continue to traverse.\n\nAfter the traversal, we return the answer array.\n\nThe time complexity is $O(n)$, and the space complexity is $O(k)$. Where $n$ is the length of the array $nums$, and $k$ is the parameter given by the problem.", "2": "We can also use an array to replace the hash table, which can improve performance to some extent.\n\nThe time complexity is $O(n)$, and the space complexity is $O(M)$. Where $n$ is the length of the array $nums$, and $M$ is the maximum value in the array $nums$. In this problem, $M \\leq 10^5$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(k)" }, { "problem_id": 1853, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1854, "explanations": { "1": "We notice that the range of years is $[1950,..2050]$. Therefore, we can map these years to an array $d$ of length $101$, where the index of the array represents the value of the year minus $1950$.\n\nNext, we traverse $logs$. For each person, we increment $d[birth_i - 1950]$ by $1$ and decrement $d[death_i - 1950]$ by $1$. Finally, we traverse the array $d$, find the maximum value of the prefix sum, which is the year with the most population, and add $1950$ to get the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(C)$. Where $n$ is the length of the array $logs$, and $C$ is the range size of the years, i.e., $2050 - 1950 + 1 = 101$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(C)" }, { "problem_id": 1855, "explanations": { "1": "Assume the lengths of $nums1$ and $nums2$ are $m$ and $n$ respectively.\n\nTraverse array $nums1$, for each number $nums1[i]$, perform a binary search for numbers in $nums2$ in the range $[i,n)$, find the **last** position $j$ that is greater than or equal to $nums1[i]$, calculate the distance between this position and $i$, and update the maximum distance value $ans$.\n\nThe time complexity is $O(m \\times \\log n)$, where $m$ and $n$ are the lengths of $nums1$ and $nums2$ respectively. The space complexity is $O(1)$.", "2": "在方法一中,我们只利用到 $nums2$ 是非递增数组这一条件,实际上,$nums1$ 也是非递增数组,我们可以用双指针 $i$ 和 $j$ 来遍历 $nums1$ 和 $nums2$。\n\n时间复杂度 $O(m+n)$,其中 $m$ 和 $n$ 分别为 $nums1$ 和 $nums2$ 的长度。空间复杂度 $O(1)$。" }, "is_english": true, "time_complexity": "O(m \\times \\log n)", "space_complexity": "O(1)" }, { "problem_id": 1856, "explanations": { "1": "We can enumerate each element $nums[i]$ as the minimum value of the subarray, and find the left and right boundaries $left[i]$ and $right[i]$ of the subarray. Where $left[i]$ represents the first position strictly less than $nums[i]$ on the left side of $i$, and $right[i]$ represents the first position less than or equal to $nums[i]$ on the right side of $i$.\n\nTo conveniently calculate the sum of the subarray, we can preprocess the prefix sum array $s$, where $s[i]$ represents the sum of the first $i$ elements of $nums$.\n\nThen the minimum product with $nums[i]$ as the minimum value of the subarray is $nums[i] \\times (s[right[i]] - s[left[i] + 1])$. We can enumerate each element $nums[i]$, find the minimum product with $nums[i]$ as the minimum value of the subarray, and then take the maximum value.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1857, "explanations": { "1": "Calculate the in-degree of each node and perform a topological sort.\n\nDefine a 2D array $dp$, where $dp[i][j]$ represents the number of nodes with color $j$ on the path from the start node to node $i$.\n\nFrom node $i$, traverse all outgoing edges $i \\to j$, and update $dp[j][k] = \\max(dp[j][k], dp[i][k] + (c == k))$, where $c$ is the color of node $j$.\n\nThe answer is the maximum value in the $dp$ array.\n\nIf there is a cycle in the graph, it is impossible to visit all nodes, so return $-1$.\n\nThe time complexity is $O((n + m) \\times |\\Sigma|)$, and the space complexity is $O(m + n \\times |\\Sigma|)$. Here, $|\\Sigma|$ is the size of the alphabet (26 in this case), and $n$ and $m$ are the number of nodes and edges, respectively." }, "is_english": true, "time_complexity": "O((n + m) \\times |\\Sigma|)", "space_complexity": "O(m + n \\times |\\Sigma|)" }, { "problem_id": 1858, "explanations": { "1": "We define a Trie where each node has two attributes: a child node array $\\textit{children}$ of length $26$, and a flag $\\textit{isEnd}$ indicating whether the node marks the end of a word.\n\nWe iterate over $\\textit{words}$, and for each word $w$, we traverse from the root node. If the child node array of the current node does not contain the first character of $w$, we create a new node, then continue traversing the next character of $w$. After traversing all characters of $w$, we set the $\\textit{isEnd}$ flag of the current node to $\\texttt{true}$.\n\nNext, we iterate over $\\textit{words}$ again, and for each word $w$, we traverse from the root node. If the $\\textit{isEnd}$ field of a node in the child node array is $\\texttt{false}$, it means some prefix of $w$ is not in $\\textit{words}$, and we return $\\texttt{false}$. Otherwise, we continue traversing the next character of $w$, and after traversing all characters, we return $\\texttt{true}$.\n\nThe time complexity is $O(\\sum_{w \\in \\textit{words}} |w|)$, and the space complexity is $O(\\sum_{w \\in \\textit{words}} |w|)$, where $|w|$ is the length of word $w$." }, "is_english": true, "time_complexity": "O(\\sum_{w \\in \\textit{words}} |w|)", "space_complexity": "O(\\sum_{w \\in \\textit{words}} |w|)" }, { "problem_id": 1859, "explanations": { "1": "First, we split the string $s$ by spaces to get the array of strings $\\textit{ws}$. Then, we iterate through the array $\\textit{ws}$, subtracting the character '1' from the last character of each word to get the result as the index of the word. We take the prefix of the word as the content of the word. Finally, we concatenate the words in index order.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1860, "explanations": { "1": "We directly simulate the allocation of memory.\n\nAssume $t$ is the moment of unexpected exit, then the two memory sticks can definitely accommodate the memory consumed at the moment $t-1$ and before, so we have:\n\n$$\n\\sum_{i=1}^{t-1} i = \\frac{t\\times (t-1)}{2} \\leq (m_1+m_2)\n$$\n\nThe time complexity is $O(\\sqrt{m_1+m_2})$, where $m_1$ and $m_2$ are the sizes of the two memory sticks respectively." }, "is_english": true, "time_complexity": "O(\\sqrt{m_1+m_2})", "space_complexity": null }, { "problem_id": 1861, "explanations": { "1": "First, we rotate the matrix 90 degrees clockwise, then simulate the falling process of the stones in each column.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Where $m$ and $n$ are the number of rows and columns of the matrix, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 1862, "explanations": { "1": "First, we count the occurrences of each element in the array $nums$ and record them in the array $cnt$. Then, we calculate the prefix sum of the array $cnt$ and record it in the array $s$, i.e., $s[i]$ represents the count of elements less than or equal to $i$.\n\nNext, we enumerate the denominator $y$ and the quotient $d$. Using the prefix sum array, we can calculate the count of the numerator $s[\\min(mx, d \\times y + y - 1)] - s[d \\times y - 1]$, where $mx$ represents the maximum value in the array $nums$. Then, we multiply the count of the numerator by the count of the denominator $cnt[y]$, and then multiply by the quotient $d$. This gives us the value of all fractions that meet the conditions. By summing these values, we can get the answer.\n\nThe time complexity is $O(M \\times \\log M)$, and the space complexity is $O(M)$. Here, $M$ is the maximum value in the array $nums$." }, "is_english": true, "time_complexity": "O(M \\times \\log M)", "space_complexity": "O(M)" }, { "problem_id": 1863, "explanations": { "1": "We can use binary enumeration to enumerate all subsets, and then calculate the XOR sum of each subset.\n\nSpecifically, we enumerate $i$ in the range $[0, 2^n)$, where $n$ is the length of the array $nums$. If the $j$th bit of the binary representation of $i$ is $1$, it means that the $j$th element of $nums$ is in the current subset; if the $j$th bit is $0$, it means that the $j$th element of $nums$ is not in the current subset. We can get the XOR sum of the current subset according to the binary representation of $i$, and add it to the answer.\n\nThe time complexity is $O(n \\times 2^n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$.", "2": "We can also use depth-first search to enumerate all subsets, and then calculate the XOR sum of each subset.\n\nWe design a function $dfs(i, s)$, where $i$ represents the current search to the $i$th element of the array $nums$, and $s$ represents the XOR sum of the current subset. Initially, $i=0$, $s=0$. During the search, we have two choices each time:\n\n- Add the $i$th element of $nums$ to the current subset, i.e., $dfs(i+1, s \\oplus nums[i])$;\n- Do not add the $i$th element of $nums$ to the current subset, i.e., $dfs(i+1, s)$.\n\nWhen we have searched all elements of the array $nums$, i.e., $i=n$, the XOR sum of the current subset is $s$, and we can add it to the answer.\n\nThe time complexity is $O(2^n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n \\times 2^n)", "space_complexity": "O(1)" }, { "problem_id": 1864, "explanations": { "1": "First, we count the number of characters $0$ and $1$ in the string $\\textit{s}$, denoted as $n_0$ and $n_1$ respectively.\n\nIf the absolute difference between $n_0$ and $n_1$ is greater than $1$, it is impossible to form an alternating string, so we return $-1$.\n\nIf $n_0$ and $n_1$ are equal, we can calculate the number of swaps needed to convert the string into an alternating string starting with $0$ and starting with $1$, and take the minimum value.\n\nIf $n_0$ and $n_1$ are not equal, we only need to calculate the number of swaps needed to convert the string into an alternating string starting with the character that appears more frequently.\n\nThe problem is reduced to calculating the number of swaps needed to convert the string $\\textit{s}$ into an alternating string starting with character $c$.\n\nWe define a function $\\text{calc}(c)$, which represents the number of swaps needed to convert the string $\\textit{s}$ into an alternating string starting with character $c$. We traverse the string $\\textit{s}$, and for each position $i$, if the parity of $i$ is different from $c$, we need to swap the character at this position, incrementing the counter by $1$. Since each swap makes two positions have the same character, the final number of swaps is half of the counter.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $\\textit{s}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1865, "explanations": { "1": "We note that the length of the array $\\textit{nums1}$ does not exceed ${10}^3$, while the length of the array $\\textit{nums2}$ reaches ${10}^5$. Therefore, if we directly enumerate all index pairs $(i, j)$ and check whether $\\textit{nums1}[i] + \\textit{nums2}[j]$ equals the specified value $\\textit{tot}$, it will exceed the time limit.\n\nCan we only enumerate the shorter array $\\textit{nums1}$? The answer is yes. We use a hash table $\\textit{cnt}$ to count the occurrences of each element in the array $\\textit{nums2}$, then enumerate each element $x$ in the array $\\textit{nums1}$ and calculate the sum of $\\textit{cnt}[\\textit{tot} - x]$.\n\nWhen calling the $\\text{add}$ method, we need to first decrement the value corresponding to $\\textit{nums2}[index]$ in $\\textit{cnt}$ by $1$, then add $\\textit{val}$ to the value of $\\textit{nums2}[index]$, and finally increment the value corresponding to $\\textit{nums2}[index]$ in $\\textit{cnt}$ by $1$.\n\nWhen calling the $\\text{count}$ method, we only need to traverse the array $\\textit{nums1}$ and calculate the sum of $\\textit{cnt}[\\textit{tot} - x]$ for each element $x$.\n\nThe time complexity is $O(n \\times q)$, and the space complexity is $O(m)$. Here, $n$ and $m$ are the lengths of the arrays $\\textit{nums1}$ and $\\textit{nums2}$, respectively, and $q$ is the number of times the $\\text{count}$ method is called." }, "is_english": true, "time_complexity": "O(n \\times q)", "space_complexity": "O(m)" }, { "problem_id": 1866, "explanations": { "1": "We define $f[i][j]$ to represent the number of permutations of length $i$ in which exactly $j$ sticks can be seen. Initially, $f[0][0]=1$ and the rest $f[i][j]=0$. The answer is $f[n][k]$.\n\nConsider whether the last stick can be seen. If it can be seen, it must be the longest. Then there are $i - 1$ sticks in front of it, and exactly $j - 1$ sticks can be seen, which is $f[i - 1][j - 1]$. If the last stick cannot be seen, it can be any one except the longest stick. Then there are $i - 1$ sticks in front of it, and exactly $j$ sticks can be seen, which is $f[i - 1][j] \\times (i - 1)$.\n\nTherefore, the state transition equation is:\n\n$$\nf[i][j] = f[i - 1][j - 1] + f[i - 1][j] \\times (i - 1)\n$$\n\nThe final answer is $f[n][k]$.\n\nThe time complexity is $O(n \\times k)$, and the space complexity is $O(n \\times k)$. Where $n$ and $k$ are the two integers given in the problem.", "2": "We notice that $f[i][j]$ is only related to $f[i - 1][j - 1]$ and $f[i - 1][j]$, so we can use a one-dimensional array to optimize the space complexity.\n\nThe time complexity is $O(n \\times k)$, and the space complexity is $O(k)$. Here, $n$ and $k$ are the two integers given in the problem." }, "is_english": true, "time_complexity": "O(n \\times k)", "space_complexity": "O(n \\times k)" }, { "problem_id": 1867, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1868, "explanations": { "1": "我们用两个指针 $i$ 和 $j$ 分别指向两个数组的当前位置,然后开始模拟乘法的过程。\n\n对于当前位置 $i$ 和 $j$,我们取 $f=min(encoded1[i][1],encoded2[j][1])$,表示当前位置的乘积的频次,然后将 $v=encoded1[i][0] \\times encoded2[j][0]$,表示当前位置的乘积的值。如果当前位置的乘积的值 $v$ 和上一个位置的乘积的值相同,则将当前位置的乘积的频次加到上一个位置的乘积的频次上,否则将当前位置的乘积的值和频次加到答案数组中。然后我们将 $encoded1[i][1]$ 和 $encoded2[j][1]$ 分别减去 $f$,如果 $encoded1[i][1]$ 或 $encoded2[j][1]$ 减为 $0$,则将对应的指针向后移动一位。\n\n最后返回答案数组即可。\n\n时间复杂度 $O(m + n)$,其中 $m$ 和 $n$ 分别是两个数组的长度。忽略答案数组的空间消耗,空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(m + n)", "space_complexity": "O(1)" }, { "problem_id": 1869, "explanations": { "1": "We design a function $f(x)$, which represents the length of the longest consecutive substring in string $s$ composed of $x$. If $f(1) > f(0)$, then return `true`, otherwise return `false`.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)`." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1870, "explanations": { "1": "We notice that if a speed value $v$ allows us to arrive within the stipulated time, then for any $v' > v$, we can also definitely arrive within the stipulated time. This exhibits monotonicity, hence we can use binary search to find the smallest speed value that meets the condition.\n\nBefore conducting the binary search, we need to first determine if it is possible to arrive within the stipulated time. If the number of trains is greater than the ceiling of the stipulated time, then it is definitely impossible to arrive within the stipulated time, and we should directly return $-1$.\n\nNext, we define the left and right boundaries for the binary search as $l = 1$, $r = 10^7 + 1$, and then we take the middle value $\\textit{mid} = \\frac{l + r}{2}$ each time to check if it meets the condition. If it does, we move the right boundary to $\\textit{mid}$; otherwise, we move the left boundary to $\\textit{mid} + 1$.\n\nThe problem is transformed into determining whether a speed value $v$ can allow us to arrive within the stipulated time. We can traverse each train trip, calculate the running time of each trip $t = \\frac{d}{v}$, if it is the last trip, we directly add $t$; otherwise, we round up and add $t$. Finally, we check if the total time is less than or equal to the stipulated time, if so, it means the condition is met.\n\nAfter the binary search ends, if the left boundary exceeds $10^7$, it means we cannot arrive within the stipulated time, and we return $-1$; otherwise, we return the left boundary.\n\nThe time complexity is $O(n \\times \\log M)$, where $n$ and $M$ are the number of train trips and the upper bound of the speed, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(1)" }, { "problem_id": 1871, "explanations": { "1": "We define a prefix sum array $pre$ of length $n+1$, where $pre[i]$ represents the number of reachable positions in the first $i$ positions of $s$. We define a boolean array $f$ of length $n$, where $f[i]$ indicates whether $s[i]$ is reachable. Initially, $pre[1] = 1$ and $f[0] = true$.\n\nConsider $i \\in [1, n)$, if $s[i] = 0$, then we need to determine whether there exists a position $j$ in the first $i$ positions of $s$, such that $j$ is reachable and the distance from $j$ to $i$ is within $[minJump, maxJump]$. If such a position $j$ exists, then we have $f[i] = true$, otherwise $f[i] = false$. When determining whether $j$ exists, we can use the prefix sum array $pre$ to determine whether such a position $j$ exists in $O(1)$ time.\n\nThe final answer is $f[n-1]$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1872, "explanations": { "1": "According to the problem description, each time we take the leftmost $x$ stones, add their sum to our score, and then put a stone with this sum value on the leftmost side, it is equivalent to merging these $x$ stones into a stone with this sum value, and the prefix sum remains unchanged.\n\nWe can use a prefix sum array $s$ of length $n$ to represent the prefix sum of the array $stones$, where $s[i]$ represents the sum of the elements $stones[0..i]$.\n\nNext, we design a function $dfs(i)$, which means that we currently take stones from $stones[i:]$, and return the maximum score difference that the current player can get.\n\nThe execution process of the function $dfs(i)$ is as follows:\n\n- If $i \\geq n - 1$, it means that we can only take all the stones at present, so we return $s[n - 1]$.\n- Otherwise, we can choose to take all the stones from $stones[i + 1:]$, and the score difference obtained is $dfs(i + 1)$; we can also choose to take the stones $stones[:i]$, and the score difference obtained is $s[i] - dfs(i + 1)$. We take the maximum of the two situations, which is the maximum score difference that the current player can get.\n\nFinally, we can get the score difference between Alice and Bob as $dfs(1)$, that is, Alice must start the game by taking stones from $stones[1:]$.\n\nTo avoid repeated calculations, we can use memoization search.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $stones$.", "2": "We can also use dynamic programming to solve this problem.\n\nSimilar to Solution 1, we first use a prefix sum array $s$ of length $n$ to represent the prefix sum of the array $stones$, where $s[i]$ represents the sum of the elements $stones[0..i]$.\n\nWe define $f[i]$ to represent the maximum score difference that the current player can get when taking stones from $stones[i:]$.\n\nIf the player chooses to take the stones $stones[:i]$, then the score obtained is $s[i]$. At this time, the other player will take stones from $stones[i+1:]$, and the maximum score difference that the other player can get is $f[i+1]$. Therefore, the maximum score difference that the current player can get is $s[i] - f[i+1]$.\n\nIf the player chooses to take stones from $stones[i+1:]$, then the maximum score difference obtained is $f[i+1]$.\n\nTherefore, we can get the state transition equation:\n\n$$\nf[i] = \\max\\{s[i] - f[i+1], f[i+1]\\}\n$$\n\nFinally, we can get the score difference between Alice and Bob as $f[1]$, that is, Alice must start the game by taking stones from $stones[1:]$.\n\nWe notice that $f[i]$ is only related to $f[i+1]$, so we only need to use a variable $f$ to represent $f[i]$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the array $stones$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1873, "explanations": { "1": "We can use the `IF` statement to determine the calculation method of the bonus, and then use `ORDER BY` to sort the results by `employee_id`." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1874, "explanations": { "1": "Since both arrays consist of positive integers, to minimize the sum of products, we can multiply the largest value in one array with the smallest value in the other array, the second largest with the second smallest, and so on.\n\nTherefore, we sort the array $\\textit{nums1}$ in ascending order and the array $\\textit{nums2}$ in descending order. Then, we multiply the corresponding elements of the two arrays and sum the results.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array $\\textit{nums1}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 1875, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1876, "explanations": { "1": "We can maintain a sliding window such that the characters within the window are not repeated. Initially, we use a binary integer $\\textit{mask}$ of length $26$ to represent the characters within the window, where the $i$-th bit being $1$ indicates that character $i$ has appeared in the window, otherwise it indicates that character $i$ has not appeared in the window.\n\nThen, we traverse the string $s$. For each position $r$, if $\\textit{s}[r]$ has appeared in the window, we need to move the left boundary $l$ of the window to the right until there are no repeated characters in the window. After this, we add $\\textit{s}[r]$ to the window. At this point, if the length of the window is greater than or equal to $3$, then we have found a good substring of length $3$ ending at $\\textit{s}[r]$.\n\nAfter the traversal, we have found the number of all good substrings.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$.\n\n> This solution can be extended to find the number of good substrings of length $k$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1877, "explanations": { "1": "To minimize the maximum pair sum in the array, we can pair the smallest number with the largest number, the second smallest with the second largest, and so on.\n\nTherefore, we can first sort the array, then use two pointers to point to the two ends of the array. Calculate the sum of the numbers pointed to by the two pointers, update the maximum pair sum, then move the left pointer one step to the right and the right pointer one step to the left. Continue this process until the two pointers meet, and we will get the minimum maximum pair sum.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 1878, "explanations": { "1": "We can preprocess to get two prefix sum arrays $s_1$ and $s_2$, where $s_1[i][j]$ represents the sum of the elements on the upper left diagonal ending at $(i, j)$, and $s_2[i][j]$ represents the sum of the elements on the upper right diagonal ending at $(i, j)$.\n\nNext, we enumerate each position $(i, j)$, first add $grid[i][j]$ to the ordered set $ss$, and then enumerate the length $k$ of the diamond. The sum of the diamond with $(i, j)$ as the center and a side length of $k$ is:\n\n$$\n\\begin{aligned}\n&\\quad s_1[i + k][j] - s_1[i][j - k] + s_1[i][j + k] - s_1[i - k][j] \\\\\n&+ s_2[i][j - k] - s_2[i - k][j] + s_2[i + k][j] - s_2[i][j + k] \\\\\n&- grid[i + k - 1][j - 1] + grid[i - k - 1][j - 1]\n\\end{aligned}\n$$\n\nWe add this value to the ordered set $ss$, while ensuring that the size of the ordered set $ss$ does not exceed $3$. Finally, we output the elements in the ordered set $ss$ in reverse order.\n\nThe time complexity is $O(m \\times n \\times \\min(m, n))$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the number of rows and columns of the matrix, respectively." }, "is_english": true, "time_complexity": "O(m \\times n \\times \\min(m, n))", "space_complexity": "O(m \\times n)" }, { "problem_id": 1879, "explanations": { "1": "我们注意到 $n \\leq 14$,因此,我们可以考虑使用状态压缩动态规划的方法求解本题。\n\n我们用一个长度为 $n$ 的二进制数表示当前的状态,第 $i$ 位为 $1$ 表示 $nums2[i]$ 已经被选择,为 $0$ 表示 $nums2[i]$ 还未被选择。\n\n我们定义 $f[i][j]$ 表示 $nums1$ 的前 $i$ 个数中,选择了 $nums2$ 的 $i$ 个数,且当前所选数字的状态为 $j$ 时,数组 $nums1$ 和 $nums2$ 的异或值之和的最小值。初始时 $f[0][0]=0$,其余 $f[i][j]=+\\infty$。\n\n我们可以枚举 $nums1$ 的第 $i$ 个数 $x$,然后在 $[0,2^n)$ 的范围内枚举状态 $j$,转移方程为 $f[i][j]=\\min(f[i][j],f[i-1][j\\oplus 2^k]+(x\\oplus nums2[k]))$,其中 $k$ 是 $j$ 的二进制表示中的某个 $1$ 所在的位置。\n\n最后答案为 $f[n][2^n-1]$。\n\n时间复杂度 $O(n^2 \\times 2^n)$,空间复杂度 $O(n \\times 2^n)$。其中 $n$ 是数组的长度。\n\n我们注意到,状态 $f[i][j]$ 只与 $f[i-1][j\\oplus 2^k]$ 有关,因此我们去掉第一维,将空间复杂度优化到 $O(2^n)$。", "2": "我们也可以直接在 $[0, 2^n)$ 范围内枚举状态 $i$,假设 $i$ 的二进制表示中有 $k$ 个 $1$,那么当前枚举的就是 $nums1$ 的第 $k$ 个数,下标为 $k-1$。状态转移方程为 $f[i]=\\min(f[i],f[i\\oplus 2^j]+(nums1[k-1]\\oplus nums2[j]))$,其中 $j$ 是 $i$ 的二进制表示中的某个 $1$ 所在的位置。\n\n时间复杂度 $O(n \\times 2^n)$,空间复杂度 $O(2^n)$。其中 $n$ 是数组的长度。", "3": "" }, "is_english": false, "time_complexity": "O(n^2 \\times 2^n)", "space_complexity": "O(n \\times 2^n)" }, { "problem_id": 1880, "explanations": { "1": "We define a function $\\textit{f}(s)$ to calculate the numerical value of the string $s$. For each character $c$ in the string $s$, we convert it to the corresponding number $x$, then concatenate $x$ sequentially, and finally convert it to an integer.\n\nFinally, we just need to check whether $\\textit{f}(\\textit{firstWord}) + \\textit{f}(\\textit{secondWord})$ equals $\\textit{f}(\\textit{targetWord})$.\n\nThe time complexity is $O(L)$, where $L$ is the sum of the lengths of all strings in the problem. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(L)", "space_complexity": "O(1)" }, { "problem_id": 1881, "explanations": { "1": "If $n$ is negative, we need to find the first position greater than $x$ and insert $x$ at that position. If $n$ is positive, we need to find the first position less than $x$ and insert $x$ at that position.\n\nThe time complexity is $O(m)$, where $m$ is the length of $n$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m)", "space_complexity": "O(1)" }, { "problem_id": 1882, "explanations": { "1": "We use a min-heap $\\textit{idle}$ to maintain all idle servers, where each element is a tuple $(x, i)$ representing the $i$-th server with weight $x$. We use another min-heap $\\textit{busy}$ to maintain all busy servers, where each element is a tuple $(w, s, i)$ representing the $i$-th server that will be idle at time $w$ with weight $s$. Initially, we add all servers to $\\textit{idle}$.\n\nNext, we iterate through all tasks. For the $j$-th task, we first remove all servers from $\\textit{busy}$ that will be idle at or before time $j$ and add them to $\\textit{idle}$. Then we take the server with the smallest weight from $\\textit{idle}$, add it to $\\textit{busy}$, and assign it to the $j$-th task. If $\\textit{idle}$ is empty, we take the server with the earliest idle time from $\\textit{busy}$, add it to $\\textit{busy}$, and assign it to the $j$-th task.\n\nAfter iterating through all tasks, we obtain the answer array $\\textit{ans}$.\n\nThe time complexity is $O((n + m) \\log n)$, where $n$ is the number of servers and $m$ is the number of tasks. The space complexity is $O(n)$. Here, $n$ and $m$ are the number of servers and tasks, respectively.\n\nSimilar problems:\n\n- [2402. Meeting Rooms III](https://github.com/doocs/leetcode/blob/main/solution/2400-2499/2402.Meeting%20Rooms%20III/README_EN.md)" }, "is_english": true, "time_complexity": "O((n + m) \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1883, "explanations": { "1": "We define $f[i][j]$ as the shortest time considering the first $i$ roads and exactly skipping $j$ rest times. Initially, $f[0][0]=0$, and the rest $f[i][j]=\\infty$.\n\nSince we can choose to skip or not skip the rest time of the $i$-th road, we can list the state transition equation:\n\n$$\nf[i][j]=\\min\\left\\{\\begin{aligned} \\lceil f[i-1][j]+\\frac{d_i}{s}\\rceil & \\textit{Do not skip the rest time of the $i$-th road} \\\\ f[i-1][j-1]+\\frac{d_i}{s} & \\textit{Skip the rest time of the $i$-th road} \\end{aligned}\\right.\n$$\n\nWhere $\\lceil x\\rceil$ represents rounding $x$ up. It should be noted that since we need to ensure that exactly $j$ rest times are skipped, we must have $j\\le i$; moreover, if $j=0$, no rest time can be skipped.\n\nDue to the possible precision error brought by floating-point operations and rounding up, we introduce a constant $eps = 10^{-8}$ to represent a very small positive real number. We subtract $eps$ before rounding the floating-point number, and finally, when comparing $f[n][j]$ and $hoursBefore$, we need to add $eps$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$, where $n$ is the number of roads." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 1884, "explanations": { "1": "We define $f[i]$ to represent the minimum number of operations to determine $f$ in $i$ floors with two eggs. Initially, $f[0] = 0$, and the rest $f[i] = +\\infty$. The answer is $f[n]$.\n\nConsidering $f[i]$, we can enumerate the first egg thrown from the $j$-th floor, where $1 \\leq j \\leq i$. At this point, there are two cases:\n\n- The egg breaks. At this time, we have one egg left and need to determine $f$ in $j - 1$ floors, which requires $j - 1$ operations. Therefore, the total number of operations is $1 + (j - 1)$;\n- The egg does not break. At this time, we have two eggs left and need to determine $f$ in $i - j$ floors, which requires $f[i - j]$ operations. Therefore, the total number of operations is $1 + f[i - j]$.\n\nIn summary, we can obtain the state transition equation:\n\n$$\nf[i] = \\min_{1 \\leq j \\leq i} \\{1 + \\max(j - 1, f[i - j])\\}\n$$\n\nFinally, we return $f[n]$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$. Where $n$ is the number of floors." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 1885, "explanations": { "1": "We can transform the inequality in the problem to $\\textit{nums1}[i] - \\textit{nums2}[i] + \\textit{nums1}[j] - \\textit{nums2}[j] > 0$, which simplifies to $\\textit{nums}[i] + \\textit{nums}[j] > 0$, where $\\textit{nums}[i] = \\textit{nums1}[i] - \\textit{nums2}[i]$.\n\nFor the array $\\textit{nums}$, we need to find all pairs $(i, j)$ that satisfy $\\textit{nums}[i] + \\textit{nums}[j] > 0$.\n\nWe can sort the array $\\textit{nums}$ and then use the two-pointer method. Initialize the left pointer $l = 0$ and the right pointer $r = n - 1$. Each time, we check if $\\textit{nums}[l] + \\textit{nums}[r]$ is less than or equal to $0$. If it is, we move the left pointer to the right in a loop until $\\textit{nums}[l] + \\textit{nums}[r] > 0$. At this point, all pairs with the left pointer at $l$, $l + 1$, $l + 2$, $\\cdots$, $r - 1$ and the right pointer at $r$ satisfy the condition, and there are $r - l$ such pairs. We add these pairs to the answer. Then, move the right pointer to the left and continue the above process until $l \\ge r$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1886, "explanations": { "1": "We observe the rotation pattern of the matrix and find that for an element $\\text{mat}[i][j]$, after rotating 90 degrees it appears at position $\\text{mat}[j][n-1-i]$, after rotating 180 degrees it appears at position $\\text{mat}[n-1-i][n-1-j]$, and after rotating 270 degrees it appears at position $\\text{mat}[n-1-j][i]$.\n\nTherefore, we can use an integer $\\textit{ok}$ to record the current rotation state, initialized to $0b1111$, indicating that all four rotation states are possible. For each element in the matrix, we compare whether its position under different rotation states matches the corresponding element in the target matrix. If they are not equal, we remove that rotation state from $\\textit{ok}$. Finally, if $\\textit{ok}$ is not zero, it means at least one rotation state can make the matrix consistent with the target matrix, and we return $\\textit{true}$; otherwise, we return $\\textit{false}$.\n\nThe time complexity is $O(n^2)$, where $n$ is the size of the matrix. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(1)" }, { "problem_id": 1887, "explanations": { "1": "We first sort the array $\\textit{nums}$, then iterate from the second element of the array. If the current element is not equal to the previous element, we increment $\\textit{cnt}$, indicating the number of operations needed to reduce the current element to the minimum value. Then we add $\\textit{cnt}$ to $\\textit{ans}$ and continue to the next element.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 1888, "explanations": { "1": "We notice that operation $1$ effectively turns the string into a cycle, and operation $2$ makes a substring of length $n$ within the cycle into an alternating binary string.\n\nTherefore, we only need to enumerate each substring of length $n$, calculate the cost to make it an alternating binary string, and take the minimum.\n\nWe can pre-calculate the number of differences between string $s$ and the two types of alternating binary strings, denoted as $\\textit{cnt}$. The cost to make $s$ into the first type of alternating binary string is $\\textit{cnt}$, and the cost to make $s$ into the second type is $n - \\textit{cnt}$. We initialize $\\textit{ans} = \\min(\\textit{cnt}, n - \\textit{cnt})$.\n\nNext, we enumerate each substring of length $n$ and update the value of $\\textit{cnt}$. For each position $i$, we subtract the difference of $s[i]$ from the first type of alternating binary string, and add the difference of $s[i]$ to the second type. We update $\\textit{ans} = \\min(\\textit{ans}, \\textit{cnt}, n - \\textit{cnt})$.\n\nFinally, return $\\textit{ans}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1889, "explanations": { "1": "我们首先对包裹的尺寸数组 $packages$ 进行排序。\n\n然后遍历每个供应商的箱子数组 $boxes$,对于每个箱子数组 $boxes$,我们也对其进行排序。\n\n如果当前箱子数组中最大的箱子尺寸小于包裹数组中最大的包裹尺寸,那么我们就可以跳过这个供应商,因为这个供应商的箱子无法装下最大的包裹。否则,我们从小到大遍历当前供应商的每个箱子 $b$,用一个指针 $i$ 指向当前待装箱的包裹。\n\n接下来,我们在数组 $packages$ 中二分查找,找到第一个尺寸大于 $b$ 的包裹 $packages[j]$。那么我们可以用箱子 $b$ 装下 $packages[i..j-1]$ 中的所有包裹,此时总空间为 $b \\times (j - i)$。然后我们将指针 $i$ 移动到 $j$,继续寻找下一个箱子的装包情况。\n\n遍历完该供应商的所有箱子后,我们就可以得到该供应商所需的箱子总空间。我们遍历所有供应商,找到所需箱子的最小总空间,那么浪费的空间就是总空间减去所有包裹的总尺寸。\n\n时间复杂度 $O(n \\times \\log n + l \\times \\log l + l \\times \\log n)$,空间复杂度 $O(\\log n + \\log l)$。其中 $n$ 是包裹的数量,而 $l$ 是所有箱子的数量。" }, "is_english": false, "time_complexity": "O(n \\times \\log n + l \\times \\log l + l \\times \\log n)", "space_complexity": "O(\\log n + \\log l)" }, { "problem_id": 1890, "explanations": { "1": "We can first filter out the login records in 2020, and then group by `user_id`, and use the `max` function to calculate the maximum login time for each user." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1891, "explanations": { "1": "We observe that if we can obtain $k$ ropes of length $x$, then we can also obtain $k$ ropes of length $x-1$. This implies that there is a monotonicity property, and we can use binary search to find the maximum length $x$ such that we can obtain $k$ ropes of length $x$.\n\nWe define the left boundary of the binary search as $left=0$, the right boundary as $right=\\max(ribbons)$, and the middle value as $mid=(left+right+1)/2$. We then calculate the number of ropes we can obtain with length $mid$, denoted as $cnt$. If $cnt \\geq k$, it means we can obtain $k$ ropes of length $mid$, so we update $left$ to $mid$. Otherwise, we update $right$ to $mid-1$.\n\nFinally, we return $left$ as the maximum length of the ropes we can obtain.\n\nThe time complexity is $O(n \\times \\log M)$, where $n$ and $M$ are the number of ropes and the maximum length of the ropes, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(1)" }, { "problem_id": 1892, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1893, "explanations": { "1": "We can use the idea of a difference array to create a difference array $\\textit{diff}$ of length $52$.\n\nNext, we iterate through the array $\\textit{ranges}$. For each interval $[l, r]$, we increment $\\textit{diff}[l]$ by $1$ and decrement $\\textit{diff}[r + 1]$ by $1$.\n\nThen, we iterate through the difference array $\\textit{diff}$, maintaining a prefix sum $s$. For each position $i$, we increment $s$ by $\\textit{diff}[i]$. If $s \\le 0$ and $left \\le i \\le right$, it indicates that an integer $i$ within the interval $[left, right]$ is not covered, and we return $\\textit{false}$.\n\nIf we finish iterating through the difference array $\\textit{diff}$ without returning $\\textit{false}$, it means that every integer within the interval $[left, right]$ is covered by at least one interval in $\\textit{ranges}$, and we return $\\textit{true}$.\n\nThe time complexity is $O(n + M)$, and the space complexity is $O(M)$. Here, $n$ is the length of the array $\\textit{ranges}$, and $M$ is the maximum value of the interval, which in this case is $M \\le 50$." }, "is_english": true, "time_complexity": "O(n + M)", "space_complexity": "O(M)" }, { "problem_id": 1894, "explanations": { "1": "Since the students' answers are conducted in rounds, we can add up the chalk needed by all students to get a total $s$. Then we take the remainder of $k$ by $s$, which can tell us the remaining number of chalks after the last round.\n\nNext, we just need to simulate the last round. Initially, the remaining number of chalks is $k$, and the student with the number $0$ starts to answer the question. When the remaining number of chalks is less than the current student needs, the current student needs to replenish the chalk, and we directly return the current student's number $i$. Otherwise, we subtract the chalk needed by the current student from the remaining chalk, and add one to the current student's number $i$ for the next simulation.\n\nThe time complexity is $O(n)$, where $n$ is the number of students. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1895, "explanations": { "1": "We define $\\text{rowsum}[i][j]$ as the sum of elements in the $i$-th row up to the $j$-th column of the matrix, and $\\text{colsum}[i][j]$ as the sum of elements in the $j$-th column up to the $i$-th row. Thus, for any submatrix from $(x_1, y_1)$ to $(x_2, y_2)$, the sum of its $i$-th row can be expressed as $\\text{rowsum}[i+1][y_2+1] - \\text{rowsum}[i+1][y_1]$, and the sum of its $j$-th column can be expressed as $\\text{colsum}[x_2+1][j+1] - \\text{colsum}[x_1][j+1]$.\n\nWe enumerate all possible submatrices and check if they are magic squares. For each submatrix, we calculate the sum of each row, each column, and both diagonals to determine if they are all equal.\n\nThe time complexity is $O(m \\times n \\times \\min(m, n)^2)$, and the space complexity is $O(m \\times n)$." }, "is_english": true, "time_complexity": "O(m \\times n \\times \\min(m, n)^2)", "space_complexity": "O(m \\times n)" }, { "problem_id": 1896, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1897, "explanations": { "1": "According to the problem description, as long as the occurrence count of each character can be divided by the length of the string array, it is possible to redistribute the characters to make all strings equal.\n\nTherefore, we use a hash table or an integer array of length $26$ $\\textit{cnt}$ to count the occurrences of each character. Finally, we check if the occurrence count of each character can be divided by the length of the string array.\n\nThe time complexity is $O(L)$, and the space complexity is $O(|\\Sigma|)$. Here, $L$ is the total length of all strings in the array $\\textit{words}$, and $\\Sigma$ is the character set, which is the set of lowercase letters, so $|\\Sigma|=26$." }, "is_english": true, "time_complexity": "O(L)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 1898, "explanations": { "1": "We notice that if removing the characters at the first $k$ indices in $\\textit{removable}$ still makes $p$ a subsequence of $s$, then removing the characters at $k \\lt k' \\leq \\textit{removable.length}$ indices will also satisfy the condition. This monotonicity allows us to use binary search to find the maximum $k$.\n\nWe define the left boundary of the binary search as $l = 0$ and the right boundary as $r = \\textit{removable.length}$. Then we perform binary search. In each search, we take the middle value $mid = \\left\\lfloor \\frac{l + r + 1}{2} \\right\\rfloor$ and check if removing the characters at the first $mid$ indices in $\\textit{removable}$ still makes $p$ a subsequence of $s$. If it does, we update the left boundary $l = mid$; otherwise, we update the right boundary $r = mid - 1$.\n\nAfter the binary search ends, we return the left boundary $l$.\n\nThe time complexity is $O(k \\times \\log k)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $s$, and $k$ is the length of $\\textit{removable}$." }, "is_english": true, "time_complexity": "O(k \\times \\log k)", "space_complexity": "O(n)" }, { "problem_id": 1899, "explanations": { "1": "Let $\\textit{target} = [x, y, z]$. We need to determine whether there exists a triplet $[a, b, c]$ such that $a \\leq x$, $b \\leq y$, and $c \\leq z$.\n\nWe can divide all triplets into two categories:\n\n1. Triplets that satisfy $a \\leq x$, $b \\leq y$, and $c \\leq z$.\n2. Triplets that do not satisfy $a \\leq x$, $b \\leq y$, and $c \\leq z$.\n\nFor the first category, we can take the maximum values of $a$, $b$, and $c$ from these triplets to form a new triplet $[d, e, f]$.\n\nFor the second category, we can ignore these triplets because they cannot help us achieve the target triplet.\n\nFinally, we just need to check whether $[d, e, f]$ is equal to $\\textit{target}$. If it is, return $\\textit{true}$; otherwise, return $\\textit{false}$.\n\nTime complexity is $O(n)$, where $n$ is the length of the array $\\textit{triplets}$. Space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1900, "explanations": { "1": "We define a function $\\text{dfs}(l, r, n)$, which represents the earliest and latest rounds where players numbered $l$ and $r$ compete among $n$ players in the current round.\n\nThe execution logic of function $\\text{dfs}(l, r, n)$ is as follows:\n\n1. If $l + r = n - 1$, it means the two players compete in the current round, return $[1, 1]$.\n2. If $f[l][r][n] \\neq 0$, it means this state has been calculated before, directly return the result.\n3. Initialize the earliest round number as positive infinity and the latest round number as negative infinity.\n4. Calculate the number of players in the first half of the current round $m = n / 2$.\n5. Enumerate all possible winner combinations of the first half (using binary enumeration), for each combination:\n - Determine which players win based on the current combination.\n - Determine the positions of players numbered $l$ and $r$ in the current round.\n - Count the positions of players numbered $l$ and $r$ among the remaining players, denoted as $a$ and $b$, and the total number of remaining players $c$.\n - Recursively call $\\text{dfs}(a, b, c)$ to get the earliest and latest round numbers for the current state.\n - Update the earliest and latest round numbers.\n6. Store the calculation result in $f[l][r][n]$ and return the earliest and latest round numbers.\n\nThe answer is $\\text{dfs}(\\text{firstPlayer} - 1, \\text{secondPlayer} - 1, n)$." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1901, "explanations": { "1": "Let $m$ and $n$ be the number of rows and columns of the matrix, respectively.\n\nThe problem asks us to find a peak, and the time complexity should be $O(m \\times \\log n)$ or $O(n \\times \\log m)$. Therefore, we can consider using binary search.\n\nWe consider the maximum value of the $i$-th row, and denote its index as $j$.\n\nIf $mat[i][j] > mat[i + 1][j]$, then there must be a peak in the rows $[0,..i]$. We only need to find the maximum value in these rows. Similarly, if $mat[i][j] < mat[i + 1][j]$, then there must be a peak in the rows $[i + 1,..m - 1]$. We only need to find the maximum value in these rows.\n\nWhy is the above method correct? We can prove it by contradiction.\n\nIf $mat[i][j] > mat[i + 1][j]$, suppose there is no peak in the rows $[0,..i]$. Then $mat[i][j]$ is not a peak. Since $mat[i][j]$ is the maximum value of the $i$-th row, and $mat[i][j] > mat[i + 1][j]$, then $mat[i][j] < mat[i - 1][j]$. We continue to consider from the $(i - 1)$-th row upwards, and the maximum value of each row is less than the maximum value of the previous row. When we traverse to $i = 0$, since all elements in the matrix are positive integers, and the values of the cells around the matrix are $-1$. Therefore, at the 0-th row, its maximum value is greater than all its adjacent elements, so the maximum value of the 0-th row is a peak, which contradicts the assumption. Therefore, there must be a peak in the rows $[0,..i]$.\n\nFor the case where $mat[i][j] < mat[i + 1][j]$, we can prove in a similar way that there must be a peak in the rows $[i + 1,..m - 1]$.\n\nTherefore, we can use binary search to find the peak.\n\nWe perform binary search on the rows of the matrix, initially with the search boundaries $l = 0$, $r = m - 1$. Each time, we find the middle row $mid$ and find the index $j$ of the maximum value of this row. If $mat[mid][j] > mat[mid + 1][j]$, then we search for the peak in the rows $[0,..mid]$, i.e., update $r = mid$. Otherwise, we search for the peak in the rows $[mid + 1,..m - 1]$, i.e., update $l = mid + 1$. When $l = r$, we find the position $[l, j_l]$ of the peak, where $j_l$ is the index of the maximum value of the $l$-th row.\n\nThe time complexity is $O(n \\times \\log m)$, where $m$ and $n$ are the number of rows and columns of the matrix, respectively. The time complexity of binary search is $O(\\log m)$, and each time we perform binary search, we need to traverse all elements of the $mid$-th row, with a time complexity of $O(n)$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m \\times \\log n)", "space_complexity": "O(1)" }, { "problem_id": 1902, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1903, "explanations": { "1": "We can traverse the string from the end to the beginning, find the first odd number, and then return the substring from the beginning to this odd number. If there is no odd number, return an empty string.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $num$. Ignoring the space consumption of the answer string, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1904, "explanations": { "1": "We can convert the input strings to minutes $a$ and $b$. If $a > b$, it means that it crosses midnight, so we need to add one day's minutes $1440$ to $b$.\n\nThen we round $a$ up to the nearest multiple of $15$, and round $b$ down to the nearest multiple of $15$. Finally, we return the difference between $b$ and $a$. Note that we should take the larger value between $0$ and $b - a$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 1905, "explanations": { "1": "We can traverse each cell $(i, j)$ in the matrix `grid2`. If the value of the cell is $1$, we start a depth-first search from this cell, set the value of all cells connected to this cell to $0$, and record whether the corresponding cell in `grid1` is also $1$ for all cells connected to this cell. If it is $1$, it means that this cell is also an island in `grid1`, otherwise it is not. Finally, we count the number of sub-islands in `grid2`.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the number of rows and columns of the matrices `grid1` and `grid2`, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 1906, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1907, "explanations": { "1": "We can first create a temporary table containing all salary categories, and then count the number of bank accounts for each salary category. Finally, we use a left join to connect the temporary table with the result table to ensure that the result table contains all salary categories.", "2": "We can filter out the number of bank accounts for each salary category separately, and then merge the results. Here, we use `UNION` to merge the results." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1908, "explanations": { "1": "我们发现,一共最多有 $7$ 堆石头,每堆石头最多有 $7$ 个,那么一共有 $7^7$ 种状态,因此我们可以用一个八进制数来表示当前的状态。\n\n接下来,我们用记忆化搜索的方法来解决这个问题。定义一个函数 $dfs(piles)$,表示当前的状态为 $piles$ 时,当前玩家是否能获胜。\n\n函数 $dfs(piles)$ 的执行过程如下:\n\n- 如果 $piles$ 所表示的状态已经被计算过,直接返回结果;\n- 否则,我们枚举每一堆石头,尝试移除 $1,2,3,...,x$ 个石头,如果移除后的状态 $piles'$ 不能获胜,那么当前玩家就能获胜,返回结果。\n- 如果所有的移除方案都不能获胜,那么当前玩家不能获胜,返回结果。\n\n时间复杂度 $(7^7 \\times 7^2)$,空间复杂度 $O(7^7)$。" }, "is_english": false, "time_complexity": "O(7^7)", "space_complexity": "O(7^7)" }, { "problem_id": 1909, "explanations": { "1": "We can traverse the array to find the first position $i$ where $\\textit{nums}[i] < \\textit{nums}[i+1]$ is not satisfied. Then, we check if the array is strictly increasing after removing either $i$ or $i+1$. If it is, we return $\\textit{true}$; otherwise, we return $\\textit{false}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1910, "explanations": { "1": "我们循环判断 $s$ 中是否存在字符串 $part$,是则进行一次替换,继续循环此操作,直至 $s$ 中不存在字符串 $part$,返回此时的 $s$ 作为答案字符串。\n\n时间复杂度 $O(n^2 + n \\times m)$,空间复杂度 $O(n + m)$。其中 $n$ 和 $m$ 分别是字符串 $s$ 和字符串 $part$ 的长度。" }, "is_english": false, "time_complexity": "O(n^2 + n \\times m)", "space_complexity": "O(n + m)" }, { "problem_id": 1911, "explanations": { "1": "我们定义 $f[i]$ 表示从前 $i$ 个元素中选出的子序列,且最后一个元素为奇数下标时的最大交替和,定义 $g[i]$ 表示从前 $i$ 个元素中选出的子序列,且最后一个元素为偶数下标时的最大交替和。初始时 $f[0] = g[0] = 0$。答案为 $max(f[n], g[n])$。\n\n我们考虑第 $i$ 个元素 $nums[i - 1]$:\n\n如果选取该元素且该元素为奇数下标,那么上一个元素必须为偶数下标,且只能从前 $i-1$ 个元素中选取,因此 $f[i] = g[i - 1] - nums[i - 1]$;如果不选取该元素,那么 $f[i] = f[i - 1]$。\n\n同理,如果选取该元素且该元素为偶数下标,那么上一个元素必须为奇数下标,且只能从前 $i-1$ 个元素中选取,因此 $g[i] = f[i - 1] + nums[i - 1]$;如果不选取该元素,那么 $g[i] = g[i - 1]$。\n\n综上,我们可以得到状态转移方程:\n\n$$\n\\begin{aligned}\nf[i] &= max(g[i - 1] - nums[i - 1], f[i - 1]) \\\\\ng[i] &= max(f[i - 1] + nums[i - 1], g[i - 1])\n\\end{aligned}\n$$\n\n最终答案为 $max(f[n], g[n])$。\n\n我们注意到 $f[i]$ 和 $g[i]$ 只与 $f[i - 1]$ 和 $g[i - 1]$ 有关,因此我们可以使用两个变量代替数组,将空间复杂度降低到 $O(1)$。\n\n时间复杂度 $O(n)$,其中 $n$ 为数组长度。", "2": "" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1912, "explanations": { "1": "We define an ordered set $\\textit{available}$, where $\\textit{available}[movie]$ stores a list of all shops that have not rented out the movie $movie$. Each element in the list is $(\\textit{price}, \\textit{shop})$, sorted in ascending order by $\\textit{price}$, and if prices are equal, by $\\textit{shop}$ in ascending order.\n\nAdditionally, we define a hash map $\\textit{price\\_map}$, where $\\textit{price\\_map}[f(\\textit{shop}, \\textit{movie})]$ stores the rental price of movie $\\textit{movie}$ in shop $\\textit{shop}$.\n\nWe also define an ordered set $\\textit{rented}$, which stores all rented movies as $(\\textit{price}, \\textit{shop}, \\textit{movie})$, sorted in ascending order by $\\textit{price}$, then by $\\textit{shop}$, and if both are equal, by $\\textit{movie}$.\n\nFor the $\\text{MovieRentingSystem}(n, \\text{entries})$ operation, we iterate through $\\text{entries}$ and add each shop's movie information to both $\\textit{available}$ and $\\textit{price\\_map}$. The time complexity is $O(m \\log m)$, where $m$ is the length of $\\text{entries}$.\n\nFor the $\\text{search}(\\text{movie})$ operation, we return the shop IDs of the first 5 shops in $\\textit{available}[\\text{movie}]$. The time complexity is $O(1)$.\n\nFor the $\\text{rent}(\\text{shop}, \\text{movie})$ operation, we remove $(\\textit{price}, \\textit{shop})$ from $\\textit{available}[\\text{movie}]$ and add $(\\textit{price}, \\textit{shop}, \\textit{movie})$ to $\\textit{rented}$. The time complexity is $O(\\log m)$.\n\nFor the $\\text{drop}(\\text{shop}, \\text{movie})$ operation, we remove $(\\textit{price}, \\textit{shop}, \\textit{movie})$ from $\\textit{rented}$ and add $(\\textit{price}, \\textit{shop})$ back to $\\textit{available}[\\text{movie}]$. The time complexity is $O(\\log m)$.\n\nFor the $\\text{report}()$ operation, we return the shop and movie IDs of the first 5 rented movies in $\\textit{rented}$. The time complexity is $O(1)$.\n\nThe space complexity is $O(m)$, where $m$ is the length of $\\text{entries}$." }, "is_english": true, "time_complexity": "O(m \\log m)", "space_complexity": "O(m)" }, { "problem_id": 1913, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1914, "explanations": { "1": "我们先计算得到矩阵的层数 $p$,然后从外到内逐层模拟循环轮转的过程。\n\n对于每一层,我们按照顺时针方向,将上、右、下、左四条边的元素依次放入数组 $nums$ 中。记数组 $nums$ 的长度为 $l$。接下来,我们将 $k$ 模 $l$。然后从数组的第 $k$ 个位置开始,将数组中的元素依次放回矩阵的上、右、下、左四条边。\n\n时间复杂度 $O(m \\times n)$,空间复杂度 $O(m + n)$。其中 $m$ 和 $n$ 分别是矩阵的行数和列数。" }, "is_english": false, "time_complexity": "O(m \\times n)", "space_complexity": "O(m + n)" }, { "problem_id": 1915, "explanations": { "1": "由于字符串中只包含 $10$ 个小写字母,因此可以用一个长度为 $10$ 的二进制数表示字符串中每个字母的奇偶性,其中第 $i$ 位为 $1$ 表示第 $i$ 个字母出现了奇数次,为 $0$ 表示第 $i$ 个字母出现了偶数次。\n\n我们遍历字符串的每个字符,用一个变量 $st$ 维护当前字符串的前缀异或值,用一个数组 $cnt$ 维护每个前缀异或值出现的次数,初始时 $st = 0$, $cnt[0] = 1$。\n\n对于当前遍历到的字符,我们更新其前缀异或值。如果当前的前缀异或值出现了 $cnt[st]$ 次,也就意味着有 $cnt[st]$ 个子字符串满足所有字母的出现次数均为偶数,因此我们将答案增加 $cnt[st]$。此外,对于 $0 \\le i < 10$,如果当前的前缀异或值 $st$ 的第 $i$ 位为 $1$,那么我们还可以找到一个字母出现了奇数次,我们将答案增加 $cnt[st \\oplus (1 << i)]$。最后,我们将 $st$ 出现的次数增加 $1$。继续遍历下一个字符,直到遍历完整个字符串。\n\n时间复杂度 $O(n \\times \\Sigma)$,空间复杂度 $O(2^{\\Sigma})$,其中 $\\Sigma = 10$,而 $n$ 为字符串的长度。\n\n相似题目:\n\n- [1371. 每个元音包含偶数次的最长子字符串](https://github.com/doocs/leetcode/blob/main/solution/1300-1399/1371.Find%20the%20Longest%20Substring%20Containing%20Vowels%20in%20Even%20Counts/README.md)" }, "is_english": false, "time_complexity": "O(n \\times \\Sigma)", "space_complexity": "O(2^{\\Sigma})" }, { "problem_id": 1916, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1917, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1918, "explanations": { "1": "We observe that all elements in the array are positive integers. The larger the subarray sum $s$, the more subarrays there are with sums less than or equal to $s$. This monotonicity allows us to use binary search to solve the problem.\n\nWe perform binary search on the subarray sum, initializing the left and right boundaries as the minimum value in the array $\\textit{nums}$ and the sum of all elements in the array, respectively. Each time, we calculate the number of subarrays with sums less than or equal to the current middle value. If the count is greater than or equal to $k$, it means the current middle value $s$ might be the $k$-th smallest subarray sum, so we shrink the right boundary. Otherwise, we increase the left boundary. After the binary search ends, the left boundary will be the $k$-th smallest subarray sum.\n\nThe problem reduces to calculating the number of subarrays in an array with sums less than or equal to $s$, which we can compute using a function $f(s)$.\n\nThe function $f(s)$ is calculated as follows:\n\n- Initialize two pointers $j$ and $i$, representing the left and right boundaries of the current window, with $j = i = 0$. Also, initialize the sum of elements in the window $t = 0$.\n- Use a variable $\\textit{cnt}$ to record the number of subarrays with sums less than or equal to $s$, initially $\\textit{cnt} = 0$.\n- Traverse the array $\\textit{nums}$. For each element $\\textit{nums}[i]$, add it to the window, i.e., $t = t + \\textit{nums}[i]$. If $t > s$, move the left boundary of the window to the right until $t \\leq s$, i.e., repeatedly execute $t -= \\textit{nums}[j]$ and $j = j + 1$. Then update $\\textit{cnt}$ as $\\textit{cnt} = \\textit{cnt} + i - j + 1$. Continue to the next element until the entire array is traversed.\n\nFinally, return $cnt$ as the result of the function $f(s)$.\n\nTime complexity is $O(n \\times \\log S)$, where $n$ is the length of the array $\\textit{nums}$, and $S$ is the sum of all elements in the array $\\textit{nums}$. Space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\log S)", "space_complexity": "O(1)" }, { "problem_id": 1919, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1920, "explanations": { "1": "We can directly simulate the process described in the problem by constructing a new array $\\textit{ans}$. For each $i$, let $\\textit{ans}[i] = \\textit{nums}[\\textit{nums}[i]]$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. Ignoring the space consumption of the answer array, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1921, "explanations": { "1": "We use the $\\textit{times}$ array to record the latest time each monster can be eliminated. For the $i$-th monster, the latest time it can be eliminated is:\n\n$$\\textit{times}[i] = \\left\\lfloor \\frac{\\textit{dist}[i]-1}{\\textit{speed}[i]} \\right\\rfloor$$\n\nNext, we sort the $\\textit{times}$ array in ascending order.\n\nThen, we traverse the $\\textit{times}$ array. For the $i$-th monster, if $\\textit{times}[i] \\geq i$, it means the $i$-th monster can be eliminated. Otherwise, it means the $i$-th monster cannot be eliminated, and we return $i$ immediately.\n\nIf all monsters can be eliminated, we return $n$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1922, "explanations": { "1": "For a \"good number\" of length $n$, the even-indexed positions have $\\lceil \\frac{n}{2} \\rceil = \\lfloor \\frac{n + 1}{2} \\rfloor$ digits, and these positions can be filled with $5$ different digits ($0, 2, 4, 6, 8$). The odd-indexed positions have $\\lfloor \\frac{n}{2} \\rfloor$ digits, and these positions can be filled with $4$ different digits ($2, 3, 5, 7$). Therefore, the total number of \"good numbers\" of length $n$ is:\n\n$$\nans = 5^{\\lceil \\frac{n}{2} \\rceil} \\times 4^{\\lfloor \\frac{n}{2} \\rfloor}\n$$\n\nWe can use fast exponentiation to compute $5^{\\lceil \\frac{n}{2} \\rceil}$ and $4^{\\lfloor \\frac{n}{2} \\rfloor}$. The time complexity is $O(\\log n)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 1923, "explanations": { "1": "**字符串哈希**是把一个任意长度的字符串映射成一个非负整数,并且其冲突的概率几乎为 0。字符串哈希用于计算字符串哈希值,快速判断两个字符串是否相等。\n\n取一固定值 BASE,把字符串看作是 BASE 进制数,并分配一个大于 0 的数值,代表每种字符。一般来说,我们分配的数值都远小于 BASE。例如,对于小写字母构成的字符串,可以令 a=1, b=2, ..., z=26。取一固定值 MOD,求出该 BASE 进制对 M 的余数,作为该字符串的 hash 值。\n\n一般来说,取 BASE=131 或者 BASE=13331,此时 hash 值产生的冲突概率极低。只要两个字符串 hash 值相同,我们就认为两个字符串是相等的。通常 MOD 取 2^64,C++ 里,可以直接使用 unsigned long long 类型存储这个 hash 值,在计算时不处理算术溢出问题,产生溢出时相当于自动对 2^64 取模,这样可以避免低效取模运算。\n\n除了在极特殊构造的数据上,上述 hash 算法很难产生冲突,一般情况下上述 hash 算法完全可以出现在题目的标准答案中。我们还可以多取一些恰当的 BASE 和 MOD 的值(例如大质数),多进行几组 hash 运算,当结果都相同时才认为原字符串相等,就更加难以构造出使这个 hash 产生错误的数据。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1924, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1925, "explanations": { "1": "We enumerate $a$ and $b$ in the range $[1, n)$, then calculate $c = \\sqrt{a^2 + b^2}$. If $c$ is an integer and $c \\leq n$, then we have found a Pythagorean triplet, and we increment the answer by one.\n\nAfter the enumeration is complete, return the answer.\n\nThe time complexity is $O(n^2)$, where $n$ is the given integer. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(1)" }, { "problem_id": 1926, "explanations": { "1": "We can start from the entrance and perform a breadth-first search (BFS). Each time we reach a new empty cell, we mark it as visited and add it to the queue until we find an empty cell on the boundary, then return the number of steps.\n\nSpecifically, we define a queue $q$, initially adding $\\textit{entrance}$ to the queue. We define a variable $\\textit{ans}$ to record the number of steps, initially set to $1$. Then we start the BFS. In each round, we take out all elements from the queue and traverse them. For each element, we try to move in four directions. If the new position is an empty cell, we add it to the queue and mark it as visited. If the new position is an empty cell on the boundary, we return $\\textit{ans}$. If the queue is empty, we return $-1$. After this round of search, we increment $\\textit{ans}$ by one and continue to the next round of search.\n\nIf we finish the traversal without finding an empty cell on the boundary, we return $-1$.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the number of rows and columns in the maze, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 1927, "explanations": { "1": "If the number of `'?'` is odd, Alice will definitely win because she can choose to replace the last `'?'` with any digit, making the sum of the first half different from the sum of the second half.\n\nIf the number of `'?'` is even, Alice will try to make the sums of the two halves different by placing $9$ in the half with the larger current sum and $0$ in the half with the smaller current sum. Bob, on the other hand, will try to make the sums equal by placing a digit in the other half that matches the digit Alice placed.\n\nAs a result, all remaining even-numbered `'?'` will be concentrated in one half. Suppose the current difference between the sums of the two halves is $d$.\n\nLet's consider the case where there are two remaining `'?'` and the difference is $x$:\n\n- If $x \\lt 9$, Alice will definitely win because she can replace one of the `'?'` with $9$, making the sums of the two halves different.\n- If $x \\gt 9$, Alice will definitely win because she can replace one of the `'?'` with $0$, making the sums of the two halves different.\n- If $x = 9$, Bob will definitely win. Suppose Alice replaces a digit with $a$, then Bob can replace the other `'?'` with $9 - a$, making the sums of the two halves equal.\n\nTherefore, if the difference between the sums of the two halves is $d = \\frac{9 \\times \\textit{cnt}}{2}$, where $\\textit{cnt}$ is the number of remaining `'?'`, Bob will definitely win; otherwise, Alice will definitely win.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1928, "explanations": { "1": "We define $f[i][j]$ to represent the minimum cost to reach city $j$ from city $0$ after $i$ minutes. Initially, $f[0][0] = \\textit{passingFees}[0]$, and the rest $f[0][j] = +\\infty$.\n\nNext, within the time range $[1, \\textit{maxTime}]$, we traverse all edges. For each edge $(x, y, t)$, if $t \\leq i$, then we:\n\n- Can first spend $i - t$ minutes to reach city $y$ from city $0$, then spend $t$ minutes to reach city $x$ from city $y$, and add the passing fee to reach city $x$, i.e., $f[i][x] = \\min(f[i][x], f[i - t][y] + \\textit{passingFees}[x])$;\n- Can also first spend $i - t$ minutes to reach city $x$ from city $0$, then spend $t$ minutes to reach city $y$ from city $x$, and add the passing fee to reach city $y$, i.e., $f[i][y] = \\min(f[i][y], f[i - t][x] + \\textit{passingFees}[y])$.\n\nThe final answer is $\\min\\{f[i][n - 1]\\}$, where $i \\in [0, \\textit{maxTime}]$. If the answer is $+\\infty$, return $-1$.\n\nThe time complexity is $O(\\textit{maxTime} \\times (m + n))$, where $m$ and $n$ are the number of edges and cities, respectively. The space complexity is $O(\\textit{maxTime} \\times n)$." }, "is_english": true, "time_complexity": "O(\\textit{maxTime} \\times (m + n))", "space_complexity": "O(\\textit{maxTime} \\times n)" }, { "problem_id": 1929, "explanations": { "1": "We directly simulate according to the problem description by adding the elements of $\\textit{nums}$ to the answer array one by one, and then adding the elements of $\\textit{nums}$ to the answer array again.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1930, "explanations": { "1": "Since the string contains only lowercase letters, we can directly enumerate all pairs of end characters. For each pair of end characters $c$, we find their first and last occurrence positions $l$ and $r$ in the string. If $r - l > 1$, it means we have found a palindromic subsequence that meets the conditions. We then count the number of unique characters between $[l+1,..r-1]$, which gives the number of palindromic subsequences with $c$ as the end characters, and add it to the answer.\n\nAfter enumerating all pairs, we get the answer.\n\nThe time complexity is $O(n \\times |\\Sigma|)$, where $n$ is the length of the string and $\\Sigma$ is the size of the character set. In this problem, $|\\Sigma| = 26$. The space complexity is $O(|\\Sigma|)$ or $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times |\\Sigma|)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 1931, "explanations": { "1": "We notice that the number of rows in the grid does not exceed $5$, so there are at most $3^5=243$ different color schemes in a column.\n\nTherefore, we define $f[i][j]$ to represent the number of schemes in the first $i$ columns, where the coloring state of the $i$th column is $j$. The state $f[i][j]$ is transferred from $f[i - 1][k]$, where $k$ is the coloring state of the $i - 1$th column, and $k$ and $j$ meet the requirement of different colors being adjacent. That is:\n\n$$\nf[i][j] = \\sum_{k \\in \\textit{valid}(j)} f[i - 1][k]\n$$\n\nwhere $\\textit{valid}(j)$ represents all legal predecessor states of state $j$.\n\nThe final answer is the sum of $f[n][j]$, where $j$ is any legal state.\n\nWe notice that $f[i][j]$ is only related to $f[i - 1][k]$, so we can use a rolling array to optimize the space complexity.\n\nThe time complexity is $O((m + n) \\times 3^{2m})$, and the space complexity is $O(3^m)$. Here, $m$ and $n$ are the number of rows and columns of the grid, respectively." }, "is_english": true, "time_complexity": "O((m + n) \\times 3^{2m})", "space_complexity": "O(3^m)" }, { "problem_id": 1932, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1933, "explanations": { "1": "We traverse the string $s$, using two pointers $i$ and $j$ to count the length of each equal substring. If the length modulo $3$ is $1$, it means that the length of this substring does not meet the requirements, so we return `false`. If the length modulo $3$ is $2$, it means that a substring of length $2$ has appeared. If a substring of length $2$ has appeared before, return `false`, otherwise assign the value of $j$ to $i$ and continue to traverse.\n\nAfter the traversal, check whether a substring of length $2$ has appeared. If not, return `false`, otherwise return `true`.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1934, "explanations": { "1": "We can use a left join to join the `Signups` table and the `Confirmations` table on `user_id`, and then use `GROUP BY` to group by `user_id` for aggregation." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1935, "explanations": { "1": "We can use a hash table or an array $s$ of length $26$ to record all the broken letter keys.\n\nThen, we traverse each word $w$ in the string $text$, and if any letter $c$ in $w$ appears in $s$, it means that the word cannot be typed, and we do not need to add one to the answer. Otherwise, we need to add one to the answer.\n\nAfter the traversal, we return the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(|\\Sigma|)$, where $n$ is the length of the string $text$, and $|\\Sigma|$ is the size of the alphabet. In this problem, $|\\Sigma|=26$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 1936, "explanations": { "1": "According to the problem description, we know that every time we plan to climb a new rung, we need to ensure that the height difference between the new rung and the current position does not exceed `dist`. Otherwise, we need to greedily insert a new rung at a distance of $dist$ from the current position, climb a new rung, and the total number of rungs to be inserted is $\\lfloor \\frac{b - a - 1}{dist} \\rfloor$, where $a$ and $b$ are the current position and the height of the new rung, respectively. The answer is the sum of all inserted rungs.\n\nThe time complexity is $O(n)$, where $n$ is the length of `rungs`. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1937, "explanations": { "1": "我们定义 $f[i][j]$ 表示选取前 $i-1$ 行,并且第 $i-1$ 行选择第 $j$ 列的格子时的最大得分。初始时 $f[0][j] = points[0][j]$。\n\n对于 $i > 0$ 的情况,对于 $f[i][j]$,我们考虑是从上一行的哪一列转移过来的,记上一行选择的列为 $k$,那么有:\n\n$$\nf[i][j]=\n\\begin{cases}\n\\max(f[i - 1][k] + k - j + points[i][j]), & 0 \\le k < j \\\\\n\\max(f[i - 1][k] - k + j + points[i][j]), & j < k < n\n\\end{cases}\n$$\n\n其中 $n$ 表示列数。答案为 $\\max\\limits_{0 \\le j < n} f[m - 1][j]$。\n\n我们注意到 $f[i]$ 的值只跟 $f[i-1]$ 的值有关,因此我们可以使用滚动数组优化空间复杂度。\n\n时间复杂度 $O(m \\times n)$,空间复杂度 $O(n)$。其中 $m$ 和 $n$ 分别是矩阵的行数和列数。" }, "is_english": false, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 1938, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1939, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1940, "explanations": { "1": "We note that the range of elements is $[1, 100]$, so we can use an array $\\textit{cnt}$ of length $101$ to record the number of occurrences of each element.\n\nSince each array in $\\textit{arrays}$ is strictly increasing, the elements of the common subsequence must be monotonically increasing, and the number of occurrences of these elements must be equal to the length of $\\textit{arrays}$.\n\nTherefore, we can traverse each array in $\\textit{arrays}$ and count the number of occurrences of each element. Finally, traverse each element of $\\textit{cnt}$ from smallest to largest. If the number of occurrences is equal to the length of $\\textit{arrays}$, then this element is one of the elements of the common subsequence, and we add it to the answer array.\n\nAfter the traversal, return the answer array.\n\nThe time complexity is $O(M + N)$, and the space complexity is $O(M)$. Here, $M$ is the range of elements, and in this problem, $M = 101$, and $N$ is the total number of elements in the arrays." }, "is_english": true, "time_complexity": "O(M + N)", "space_complexity": "O(M)" }, { "problem_id": 1941, "explanations": { "1": "We use a hash table or an array of length $26$ called $\\textit{cnt}$ to record the number of occurrences of each character in the string $s$.\n\nNext, we traverse each value in $\\textit{cnt}$ and check if all non-zero values are equal.\n\nThe time complexity is $O(n)$, and the space complexity is $O(|\\Sigma|)$. Here, $n$ is the length of the string $s$, and $\\Sigma$ is the size of the character set. In this problem, the character set consists of lowercase English letters, so $|\\Sigma|=26$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 1942, "explanations": { "1": "First, we create a tuple for each friend consisting of their arrival time, leaving time, and index, then sort these tuples by arrival time.\n\nWe use a min-heap $\\textit{idle}$ to store the currently available chair numbers. Initially, we add $0, 1, \\ldots, n-1$ to $\\textit{idle}$. We also use a min-heap $\\textit{busy}$ to store tuples $(\\textit{leaving}, \\textit{chair})$, where $\\textit{leaving}$ represents the leaving time and $\\textit{chair}$ represents the chair number.\n\nWe iterate through each friend's arrival time, leaving time, and index. For each friend, we first remove all friends from $\\textit{busy}$ whose leaving time is less than or equal to the current friend's arrival time, and add their chair numbers back to $\\textit{idle}$. Then we pop a chair number from $\\textit{idle}$, assign it to the current friend, and add $(\\textit{leaving}, \\textit{chair})$ to $\\textit{busy}$. If the current friend's index is equal to $\\textit{targetFriend}$, we return the assigned chair number.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the number of friends." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1943, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1944, "explanations": { "1": "We observe that for the $i$-th person, the people he can see must be strictly increasing in height from left to right.\n\nTherefore, we can traverse the array $\\textit{heights}$ in reverse order, using a stack $\\textit{stk}$ that is monotonically increasing from top to bottom to record the heights of the people we have traversed.\n\nFor the $i$-th person, if the stack is not empty and the top element of the stack is less than $\\textit{heights}[i]$, we increment the count of people the $i$-th person can see, then pop the top element of the stack, until the stack is empty or the top element of the stack is greater than or equal to $\\textit{heights}[i]$. If the stack is not empty at this point, it means the top element of the stack is greater than or equal to $\\textit{heights}[i]$, so we increment the count of people the $i$-th person can see by 1.\n\nNext, we push $\\textit{heights}[i]$ onto the stack and continue to the next person.\n\nAfter traversing, we return the answer array $\\textit{ans}$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{heights}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1945, "explanations": { "1": "We can simulate the process described in the problem.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1946, "explanations": { "1": "According to the problem description, we can start from the highest digit of the string and greedily perform continuous replacement operations until we encounter a digit smaller than the current digit.\n\nFirst, we convert the string $\\textit{num}$ into a character array $\\textit{s}$ and use a variable $\\textit{changed}$ to record whether a change has already occurred, initially $\\textit{changed} = \\text{false}$.\n\nThen we traverse the character array $\\textit{s}$. For each character $\\textit{c}$, we convert it to a number $\\textit{d} = \\text{change}[\\text{int}(\\textit{c})]$. If a change has already occurred and $\\textit{d} < \\textit{c}$, it means we cannot continue changing, so we exit the loop immediately. Otherwise, if $\\textit{d} > \\textit{c}$, it means we can replace $\\textit{c}$ with $\\textit{d}$. At this point, we set $\\textit{changed} = \\text{true}$ and replace $\\textit{s}[i]$ with $\\textit{d}$.\n\nFinally, we convert the character array $\\textit{s}$ back to a string and return it.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $\\textit{num}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1947, "explanations": { "1": "We can first preprocess the compatibility score $g[i][j]$ between each student $i$ and mentor $j$, and then use a backtracking algorithm to solve the problem.\n\nDefine a function $\\textit{dfs}(i, s)$, where $i$ represents the current student being processed, and $s$ represents the current sum of compatibility scores.\n\nIn $\\textit{dfs}(i, s)$, if $i \\geq m$, it means all students have been assigned, and we update the answer to $\\max(\\textit{ans}, s)$. Otherwise, we enumerate which mentor the $i$-th student can be assigned to, and then recursively process the next student. During the process, we use an array $\\textit{vis}$ to record which mentors have already been assigned to avoid duplicate assignments.\n\nWe call $\\textit{dfs}(0, 0)$ to get the maximum compatibility score sum.\n\nThe time complexity is $O(m!)$, and the space complexity is $O(m^2)$. Here, $m$ is the number of students and mentors." }, "is_english": true, "time_complexity": "O(m!)", "space_complexity": "O(m^2)" }, { "problem_id": 1948, "explanations": { "1": "We can use a trie to store the folder structure, where each node in the trie contains the following data:\n\n- `children`: A dictionary where the key is the name of the subfolder and the value is the corresponding child node.\n- `deleted`: A boolean value indicating whether the node is marked for deletion.\n\nWe insert all paths into the trie, then use DFS to traverse the trie and build a string representation for each subtree. For each subtree, if its string representation already exists in a global dictionary, we mark both the current node and the corresponding node in the global dictionary for deletion. Finally, we use DFS again to traverse the trie and add the paths of unmarked nodes to the result list." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1949, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1950, "explanations": { "1": "我们可以先利用单调栈,求出每个位置的左边第一个比它小的位置 $left[i]$ 和右边第一个比它小的位置 $right[i]$,那么以 $nums[i]$ 为最小值的子数组的长度为 $m = right[i] - left[i] - 1$。\n\n然后我们遍历数组,对于每个位置 $i$,更新 $ans[m - 1] = max(ans[m - 1], nums[i])$。\n\n接着我们倒序遍历数组,更新 $ans[i] = max(ans[i], ans[i + 1])$。\n\n最后返回 $ans$ 即可。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组长度。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1951, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1952, "explanations": { "1": "一个数 $n$ 一定有 $1$ 和 $n$ 两个正除数,因此只需要枚举 $2$ 到 $n-1$ 之间的数,看它们是否是 $n$ 的正除数即可,是则累加计数器,最后判断计数器是否为 $1$ 即可。\n\n时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为给定的整数。", "2": "我们可以枚举 $1$ 到 $\\sqrt{n}$ 之间的数 $i$,如果 $n$ 能被 $i$ 整除,并且 $\\frac{n}{i}$ 不等于 $i$,那么计数器累加 $2$,否则计数器累加 $1$。最后判断计数器是否为 $3$ 即可。\n\n时间复杂度 $O(\\sqrt{n})$,空间复杂度 $O(1)$。其中 $n$ 为给定的整数。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1953, "explanations": { "1": "We consider under what circumstances we cannot complete all stage tasks. If there is a project $i$ whose number of stage tasks is greater than the sum of the number of stage tasks of all other projects plus $1$, then we cannot complete all stage tasks. Otherwise, we can definitely complete all stage tasks by interlacing between different projects.\n\nWe denote the sum of the number of stage tasks of all projects as $s$, and the maximum number of stage tasks as $mx$, then the sum of the number of stage tasks of all other projects is $rest = s - mx$.\n\nIf $mx > rest + 1$, then we cannot complete all stage tasks, and at most we can complete $rest \\times 2 + 1$ stage tasks. Otherwise, we can complete all stage tasks, the number is $s$.\n\nThe time complexity is $O(n)$, where $n$ is the number of projects. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1954, "explanations": { "1": "假设正方形右上角坐标为 $(n, n)$,那么它的边长为 $2n$,周长为 $8n$,里面的苹果总数为:\n\n$$\n\\begin{aligned}\n&\\sum_{x=-n}^{n} \\sum_{y=-n}^{n} |x| + |y| \\\\\n\\end{aligned}\n$$\n\n由于 $x$ 和 $y$ 是对称的,所以可以化简为:\n\n$$\n\\begin{aligned}\n&\\sum_{x=-n}^{n} \\sum_{y=-n}^{n} |x| + |y| \\\\\n&= 2 \\sum_{x=-n}^{n} \\sum_{y=-n}^{n} |x| \\\\\n&= 2 \\sum_{x=-n}^{n} (2n + 1) |x| \\\\\n&= 2 (2n + 1) \\sum_{x=-n}^{n} |x| \\\\\n&= 2n(n+1)(2n+1)\n\\end{aligned}\n$$\n\n所以,我们只需要枚举 $n$,直到找到第一个满足 $2n(n+1)(2n+1) \\geq neededApples$ 的 $n$ 即可。\n\n时间复杂度 $O(m^{\\frac{1}{3}})$,其中 $m$ 为 $neededApples$ 的值。空间复杂度 $O(1)$。", "2": "我们也可以二分枚举 $n$,时间复杂度 $O(\\log m)$。" }, "is_english": false, "time_complexity": "O(m^{\\frac{1}{3}})", "space_complexity": "O(1)" }, { "problem_id": 1955, "explanations": { "1": "We define $f[i][j]$ to represent the number of special subsequences ending with $j$ among the first $i+1$ elements. Initially, $f[i][j]=0$, and if $nums[0]=0$, then $f[0][0]=1$.\n\nFor $i \\gt 0$, we consider the value of $nums[i]$:\n\nIf $nums[i] = 0$: If we do not choose $nums[i]$, then $f[i][0] = f[i-1][0]$; if we choose $nums[i]$, then $f[i][0]=f[i-1][0]+1$, because we can add a $0$ to the end of any special subsequence ending with $0$ to get a new special subsequence, or we can use $nums[i]$ alone as a special subsequence. Therefore, $f[i][0] = 2 \\times f[i - 1][0] + 1$. The rest of $f[i][j]$ is equal to $f[i-1][j]$.\n\nIf $nums[i] = 1$: If we do not choose $nums[i]$, then $f[i][1] = f[i-1][1]$; if we choose $nums[i]$, then $f[i][1]=f[i-1][1]+f[i-1][0]$, because we can add a $1$ to the end of any special subsequence ending with $0$ or $1$ to get a new special subsequence. Therefore, $f[i][1] = f[i-1][0] + 2 \\times f[i - 1][1]$. The rest of $f[i][j]$ is equal to $f[i-1][j]$.\n\nIf $nums[i] = 2$: If we do not choose $nums[i]$, then $f[i][2] = f[i-1][2]$; if we choose $nums[i]$, then $f[i][2]=f[i-1][2]+f[i-1][1]$, because we can add a $2$ to the end of any special subsequence ending with $1$ or $2$ to get a new special subsequence. Therefore, $f[i][2] = f[i-1][1] + 2 \\times f[i - 1][2]$. The rest of $f[i][j]$ is equal to $f[i-1][j]$.\n\nIn summary, we can get the following state transition equations:\n\n$$\n\\begin{aligned}\nf[i][0] &= 2 \\times f[i - 1][0] + 1, \\quad nums[i] = 0 \\\\\nf[i][1] &= f[i-1][0] + 2 \\times f[i - 1][1], \\quad nums[i] = 1 \\\\\nf[i][2] &= f[i-1][1] + 2 \\times f[i - 1][2], \\quad nums[i] = 2 \\\\\nf[i][j] &= f[i-1][j], \\quad nums[i] \\neq j\n\\end{aligned}\n$$\n\nThe final answer is $f[n-1][2]$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $nums$.\n\nSimilar code found with 1 license type", "2": "We notice that in the above state transition equations, the value of $f[i][j]$ is only related to $f[i-1][j]$. Therefore, we can remove the first dimension and optimize the space complexity to $O(1)$.\n\nWe can use an array $f$ of length 3 to represent the number of special subsequences ending with 0, 1, and 2, respectively. For each element in the array, we update the array $f$ according to the value of the current element.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$. Where $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1956, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1957, "explanations": { "1": "We can iterate through the string $s$ and use an array $\\textit{ans}$ to record the current answer. For each character $\\textit{s[i]}$, if $i < 2$ or $s[i]$ is not equal to $s[i - 1]$, or $s[i]$ is not equal to $s[i - 2]$, we add $s[i]$ to $\\textit{ans}$.\n\nFinally, we concatenate the characters in $\\textit{ans}$ to get the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. Ignoring the space consumption of the answer, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1958, "explanations": { "1": "We enumerate all possible directions. For each direction $(a, b)$, we start from $(\\textit{rMove}, \\textit{cMove})$ and use a variable $\\textit{cnt}$ to record the number of cells we have passed. If, during our traversal, we encounter a cell of color $\\textit{color}$ and $\\textit{cnt} > 1$, then we have found a good line segment and return $\\textit{true}$.\n\nIf no good line segments are found after the enumeration, we return $\\textit{false}$.\n\nThe time complexity is $O(m + n)$, where $m$ is the number of rows and $n$ is the number of columns in $\\textit{board}$, with $m = n = 8$ in this problem. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m + n)", "space_complexity": "O(1)" }, { "problem_id": 1959, "explanations": { "1": "The problem is equivalent to dividing the array $\\textit{nums}$ into $k + 1$ segments. The wasted space for each segment is the maximum value of that segment multiplied by the length of the segment minus the sum of the elements in that segment. By summing the wasted space of each segment, we get the total wasted space. By adding 1 to $k$, we are effectively dividing the array into $k$ segments.\n\nTherefore, we define an array $\\textit{g}[i][j]$ to represent the wasted space for the segment $\\textit{nums}[i..j]$, which is the maximum value of $\\textit{nums}[i..j]$ multiplied by the length of $\\textit{nums}[i..j]$ minus the sum of the elements in $\\textit{nums}[i..j]$. We iterate over $i$ in the range $[0, n)$ and $j$ in the range $[i, n)$, using a variable $s$ to maintain the sum of the elements in $\\textit{nums}[i..j]$ and a variable $\\textit{mx}$ to maintain the maximum value of $\\textit{nums}[i..j]$. Then we can get:\n\n$$ \\textit{g}[i][j] = \\textit{mx} \\times (j - i + 1) - s $$\n\nNext, we define $\\textit{f}[i][j]$ to represent the minimum wasted space for dividing the first $i$ elements into $j$ segments. We initialize $\\textit{f}[0][0] = 0$ and the other positions to infinity. We iterate over $i$ in the range $[1, n]$ and $j$ in the range $[1, k]$, then we iterate over the last element $h$ of the previous $j - 1$ segments. Then we have:\n\n$$ \\textit{f}[i][j] = \\min(\\textit{f}[i][j], \\textit{f}[h][j - 1] + \\textit{g}[h][i - 1]) $$\n\nThe final answer is $\\textit{f}[n][k]$.\n\nThe time complexity is $O(n^2 \\times k)$, and the space complexity is $O(n \\times (n + k))$. Where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n^2 \\times k)", "space_complexity": "O(n \\times (n + k))" }, { "problem_id": 1960, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1961, "explanations": { "1": "We traverse the array $words$, using a variable $t$ to record the currently concatenated string. If the length of $t$ is greater than the length of $s$, it means that $s$ is not a prefix string of $words$, so we return $false$; if the length of $t$ is equal to the length of $s$, we return whether $t$ is equal to $s$.\n\nAt the end of the traversal, if the length of $t$ is less than the length of $s$, it means that $s$ is not a prefix string of $words$, so we return $false$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1962, "explanations": { "1": "According to the problem description, in order to minimize the total number of remaining stones, we need to remove as many stones as possible from the stone piles. Therefore, we should always choose the pile with the most stones for removal.\n\nWe create a priority queue (max heap) $pq$ to store the number of stones in each pile. Initially, we add the number of stones in all piles to the priority queue.\n\nNext, we perform $k$ operations. In each operation, we take out the top element $x$ of the priority queue, halve $x$, and then add it back to the priority queue.\n\nAfter performing $k$ operations, the sum of all elements in the priority queue is the answer.\n\nThe time complexity is $O(n + k \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array `piles`." }, "is_english": true, "time_complexity": "O(n + k \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1963, "explanations": { "1": "We use a variable $x$ to record the current number of unmatched left brackets. We traverse the string $s$, for each character $c$:\n\n- If $c$ is a left bracket, then we increment $x$ by one;\n- If $c$ is a right bracket, then we need to check whether $x$ is greater than zero. If it is, we match the current right bracket with the nearest unmatched left bracket on the left, i.e., decrement $x$ by one.\n\nAfter the traversal, we will definitely get a string of the form `\"]]]...[[[...\"`. We then greedily swap the brackets at both ends each time, which can eliminate $2$ unmatched left brackets at a time. Therefore, the total number of swaps needed is $\\left\\lfloor \\frac{x + 1}{2} \\right\\rfloor$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1964, "explanations": { "1": "We can use a Binary Indexed Tree to maintain an array of the lengths of the longest increasing subsequences.\n\nThen for each obstacle, we query in the Binary Indexed Tree for the length of the longest increasing subsequence that is less than or equal to the current obstacle, suppose it is $l$. Then the length of the longest increasing subsequence of the current obstacle is $l+1$. We add $l+1$ to the answer array, and update $l+1$ in the Binary Indexed Tree.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the number of obstacles." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1965, "explanations": { "1": "We can first find all `employee_id` that are not in the `Salaries` table from the `Employees` table, and then find all `employee_id` that are not in the `Employees` table from the `Salaries` table. Finally, we can combine the two results using the `UNION` operator, and sort the result by `employee_id`." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1966, "explanations": { "1": "我们注意到,对于数组中的每个元素,如果它是可被二分搜索的,那么需要满足两个条件:\n\n1. 这个元素大于它的左边所有元素,否则,如果左边存在比当前元素大的元素,那么就会被移除,导致无法找到当前元素;\n2. 这个元素小于它的右边所有元素,否则,如果右边存在比当前元素小的元素,那么就会被移除,导致无法找到当前元素。\n\n我们创建一个数组 $ok$,其中 $ok[i]$ 表示 $nums[i]$ 是否是可被二分搜索的。初始时 $ok[i]$ 都为 $1$。\n\n我们先从左到右遍历数组,维护前缀最大值 $mx$,如果当前元素 $x$ 比 $mx$ 小,那么 $x$ 就不是可被二分搜索的,我们将 $ok[i]$ 置为 $0$,否则,我们将 $mx$ 更新为 $x$。\n\n然后我们从右到左遍历数组,维护后缀最小值 $mi$,如果当前元素 $x$ 比 $mi$ 大,那么 $x$ 就不是可被二分搜索的,我们将 $ok[i]$ 置为 $0$,否则,我们将 $mi$ 更新为 $x$。\n\n最后我们统计 $ok$ 中的 $1$ 的个数,即为可被二分搜索的元素的个数。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $nums$ 的长度。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1967, "explanations": { "1": "Traverse each string $p$ in the array $\\textit{patterns}$ and check if it is a substring of $\\textit{word}$. If it is, increment the answer by one.\n\nAfter traversing, return the answer.\n\nThe time complexity is $O(n \\times m)$, and the space complexity is $O(1)$. Here, $n$ and $m$ are the lengths of $\\textit{patterns}$ and $\\textit{word}$, respectively." }, "is_english": true, "time_complexity": "O(n \\times m)", "space_complexity": "O(1)" }, { "problem_id": 1968, "explanations": { "1": "Since the elements in the array are distinct, we can first sort the array, then divide the array into two parts. Place the first half of the elements in the even positions of the answer array, and the second half of the elements in the odd positions of the answer array. In this way, for each element, its two adjacent elements will not be equal to its average value.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 1969, "explanations": { "1": "We notice that each operation does not change the sum of the elements. When the sum of the elements remains unchanged, to minimize the product, we should maximize the difference between the elements as much as possible.\n\nSince the largest element is $2^p - 1$, no matter which element it exchanges with, it will not increase the difference. Therefore, we do not need to consider the case of exchanging with the largest element.\n\nFor the other elements in $[1,..2^p-2]$, we pair the first and last elements one by one, that is, pair $x$ with $2^p-1-x$. After several operations, each pair of elements becomes $(1, 2^p-2)$. The final product is $(2^p-1) \\times (2^p-2)^{2^{p-1}-1}$.\n\nThe time complexity is $O(p)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(p)", "space_complexity": "O(1)" }, { "problem_id": 1970, "explanations": { "1": "We note that if we can walk from the top row to the bottom row on day $k$, then for any $0 < k' < k$, we can also walk from the top row to the bottom row on day $k'$. This exhibits monotonicity, so we can use binary search to find the largest $k$ such that we can walk from the top row to the bottom row on day $k$.\n\nWe define the left boundary of the binary search as $l = 1$ and the right boundary as $r = |cells|$, where $|cells|$ represents the length of the array $\\textit{cells}$. Then, we perform binary search on $k$. For each $k$, we take the first $k$ elements of $\\textit{cells}$, turn the corresponding cells into water, and then use breadth-first search (BFS) to try to walk from the top row to the bottom row. If we can reach the bottom row, it means we can walk from the top row to the bottom row on day $k$, so we update the left boundary $l$ to $k$. Otherwise, we update the right boundary $r$ to $k - 1$.\n\nThe time complexity is $O(m \\times n \\times \\log (m \\times n))$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ represent the number of rows and columns of the matrix, respectively.", "2": "We can first initialize all land cells as $1$, then traverse the array $\\textit{cells}$ in reverse order, turning each corresponding land cell into $0$ and merging it with the adjacent land cells (up, down, left, right). We also need to maintain two virtual nodes $s$ and $t$, representing the virtual nodes for the top row and the bottom row, respectively. If $s$ and $t$ are connected in the union-find set, it means we can walk from the top row to the bottom row on day $i$.\n\nThe time complexity is $O(m \\times n \\times \\alpha(m \\times n))$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ represent the number of rows and columns of the matrix, respectively, and $\\alpha$ represents the inverse Ackermann function." }, "is_english": true, "time_complexity": "O(m \\times n \\times \\log (m \\times n))", "space_complexity": "O(m \\times n)" }, { "problem_id": 1971, "explanations": { "1": "We first convert $\\textit{edges}$ into an adjacency list $g$, then use DFS to determine whether there is a path from $\\textit{source}$ to $\\textit{destination}$.\n\nDuring the process, we use an array $\\textit{vis}$ to record the vertices that have already been visited to avoid revisiting them.\n\nThe time complexity is $O(n + m)$, and the space complexity is $O(n + m)$. Here, $n$ and $m$ are the number of nodes and edges, respectively.", "2": "We can also use BFS to determine whether there is a path from $\\textit{source}$ to $\\textit{destination}$.\n\nSpecifically, we define a queue $q$, initially adding $\\textit{source}$ to the queue. Additionally, we use a set $\\textit{vis}$ to record the vertices that have already been visited to avoid revisiting them.\n\nNext, we continuously take vertices $i$ from the queue. If $i = \\textit{destination}$, it means there is a path from $\\textit{source}$ to $\\textit{destination}$, and we return $\\textit{true}$. Otherwise, we traverse all adjacent vertices $j$ of $i$. If $j$ has not been visited, we add $j$ to the queue $q$ and mark $j$ as visited.\n\nFinally, if the queue is empty, it means there is no path from $\\textit{source}$ to $\\textit{destination}$, and we return $\\textit{false}$.\n\nThe time complexity is $O(n + m)$, and the space complexity is $O(n + m)$. Here, $n$ and $m$ are the number of nodes and edges, respectively.", "3": "Union-Find is a tree-like data structure that, as the name suggests, is used to handle some disjoint set **merge** and **query** problems. It supports two operations:\n\n1. Find: Determine which subset an element belongs to. The time complexity of a single operation is $O(\\alpha(n))$.\n2. Union: Merge two subsets into one set. The time complexity of a single operation is $O(\\alpha(n))$.\n\nFor this problem, we can use the Union-Find set to merge the edges in `edges`, and then determine whether `source` and `destination` are in the same set.\n\nThe time complexity is $O(n \\log n + m)$ or $O(n \\alpha(n) + m)$, and the space complexity is $O(n)$. Where $n$ and $m$ are the number of nodes and edges, respectively." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(n + m)" }, { "problem_id": 1972, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1973, "explanations": { "1": "我们设计一个函数 $dfs(root)$,该函数返回以 $root$ 为根节点的子树的所有节点值之和。函数 $dfs(root)$ 的执行过程如下:\n\n- 如果 $root$ 为空,返回 $0$;\n- 否则,我们递归地计算 $root$ 的左子树和右子树的节点值之和,记为 $l$ 和 $r$;如果 $l + r = root.val$,说明以 $root$ 为根节点的子树满足条件,我们将答案加 $1$;最后,返回 $root.val + l + r$。\n\n然后我们调用函数 $dfs(root)$,返回答案即可。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点数。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1974, "explanations": { "1": "We initialize the answer variable $\\textit{ans}$ to the length of the string, indicating that we need at least $\\textit{ans}$ seconds to type the string.\n\nNext, we traverse the string. For each character, we calculate the minimum distance between the current character and the previous character, and add this distance to the answer. Then we update the current character to the previous character and continue traversing.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1975, "explanations": { "1": "If there is a zero in the matrix, or the number of negative numbers in the matrix is even, then the maximum sum is the sum of the absolute values of all elements in the matrix.\n\nOtherwise, if there are an odd number of negative numbers in the matrix, there will be one negative number left in the end. We choose the number with the smallest absolute value and make it negative, so that the final sum is maximized.\n\nThe time complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns of the matrix, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(1)" }, { "problem_id": 1976, "explanations": { "1": "We define the following arrays:\n\n- `g` represents the adjacency matrix of the graph. `g[i][j]` represents the shortest path length from point `i` to point `j`. Initially, all are infinity, while `g[0][0]` is 0. Then we traverse `roads` and update `g[u][v]` and `g[v][u]` to `t`.\n- `dist[i]` represents the shortest path length from the starting point to point `i`. Initially, all are infinity, while `dist[0]` is 0.\n- `f[i]` represents the number of shortest paths from the starting point to point `i`. Initially, all are 0, while `f[0]` is 1.\n- `vis[i]` represents whether point `i` has been visited. Initially, all are `False`.\n\nThen, we use the naive Dijkstra algorithm to find the shortest path length from the starting point to the end point, and record the number of shortest paths for each point during the process.\n\nFinally, we return `f[n - 1]`. Since the answer may be very large, we need to take the modulus of $10^9 + 7$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$, where $n$ is the number of points." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 1977, "explanations": { "1": "Define $dp[i][j]$ to represent the number of ways to partition the first $i$ characters of the string `num` such that the length of the last number is $j$. Clearly, the answer is $\\sum_{j=0}^{n} dp[n][j]$. The initial value is $dp[0][0] = 1$.\n\nFor $dp[i][j]$, the end of the previous number should be $i-j$. We can enumerate $dp[i-j][k]$, where $k \\le j$. For the part where $k < j$, i.e., the number of ways with a length less than $j$ can be directly added to $dp[i][j]$, i.e., $dp[i][j] = \\sum_{k=0}^{j-1} dp[i-j][k]$. Because the previous number is shorter, it means it is smaller than the current number. Here, prefix sum can be used for optimization.\n\nHowever, when $k = j$, we need to compare the sizes of the two numbers of the same length. If the previous number is larger than the current number, this situation is invalid, and we should not add it to $dp[i][j]$. Otherwise, we can add it to $dp[i][j]$. Here, we can preprocess the \"longest common prefix\" in $O(n^2)$ time, and then compare the sizes of two numbers of the same length in $O(1)$ time.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Where $n$ is the length of the string `num`." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 1978, "explanations": { "1": "We can use a left join to connect the employee table with itself, and then filter out the employees whose salary is less than $30000$ and have a superior manager who has left the company.", "2": "We can also use a subquery to first find all the managers who have left the company, and then find the employees whose salary is less than $30000$ and whose superior manager is not in the list of managers who have left the company." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 1979, "explanations": { "1": "We can simulate according to the problem description. First, find the maximum and minimum values in the array $\\textit{nums}$, then find the greatest common divisor of the maximum and minimum values.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1980, "explanations": { "1": "Since the number of `'1'`s in a binary string of length $n$ can be $0, 1, 2, \\cdots, n$ (a total of $n + 1$ possibilities), we can always find a new binary string whose count of `'1'`s differs from every string in $\\textit{nums}$.\n\nWe use an integer $\\textit{mask}$ to record the counts of `'1'`s across all strings, where the $i$-th bit of $\\textit{mask}$ being $1$ indicates that a binary string of length $n$ with exactly $i$ occurrences of `'1'` exists in $\\textit{nums}$, and $0$ otherwise.\n\nWe then enumerate $i$ starting from $0$, representing the count of `'1'`s in a binary string of length $n$. If the $i$-th bit of $\\textit{mask}$ is $0$, it means no binary string of length $n$ with exactly $i$ occurrences of `'1'` exists, and we can return that string as the answer.\n\nThe time complexity is $O(L)$, where $L$ is the total length of all strings in $\\textit{nums}$. The space complexity is $O(1)$.", "2": "We can construct a binary string $\\textit{ans}$ of length $n$, where the $i$-th bit of $\\textit{ans}$ differs from the $i$-th bit of $\\textit{nums}[i]$. Since all strings in $\\textit{nums}$ are distinct, $\\textit{ans}$ will not appear in $\\textit{nums}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the strings in $\\textit{nums}$. Ignoring the space used by the answer string, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(L)", "space_complexity": "O(1)" }, { "problem_id": 1981, "explanations": { "1": "Let $f[i][j]$ represent whether it is possible to select elements from the first $i$ rows with a sum of $j$. Then we have the state transition equation:\n\n$$\nf[i][j] = \\begin{cases} 1 & \\textit{if there exists } x \\in row[i] \\textit{ such that } f[i - 1][j - x] = 1 \\\\ 0 & \\textit{otherwise} \\end{cases}\n$$\n\nwhere $row[i]$ represents the set of elements in the $i$-th row.\n\nSince $f[i][j]$ is only related to $f[i - 1][j]$, we can use a rolling array to optimize the space complexity.\n\nFinally, we traverse the $f$ array to find the smallest absolute difference.\n\nThe time complexity is $O(m^2 \\times n \\times C)$ and the space complexity is $O(m \\times C)$. Here, $m$ and $n$ are the number of rows and columns of the matrix, respectively, and $C$ is the maximum value of the matrix elements." }, "is_english": true, "time_complexity": "O(m^2 \\times n \\times C)", "space_complexity": "O(m \\times C)" }, { "problem_id": 1982, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1983, "explanations": { "1": "We observe that for any index pair $(i, j)$, if $nums1[i] + nums1[i+1] + ... + nums1[j] = nums2[i] + nums2[i+1] + ... + nums2[j]$, then $nums1[i] - nums2[i] + nums1[i+1] - nums2[i+1] + ... + nums1[j] - nums2[j] = 0$. If we subtract the corresponding elements of array $nums1$ and array $nums2$ to get a new array $nums$, the problem is transformed into finding the longest subarray in $nums$ such that the sum of the subarray is $0$. This can be solved using the prefix sum + hash table method.\n\nWe define a variable $s$ to represent the current prefix sum of $nums$, and use a hash table $d$ to store the first occurrence position of each prefix sum. Initially, $s = 0$ and $d[0] = -1$.\n\nNext, we traverse each element $x$ in the array $nums$, calculate the value of $s$, and then check whether $s$ exists in the hash table. If $s$ exists in the hash table, it means that there is a subarray $nums[d[s]+1,..i]$ such that the sum of the subarray is $0$, and we update the answer to $\\max(ans, i - d[s])$. Otherwise, we add the value of $s$ to the hash table, indicating that the first occurrence position of $s$ is $i$.\n\nAfter the traversal, we can get the final answer.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1984, "explanations": { "1": "We can sort the students' scores in ascending order, then use a sliding window of size $k$ to calculate the difference between the maximum and minimum values in the window, and finally take the minimum of the differences of all windows.\n\nWhy do we take the scores of $k$ consecutive students? Because if they are not consecutive, the difference between the maximum and minimum values may remain the same or increase, but it will definitely not decrease. Therefore, we only need to consider the scores of $k$ consecutive students after sorting.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the number of students." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 1985, "explanations": { "1": "We can sort the strings in the $\\textit{nums}$ array in descending order as integers, and then take the $k$-th element. Alternatively, we can use the quickselect algorithm to find the $k$-th largest integer.\n\nThe time complexity is $O(n \\times \\log n)$ or $O(n)$, where $n$ is the length of the $\\textit{nums}$ array. The space complexity is $O(\\log n)$ or $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 1986, "explanations": { "1": "We note that $n$ does not exceed $14$, so we can consider using state compression dynamic programming to solve this problem.\n\nWe use a binary number $i$ of length $n$ to represent the current task state, where the $j$-th bit of $i$ is $1$ if and only if the $j$-th task is completed. We use $f[i]$ to represent the minimum number of work sessions needed to complete all tasks with state $i$.\n\nWe can enumerate all subsets $j$ of $i$, where each bit of the binary representation of $j$ is a subset of the corresponding bit of the binary representation of $i$, i.e., $j \\subseteq i$. If the tasks corresponding to $j$ can be completed in one work session, then we can update $f[i]$ using $f[i \\oplus j] + 1$, where $i \\oplus j$ represents the bitwise XOR of $i$ and $j$.\n\nThe final answer is $f[2^n - 1]$.\n\nThe time complexity is $O(n \\times 3^n)$, and the space complexity is $O(2^n)$. Here, $n$ is the number of tasks." }, "is_english": true, "time_complexity": "O(n \\times 3^n)", "space_complexity": "O(2^n)" }, { "problem_id": 1987, "explanations": { "1": "We define $f$ as the number of distinct good subsequences ending with $1$, and $g$ as the number of distinct good subsequences ending with $0$ and starting with $1$. Initially, $f = g = 0$.\n\nFor a binary string, we can traverse each bit from left to right. Suppose the current bit is $c$:\n\n- If $c = 0$, we can append $c$ to the $f$ and $g$ distinct good subsequences, so update $g = (g + f) \\bmod (10^9 + 7)$;\n- If $c = 1$, we can append $c$ to the $f$ and $g$ distinct good subsequences, and also append $c$ alone, so update $f = (f + g + 1) \\bmod (10^9 + 7)$.\n\nIf the string contains $0$, the final answer is $f + g + 1$, otherwise the answer is $f + g$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(1)$.\n\nSimilar problems:\n\n- [940. Distinct Subsequences II](https://github.com/doocs/leetcode/blob/main/solution/0900-0999/0940.Distinct%20Subsequences%20II/README_EN.md)" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1988, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1989, "explanations": { "1": "We can use two pointers $i$ and $j$ to point to the ghost and non-ghost people, initially $i=0$, $j=0$.\n\nThen we traverse the array from left to right. When we encounter a ghost, i.e., $team[i]=1$, if $j \\lt n$ and $\\textit{team}[j]=1$ or $i - j \\gt \\textit{dist}$, then move pointer $j$ to the right in a loop. This means we need to find the first non-ghost person such that the distance between $i$ and $j$ does not exceed $\\textit{dist}$. If such a person is found, move pointer $j$ one step to the right, indicating that we have caught this person, and increment the answer by one. Continue traversing the array until the entire array is processed.\n\nFinally, return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{team}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1990, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1991, "explanations": { "1": "We define two variables $l$ and $r$, representing the sum of elements to the left and right of index $i$ in the array $\\textit{nums}$, respectively. Initially, $l = 0$ and $r = \\sum_{i = 0}^{n - 1} \\textit{nums}[i]$.\n\nWe traverse the array $\\textit{nums}$, and for the current number $x$, we update $r = r - x$. If $l = r$ at this point, it means the current index $i$ is the middle index, and we return it directly. Otherwise, we update $l = l + x$ and continue to the next number.\n\nIf the traversal ends without finding a middle index, return $-1$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$.\n\nSimilar problems:\n\n- [0724. Find Pivot Index](https://github.com/doocs/leetcode/blob/main/solution/0700-0799/0724.Find%20Pivot%20Index/README_EN.md)\n- [2574. Left and Right Sum Differences](https://github.com/doocs/leetcode/blob/main/solution/2500-2599/2574.Left%20and%20Right%20Sum%20Differences/README_EN.md)" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 1992, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1993, "explanations": { "1": "我们定义以下几个变量:\n\n- $locked$:记录每个节点的锁定状态,其中 $locked[i]$ 表示节点 $i$ 的锁定状态,如果节点 $i$ 未被上锁,则 $locked[i] = -1$,否则 $locked[i]$ 为锁定节点 $i$ 的用户编号。\n- $parent$:记录每个节点的父节点。\n- $children$:记录每个节点的子节点。\n\n调用 $lock$ 函数时,如果节点 $num$ 未被上锁,则将节点 $num$ 上锁,返回 `true`,否则返回 `false`。\n\n调用 $unlock$ 函数时,如果节点 $num$ 被上锁且上锁的用户编号为 $user$,则将节点 $num$ 解锁,返回 `true`,否则返回 `false`。\n\n调用 $upgrade$ 函数时,我们首先判断节点 $num$ 及其祖先节点是否被上锁,如果是,则返回 $false$。否则,我们判断节点 $num$ 的子孙节点是否有被上锁的,如果没有,则返回 `false`。否则,我们将节点 $num$ 及其子孙节点解锁,然后将节点 $num$ 上锁,返回 `true`。\n\n时间复杂度方面,初始化和 $upgrade$ 函数的时间复杂度均为 $O(n)$,而 $lock$ 和 $unlock$ 函数的时间复杂度均为 $O(1)$。空间复杂度 $O(n)$。其中 $n$ 是节点的数量。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1994, "explanations": { "1": "注意到题目中 $nums[i]$ 的范围为 $[1, 30]$,因此我们可以预处理出所有小于等于 $30$ 的质数,即 $[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]$。\n\n好子集中,所有元素的乘积可以表示为一个或多个互不相同的质数的乘积,也即是说,每个质因数最多只能出现一次。因此,我们可以使用一个二进制数来表示一个子集中的质因数,其中二进制数的第 $i$ 位表示质数 $primes[i]$ 是否出现在子集中。\n\n我们可以使用状态压缩动态规划的方法来求解本题。设 $f[i]$ 表示二进制数 $i$ 表示的子集中的质因数的乘积为一个或多个互不相同的质数的乘积的方案数。初始时 $f[0]=1$。\n\n我们在 $[2,..30]$ 的范围内枚举一个数 $x$,如果 $x$ 不在 $nums$ 中,或者 $x$ 为 $4, 9, 25$ 的倍数,那么我们可以直接跳过。否则,我们可以将 $x$ 的质因数用一个二进制数 $mask$ 表示,然后我们从大到小枚举当前的状态 $state$,如果 $state$ 与 $mask$ 按位与的结果为 $mask$,那么我们可以从状态 $f[state \\oplus mask]$ 转移到状态 $f[state]$,转移方程为 $f[state] = f[state] + cnt[x] \\times f[state \\oplus mask]$,其中 $cnt[x]$ 表示 $x$ 在 $nums$ 中出现的次数。\n\n注意,我们没有从数字 $1$ 开始枚举,因为我们可以选择任意个数字 $1$,加入到好子集中。那么最终的答案为 $\\sum_{i=1}{2^{10}-1} f[i] \\times 2^{cnt[1]}$。\n\n时间复杂度 $O(n + C \\times M)$,空间复杂度 $O(M)$。其中 $n$ 为 $nums$ 的长度;而 $C$ 和 $M$ 分别为题目中 $nums[i]$ 的范围和状态的个数,本题中 $C=30$, $M=2^{10}$。\n\n相似题目:\n\n- [2572. 无平方子集计数](https://github.com/doocs/leetcode/blob/main/solution/2500-2599/2572.Count%20the%20Number%20of%20Square-Free%20Subsets/README.md)" }, "is_english": false, "time_complexity": "O(n + C \\times M)", "space_complexity": "O(M)" }, { "problem_id": 1995, "explanations": { "1": "", "2": "", "3": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1996, "explanations": { "1": "We can sort all characters in descending order of attack power and ascending order of defense power.\n\nThen, traverse all characters. For the current character, if its defense power is less than the previous maximum defense power, it is a weak character, and we increment the answer by one. Otherwise, update the maximum defense power.\n\nAfter the traversal, we get the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the number of characters." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 1997, "explanations": { "1": "We define $f[i]$ as the date number of the first visit to the $i$-th room, so the answer is $f[n - 1]$.\n\nConsider the date number of the first arrival at the $(i-1)$-th room, denoted as $f[i-1]$. At this time, it takes one day to return to the $nextVisit[i-1]$-th room. Why return? Because the problem restricts $0 \\leq nextVisit[i] \\leq i$.\n\nAfter returning, the $nextVisit[i-1]$-th room is visited an odd number of times, and the rooms from $nextVisit[i-1]+1$ to $i-1$ are visited an even number of times. At this time, we go to the $(i-1)$-th room again from the $nextVisit[i-1]$-th room, which takes $f[i-1] - f[nextVisit[i-1]]$ days, and then it takes one more day to reach the $i$-th room. Therefore, $f[i] = f[i-1] + 1 + f[i-1] - f[nextVisit[i-1]] + 1$. Since $f[i]$ may be very large, we need to take the remainder of $10^9 + 7$, and to prevent negative numbers, we need to add $10^9 + 7$.\n\nFinally, return $f[n-1]$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of rooms." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 1998, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 1999, "explanations": { "1": "我们观察 $k$ 的范围,发现 $1 \\leq k \\leq 1000$,因此,如果 $digit1$ 和 $digit2$ 都为 $0$,那么一定不存在满足条件的整数,直接返回 $-1$ 即可。\n\n否则,我们不妨设 $digit1 \\leq digit2$,接下来我们可以使用 BFS 的方法,初始时将整数 $0$ 入队,然后不断地从队首取出一个整数 $x$,如果 $x \\gt 2^{31} - 1$,那么说明不存在满足条件的整数,直接返回 $-1$ 即可。如果 $x \\gt k$ 且 $x \\bmod k = 0$,那么说明找到了满足条件的整数,直接返回 $x$ 即可。否则,我们将其乘以 $10$ 后加上 $digit1$ 和 $digit2$,并将这两个整数入队,继续进行搜索。\n\n时间复杂度 $(\\log_{10} M)$,空间复杂度 $O(\\log_{10} M)$,其中 $M$ 为 $2^{31} - 1$。" }, "is_english": false, "time_complexity": "O(\\log_{10} M)", "space_complexity": "O(\\log_{10} M)" }, { "problem_id": 2000, "explanations": { "1": "First, we find the index $i$ where the character $ch$ first appears. Then, we reverse the characters from index $0$ to index $i$ (including index $i$). Finally, we concatenate the reversed string with the string starting from index $i + 1$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $word$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2001, "explanations": { "1": "In order to uniquely represent a rectangle, we need to simplify the width-to-height ratio of the rectangle to a simplest fraction. Therefore, we can find the greatest common divisor of the width-to-height ratio of each rectangle, and then simplify the width-to-height ratio to the simplest fraction. Next, we use a hash table to count the number of rectangles for each simplest fraction, and then calculate the combination of the number of rectangles for each simplest fraction to get the answer.\n\nThe time complexity is $O(n \\times \\log M)$, and the space complexity is $O(n)$. Here, $n$ and $M$ are the number of rectangles and the maximum side length of the rectangles, respectively." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(n)" }, { "problem_id": 2002, "explanations": { "1": "We notice that the length of the string $s$ does not exceed $12$, so we can use the method of binary enumeration to enumerate all subsequences of $s$. Suppose the length of $s$ is $n$, we can use $2^n$ binary numbers of length $n$ to represent all subsequences of $s$. For each binary number, the $i$-th bit being $1$ means the $i$-th character of $s$ is in the subsequence, and $0$ means it is not in the subsequence. For each binary number, we judge whether it is a palindrome subsequence and record it in the array $p$.\n\nNext, we enumerate each number $i$ in $p$. If $i$ is a palindrome subsequence, then we can enumerate a number $j$ from the complement of $i$, $mx = (2^n - 1) \\oplus i$. If $j$ is also a palindrome subsequence, then $i$ and $j$ are the two palindrome subsequences we are looking for. Their lengths are the number of $1$s in the binary representation of $i$ and $j$, denoted as $a$ and $b$, respectively. Then their product is $a \\times b$. We take the maximum of all possible $a \\times b$.\n\nThe time complexity is $(2^n \\times n + 3^n)$, and the space complexity is $O(2^n)$. Here, $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(2^n)", "space_complexity": "O(2^n)" }, { "problem_id": 2003, "explanations": { "1": "We notice that each node has a unique gene value, so we only need to find the node $idx$ with gene value $1$, and all nodes except for those on the path from node $idx$ to the root node $0$ have an answer of $1$.\n\nTherefore, we initialize the answer array $ans$ to $[1,1,...,1]$, and our focus is on finding the answer for each node on the path from node $idx$ to the root node $0$.\n\nWe can start from node $idx$ and use depth-first search to mark the gene values that appear in the subtree rooted at $idx$, and record them in the array $has$. During the search process, we use an array $vis$ to mark the visited nodes to prevent repeated visits.\n\nNext, we start from $i=2$ and keep looking for the first gene value that has not appeared, which is the answer for node $idx$. Here, $i$ is strictly increasing, because the gene values are unique, so we can always find a gene value that has not appeared in $[1,..n+1]$.\n\nThen, we update the answer for node $idx$, i.e., $ans[idx]=i$, and update $idx$ to its parent node to continue the above process until $idx=-1$, which means we have reached the root node $0$.\n\nFinally, we return the answer array $ans$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2004, "explanations": { "1": "相似题目:\n\n- [2010. 职员招聘人数 🔒 II](https://github.com/doocs/leetcode/blob/main/solution/2000-2099/2010.The%20Number%20of%20Seniors%20and%20Juniors%20to%20Join%20the%20Company%20II/README.md)" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2005, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2006, "explanations": { "1": "We notice that the length of the array $nums$ does not exceed $200$, so we can enumerate all pairs $(i, j)$, where $i < j$, and check if $|nums[i] - nums[j]|$ equals $k$. If it does, we increment the answer by one.\n\nFinally, we return the answer.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(1)$. Here, $n$ is the length of the array $nums$.", "2": "We can use a hash table or array to record the occurrence count of each number in the array $nums$. Then, we enumerate each number $x$ in the array $nums$, and check if $x + k$ and $x - k$ are in the array $nums$. If they are, we increment the answer by the sum of the occurrence counts of $x + k$ and $x - k$.\n\nFinally, we return the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(1)" }, { "problem_id": 2007, "explanations": { "1": "We notice that if the array `changed` is a double array, then the smallest element in the array `changed` must also be an element in the original array. Therefore, we can first sort the array `changed`, and then start from the first element to traverse the array `changed` in ascending order.\n\nWe use a hash table or array $cnt$ to count the occurrence of each element in the array `changed`. For each element $x$ in the array `changed`, we first check whether $x$ exists in $cnt$. If it does not exist, we skip this element. Otherwise, we subtract one from $cnt[x]$, and check whether $x \\times 2$ exists in $cnt$. If it does not exist, we return an empty array directly. Otherwise, we subtract one from $cnt[x \\times 2]$, and add $x$ to the answer array.\n\nAfter the traversal, we return the answer array.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$, where $n$ is the length of the array `changed`." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2008, "explanations": { "1": "First, we sort $rides$ in ascending order by $start$. Then we design a function $dfs(i)$, which represents the maximum tip that can be obtained from accepting orders starting from the $i$-th passenger. The answer is $dfs(0)$.\n\nThe calculation process of the function $dfs(i)$ is as follows:\n\nFor the $i$-th passenger, we can choose to accept or not to accept the order. If we don't accept the order, the maximum tip that can be obtained is $dfs(i + 1)$. If we accept the order, we can use binary search to find the first passenger encountered after the drop-off point of the $i$-th passenger, denoted as $j$. The maximum tip that can be obtained is $dfs(j) + end_i - start_i + tip_i$. Take the larger of the two. That is:\n\n$$\ndfs(i) = \\max(dfs(i + 1), dfs(j) + end_i - start_i + tip_i)\n$$\n\nWhere $j$ is the smallest index that satisfies $start_j \\ge end_i$, which can be obtained by binary search.\n\nIn this process, we can use memoization search to save the answer of each state to avoid repeated calculations.\n\nThe time complexity is $O(m \\times \\log m)$, and the space complexity is $O(m)$. Here, $m$ is the length of $rides$.", "2": "We can change the memoization search in Solution 1 to dynamic programming.\n\nFirst, sort $rides$, this time we sort by $end$ in ascending order. Then define $f[i]$, which represents the maximum tip that can be obtained from the first $i$ passengers. Initially, $f[0] = 0$, and the answer is $f[m]$.\n\nFor the $i$-th passenger, we can choose to accept or not to accept the order. If we don't accept the order, the maximum tip that can be obtained is $f[i-1]$. If we accept the order, we can use binary search to find the last passenger whose drop-off point is not greater than $start_i$ before the $i$-th passenger gets on the car, denoted as $j$. The maximum tip that can be obtained is $f[j] + end_i - start_i + tip_i$. Take the larger of the two. That is:\n\n$$\nf[i] = \\max(f[i - 1], f[j] + end_i - start_i + tip_i)\n$$\n\nWhere $j$ is the largest index that satisfies $end_j \\le start_i$, which can be obtained by binary search.\n\nThe time complexity is $O(m \\times \\log m)$, and the space complexity is $O(m)$. Here, $m$ is the length of $rides$.\n\nSimilar problems:\n\n- [1235. Maximum Profit in Job Scheduling](https://github.com/doocs/leetcode/blob/main/solution/1200-1299/1235.Maximum%20Profit%20in%20Job%20Scheduling/README_EN.md)\n- [1751. Maximum Number of Events That Can Be Attended II](https://github.com/doocs/leetcode/blob/main/solution/1700-1799/1751.Maximum%20Number%20of%20Events%20That%20Can%20Be%20Attended%20II/README_EN.md)" }, "is_english": true, "time_complexity": "O(m \\times \\log m)", "space_complexity": "O(m)" }, { "problem_id": 2009, "explanations": { "1": "First, we sort the array and remove duplicates.\n\nThen, we traverse the array, enumerating the current element $nums[i]$ as the minimum value of the consecutive array. We use binary search to find the first position $j$ that is greater than $nums[i] + n - 1$. Then, $j-i$ is the length of the consecutive array when the current element is the minimum value. We update the answer, i.e., $ans = \\min(ans, n - (j - i))$.\n\nFinally, we return $ans$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array.", "2": "Similar to Solution 1, we first sort the array and remove duplicates.\n\nThen, we traverse the array, enumerating the current element $nums[i]$ as the minimum value of the consecutive array. We use two pointers to find the first position $j$ that is greater than $nums[i] + n - 1$. Then, $j-i$ is the length of the consecutive array when the current element is the minimum value. We update the answer, i.e., $ans = \\min(ans, n - (j - i))$.\n\nFinally, we return $ans$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 2010, "explanations": { "1": "相似题目:\n\n- [2004. 职员招聘人数](https://github.com/doocs/leetcode/blob/main/solution/2000-2099/2004.The%20Number%20of%20Seniors%20and%20Juniors%20to%20Join%20the%20Company/README.md)" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2011, "explanations": { "1": "We traverse the array $\\textit{operations}$. For each operation $\\textit{operations}[i]$, if it contains `'+'`, we increment the answer by $1$, otherwise, we decrement the answer by $1$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{operations}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2012, "explanations": { "1": "We can preprocess the right minimum array $right$, where $right[i]$ represents the minimum value in $nums[i..n-1]$.\n\nThen we traverse the array $nums$ from left to right, while maintaining the maximum value $l$ on the left. For each position $i$, we judge whether $l < nums[i] < right[i + 1]$ holds. If it does, we add $2$ to the answer. Otherwise, we judge whether $nums[i - 1] < nums[i] < nums[i + 1]$ holds. If it does, we add $1$ to the answer.\n\nAfter the traversal, we can get the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2013, "explanations": { "1": "We can use a hash table $cnt$ to maintain all the information of the points, where $cnt[x][y]$ represents the count of point $(x, y)$.\n\nWhen calling the $add(x, y)$ method, we increase the value of $cnt[x][y]$ by $1$.\n\nWhen calling the $count(x_1, y_1)$ method, we need to get three other points to form an axis-aligned square. We can enumerate the point $(x_2, y_1)$ that is parallel to the $x$-axis and at a distance $d$ from $(x_1, y_1)$. If such a point exists, based on these two points, we can determine the other two points as $(x_1, y_1 + d)$ and $(x_2, y_1 + d)$, or $(x_1, y_1 - d)$ and $(x_2, y_1 - d)$. We can add up the number of schemes for these two situations.\n\nIn terms of time complexity, the time complexity of calling the $add(x, y)$ method is $O(1)$, and the time complexity of calling the $count(x_1, y_1)$ method is $O(n)$; the space complexity is $O(n)$. Here, $n$ is the number of points in the data stream." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(n)" }, { "problem_id": 2014, "explanations": { "1": "We can first count the occurrences of each character in the string, and then store the characters that appear at least $k$ times in a list $\\textit{cs}$ in ascending order. Next, we can use BFS to enumerate all possible subsequences.\n\nWe define a queue $\\textit{q}$, initially putting the empty string into the queue. Then, we take out a string $\\textit{cur}$ from the queue and try to append each character $c \\in \\textit{cs}$ to the end of $\\textit{cur}$ to form a new string $\\textit{nxt}$. If $\\textit{nxt}$ is a subsequence that can be repeated $k$ times, we add it to the answer and put $\\textit{nxt}$ back into the queue for further processing.\n\nWe need an auxiliary function $\\textit{check(t, k)}$ to determine whether the string $\\textit{t}$ is a repeated $k$ times subsequence of string $s$. Specifically, we can use two pointers to traverse $s$ and $\\textit{t}$. If we can find all characters of $\\textit{t}$ in $s$ and repeat this process $k$ times, then return $\\textit{true}$; otherwise, return $\\textit{false}$." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 2015, "explanations": { "1": "We can use the difference array concept, utilizing a hash table $\\textit{cnt}$ to record the change in the number of buildings at each position, and another hash table $\\textit{d}$ to record the change in height at each position.\n\nNext, we sort the hash table $\\textit{d}$ by its keys, use a variable $\\textit{s}$ to record the current total height, and a variable $\\textit{m}$ to record the current number of buildings.\n\nThen, we traverse the hash table $\\textit{d}$. For each position, if $\\textit{m}$ is not 0, it means there are buildings at the previous positions. We calculate the average height. If the average height of the buildings at the current position is the same as that of the previous buildings, we merge them; otherwise, we add the current position to the result set.\n\nFinally, we return the result set.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the number of buildings." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2016, "explanations": { "1": "We use a variable $\\textit{mi}$ to represent the minimum value among the elements currently being traversed, and a variable $\\textit{ans}$ to represent the maximum difference. Initially, $\\textit{mi}$ is set to $+\\infty$, and $\\textit{ans}$ is set to $-1$.\n\nTraverse the array. For the current element $x$, if $x \\gt \\textit{mi}$, update $\\textit{ans}$ to $\\max(\\textit{ans}, x - \\textit{mi})$. Otherwise, update $\\textit{mi}$ to $x$.\n\nAfter the traversal, return $\\textit{ans}$.\n\nTime complexity is $O(n)$, where $n$ is the length of the array. Space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2017, "explanations": { "1": "We notice that if we determine the position $j$ where the first robot turns down, then the optimal path of the second robot is also determined. The optimal path of the second robot is the prefix sum of the first row from $j+1$ to $n-1$, or the prefix sum of the second row from $0$ to $j-1$, taking the maximum of the two.\n\nFirst, we calculate the suffix sum of the points in the first row, denoted as $s_1$, and the prefix sum of the points in the second row, denoted as $s_2$. Initially, $s_1 = \\sum_{j=0}^{n-1} grid[0][j]$, $s_2 = 0$.\n\nThen we enumerate the position $j$ where the first robot turns down. At this time, we update $s_1 = s_1 - grid[0][j]$. Then the sum of the optimal path of the second robot is $max(s_1, s_2)$. We take the minimum of $max(s_1, s_2)$ for all $j$. Then we update $s_2 = s_2 + grid[1][j]$.\n\nAfter the enumeration, we return the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the number of columns in the grid." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2018, "explanations": { "1": "We can enumerate each position $(i, j)$ in the matrix, and judge whether we can place the word `word` from left to right or from right to left, or from top to bottom or from bottom to top, starting from this position.\n\nThe following conditions must be met for this position to be used as a starting point:\n\n1. If the word `word` is to be placed from left to right, then this position must be the left boundary, or the cell `board[i][j - 1]` to the left of this position is `'#'`.\n2. If the word `word` is to be placed from right to left, then this position must be the right boundary, or the cell `board[i][j + 1]` to the right of this position is `'#'`.\n3. If the word `word` is to be placed from top to bottom, then this position must be the upper boundary, or the cell `board[i - 1][j]` above this position is `'#'`.\n4. If the word `word` is to be placed from bottom to top, then this position must be the lower boundary, or the cell `board[i + 1][j]` below this position is `'#'`.\n\nUnder the above conditions, we can start from this position and judge whether the word `word` can be placed. We design a function $check(i, j, a, b)$, which represents whether it is legal to place the word `word` from the position $(i, j)$ in the direction $(a, b)$. If it is legal, return `true`, otherwise return `false`.\n\nThe implementation of the function $check(i, j, a, b)$ is as follows:\n\nWe first get the other boundary position $(x, y)$ in the current direction, i.e., $(x, y) = (i + a \\times k, j + b \\times k)$, where $k$ is the length of the word `word`. If $(x, y)$ is in the matrix and the cell at $(x, y)$ is not `'#'`, it means that the other boundary position in the current direction is not `'#'`, so the word `word` cannot be placed, and `false` is returned.\n\nOtherwise, we start from the position $(i, j)$ and traverse the word `word` in the direction $(a, b)$. If we encounter a cell `board[i][j]` that is not a space or not the current character of the word `word`, it means that the word `word` cannot be placed, and `false` is returned. If the word `word` is traversed, it means that the word `word` can be placed, and `true` is returned.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(1)$. Here, $m$ and $n$ are the number of rows and columns in the matrix, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(1)" }, { "problem_id": 2019, "explanations": { "1": "First, we design a function $cal(s)$ to calculate the result of a valid mathematical expression that only contains single-digit numbers. The correct answer is $x = cal(s)$.\n\nLet the length of the string $s$ be $n$, then the number of digits in $s$ is $m = \\frac{n+1}{2}$.\n\nWe define $f[i][j]$ as the possible values of the result calculated by selecting the digits from the $i$-th to the $j$-th in $s$ (index starts from $0$). Initially, $f[i][i]$ represents the selection of the $i$-th digit, and the result can only be this digit itself, i.e., $f[i][i] = \\{s[i \\times 2]\\}$ (the $i$-th digit maps to the character at index $i \\times 2$ in the string $s$).\n\nNext, we enumerate $i$ from large to small, and then enumerate $j$ from small to large. We need to find out the possible values of the results of the operation of all digits in the interval $[i, j]$. We enumerate the boundary point $k$ in the interval $[i, j]$, then $f[i][j]$ can be obtained from $f[i][k]$ and $f[k+1][j]$ through the operator $s[k \\times 2 + 1]$. Therefore, we can get the following state transition equation:\n\n$$\nf[i][j] = \\begin{cases}\n\\{s[i \\times 2]\\}, & i = j \\\\\n\\bigcup\\limits_{k=i}^{j-1} \\{f[i][k] \\otimes f[k+1][j]\\}, & i < j\n\\end{cases}\n$$\n\nWhere $\\otimes$ represents the operator, i.e., $s[k \\times 2 + 1]$.\n\nThe possible values of the results of all digit operations in the string $s$ are $f[0][m-1]$.\n\nFinally, we count the answer. We use an array $cnt$ to count the number of times each answer appears in the answer array $answers$. If the answer is equal to $x$, then this student gets $5$ points, otherwise if the answer is in $f[0][m-1]$, then this student gets $2$ points. Traverse $cnt$ to count the answer.\n\nThe time complexity is $O(n^3 \\times M^2)$, and the space complexity is $O(n^2 \\times M^2)$. Here, $M$ is the maximum possible value of the answer, and $n$ is the number of digits in the length of the string $s$." }, "is_english": true, "time_complexity": "O(n^3 \\times M^2)", "space_complexity": "O(n^2 \\times M^2)" }, { "problem_id": 2020, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2021, "explanations": { "1": "We can consider the range illuminated by each street light as an interval, with the left endpoint $l = position_i - range_i$ and the right endpoint $r = position_i + range_i$. We can use the idea of a difference array. For each interval $[l, r]$, we add $1$ to the value at position $l$ and subtract $1$ from the value at position $r + 1$. We use a hash table to maintain the change value at each position.\n\nThen we traverse each position in ascending order, calculate the brightness $s$ at the current position. If the previous maximum brightness $mx < s$, then update the maximum brightness $mx = s$ and record the current position $ans = i$.\n\nFinally, return $ans$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of `lights`." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2022, "explanations": { "1": "According to the problem description, we know that to construct an $m$-row and $n$-column two-dimensional array, it needs to satisfy that $m \\times n$ equals the length of the original array. If it does not satisfy, return an empty array directly.\n\nIf it does satisfy, we can follow the process described in the problem, and put the elements from the original array into the two-dimensional array in order.\n\nThe time complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns of the two-dimensional array, respectively. Ignoring the space consumption of the answer, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(1)" }, { "problem_id": 2023, "explanations": { "1": "Traverse the array `nums`, for each $i$, enumerate all $j$, if $i \\neq j$ and $nums[i] + nums[j] = target$, then increment the answer by one.\n\nThe time complexity is $O(n^2 \\times m)$, where $n$ and $m$ are the lengths of the array `nums` and the string `target`, respectively. The space complexity is $O(1)$.", "2": "We can use a hash table to count the occurrence of each string in the array `nums`, then traverse all prefixes and suffixes of the string `target`. If both the prefix and suffix are in the hash table, then increment the answer by the product of their occurrences.\n\nThe time complexity is $O(n + m^2)$, and the space complexity is $O(n)$. Here, $n$ and $m$ are the lengths of the array `nums` and the string `target`, respectively." }, "is_english": true, "time_complexity": "O(n^2 \\times m)", "space_complexity": "O(1)" }, { "problem_id": 2024, "explanations": { "1": "We design a function $\\textit{f}(c)$, which represents the longest length of consecutive characters under the condition that at most $k$ characters $c$ can be replaced, where $c$ can be 'T' or 'F'. The answer is $\\max(\\textit{f}('T'), \\textit{f}('F'))$.\n\nWe iterate through the string $\\textit{answerKey}$, using a variable $\\textit{cnt}$ to record the number of characters $c$ within the current window. When $\\textit{cnt} > k$, we move the left pointer of the window one position to the right. After the iteration ends, the length of the window is the maximum length of consecutive characters.\n\nTime complexity is $O(n)$, where $n$ is the length of the string. Space complexity is $O(1)$.\n\nSimilar problems:\n\n- [487. Max Consecutive Ones II](https://github.com/doocs/leetcode/blob/main/solution/0400-0499/0487.Max%20Consecutive%20Ones%20II/README_EN.md)\n- [1004. Max Consecutive Ones III](https://github.com/doocs/leetcode/blob/main/solution/1000-1099/1004.Max%20Consecutive%20Ones%20III/README_EN.md)" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2025, "explanations": { "1": "We can preprocess to get the prefix sum array $s$ corresponding to the array $nums$, where $s[i]$ represents the sum of the array $nums[0,...i-1]$. Therefore, the sum of all elements in the array is $s[n - 1]$.\n\nIf we do not modify the array $nums$, the condition for the sums of the two subarrays to be equal is that $s[n - 1]$ must be even. If $s[n - 1]$ is even, then we calculate $ans = \\frac{right[s[n - 1] / 2]}{2}$.\n\nIf we modify the array $nums$, we can enumerate each modification position $i$, change $nums[i]$ to $k$, then the change in the total sum of the array is $d = k - nums[i]$. At this time, the sum of the left part of $i$ remains unchanged, so the legal split must satisfy $s[i] = s[n - 1] + d - s[i]$, that is, $s[i] = \\frac{s[n - 1] + d}{2}$. Each prefix sum of the right part has increased by $d$, so the legal split must satisfy $s[i] + d = s[n - 1] + d - (s[i] + d)$, that is, $s[i] = \\frac{s[n - 1] - d}{2}$. We use hash tables $left$ and $right$ to record the number of times each prefix sum appears in the left and right parts, respectively. Then we can calculate $ans = max(ans, left[\\frac{s[n - 1] + d}{2}]) + right[\\frac{s[n - 1] - d}{2}]$.\n\nFinally, we return $ans$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2026, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2027, "explanations": { "1": "Traverse the string $s$. Whenever you encounter `'X'`, move the pointer $i$ three steps forward and add $1$ to the answer; otherwise, move the pointer $i$ one step forward.\n\nThe time complexity is $O(n)$, where $n$ represents the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": null }, { "problem_id": 2028, "explanations": { "1": "According to the problem description, the sum of all numbers is $(n + m) \\times \\textit{mean}$, and the sum of known numbers is $\\sum_{i=0}^{m-1} \\textit{rolls}[i]$. Therefore, the sum of the missing numbers is $s = (n + m) \\times \\textit{mean} - \\sum_{i=0}^{m-1} \\textit{rolls}[i]$.\n\nIf $s \\gt n \\times 6$ or $s \\lt n$, it means there is no answer that satisfies the conditions, so we return an empty array.\n\nOtherwise, we can evenly distribute $s$ to $n$ numbers, that is, the value of each number is $s / n$, and the value of $s \\bmod n$ numbers is increased by $1$.\n\nThe time complexity is $O(n + m)$, where $n$ and $m$ are the number of missing numbers and known numbers, respectively. Ignoring the space consumption of the answer, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(1)" }, { "problem_id": 2029, "explanations": { "1": "Since the player's goal is to ensure the total value of the removed stones is not divisible by $3$, we only need to consider the remainder of each stone's value when divided by $3$.\n\nWe use an array $\\textit{cnt}$ of length $3$ to maintain the count of the current remaining stones' values modulo $3$, where $\\textit{cnt}[0]$ represents the count of stones with a remainder of $0$, and $\\textit{cnt}[1]$ and $\\textit{cnt}[2]$ respectively represent the counts of stones with remainders of $1$ and $2$.\n\nIn the first round, Alice cannot remove stones with a remainder of $0$, as this would make the total value of the removed stones divisible by $3$. Therefore, Alice can only remove stones with a remainder of $1$ or $2$.\n\nFirst, let's consider the case where Alice removes a stone with a remainder of $1$. If Alice removes a stone with a remainder of $1$, the remainder of the total value of stones $0$ against $3$ will not change, so stones with a value remainder of $0$ can be removed in any round, which we will not consider for now. Thus, Bob can only remove stones with a remainder of $1$, followed by Alice removing stones with a remainder of $2$, and so on, in the sequence $1, 1, 2, 1, 2, \\ldots$. In this scenario, if the final round is odd and there are still remaining stones, then Alice wins; otherwise, Bob wins.\n\nFor the case where Alice removes a stone with a remainder of $2$ in the first round, we can draw a similar conclusion.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{stones}$. The space complexity is $O(1)$.", "2": "" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2030, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2031, "explanations": { "1": "The problem requires us to count the number of subarrays where the count of $1$ is greater than the count of $0$. If we treat $0$ in the array as $-1$, then the problem becomes counting the number of subarrays where the sum of elements is greater than $0$.\n\nTo calculate the sum of elements in a subarray, we can use the prefix sum. To count the number of subarrays where the sum of elements is greater than $0$, we can use a binary indexed tree to maintain the occurrence count of each prefix sum. Initially, the occurrence count of the prefix sum $0$ is $1$.\n\nNext, we traverse the array $nums$, use variable $s$ to record the current prefix sum, and use variable $ans$ to record the answer. For each position $i$, we update the prefix sum $s$, then query the occurrence count of the prefix sum in the range $[0, s)$ in the binary indexed tree, add it to $ans$, and then update the occurrence count of $s$ in the binary indexed tree.\n\nFinally, return $ans$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $nums$.", "2": "" }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2032, "explanations": { "1": "We can first put each element of the arrays into an array, then enumerate each number $i$ from $1$ to $100$, and check whether $i$ appears in at least two arrays. If so, add $i$ to the answer array.\n\nThe time complexity is $O(n_1 + n_2 + n_3)$, and the space complexity is $O(n_1 + n_2 + n_3)$. Here, $n_1, n_2, n_3$ are the lengths of the arrays `nums1`, `nums2`, and `nums3`, respectively." }, "is_english": true, "time_complexity": "O(n_1 + n_2 + n_3)", "space_complexity": "O(n_1 + n_2 + n_3)" }, { "problem_id": 2033, "explanations": { "1": "Firstly, to make the grid a single-value grid, the remainder of all elements of the grid with $x$ must be the same.\n\nTherefore, we can first traverse the grid to check whether the remainder of all elements with $x$ is the same. If not, return $-1$. Otherwise, we put all elements into an array, sort the array, take the median, then traverse the array, calculate the difference between each element and the median, divide it by $x$, and add all the differences to get the answer.\n\nThe time complexity is $O((m \\times n) \\times \\log (m \\times n))$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the number of rows and columns of the grid, respectively." }, "is_english": true, "time_complexity": "O((m \\times n) \\times \\log (m \\times n))", "space_complexity": "O(m \\times n)" }, { "problem_id": 2034, "explanations": { "1": "We define the following data structures or variables:\n\n- `d`: a hash table that stores the timestamp and the corresponding price;\n- `ls`: an ordered set that stores all prices;\n- `last`: the timestamp of the last update.\n\nThen, we can perform the following operations:\n\n- `update(timestamp, price)`: update the price corresponding to the timestamp `timestamp` to `price`. If `timestamp` already exists, we need to first remove its corresponding price from the ordered set, and then update it to `price`. Otherwise, we directly update it to `price`. Then, we need to update `last` to `max(last, timestamp)`. The time complexity is O(log n).\n- `current()`: return the price corresponding to `last`. The time complexity is $O(1)$.\n- `maximum()`: return the maximum value in the ordered set. The time complexity is $O(\\log n)$.\n- `minimum()`: return the minimum value in the ordered set. The time complexity is $O(\\log n)$.\n\nThe space complexity is $O(n)$, where $n$ is the number of `update` operations." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(n)" }, { "problem_id": 2035, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2036, "explanations": { "1": "We define $f$ as the maximum sum of the alternating subarray ending with $nums[i]$, and define $g$ as the maximum sum of the alternating subarray ending with $-nums[i]$. Initially, both $f$ and $g$ are $-\\infty$.\n\nNext, we traverse the array $nums$. For position $i$, we need to maintain the values of $f$ and $g$, i.e., $f = \\max(g, 0) + nums[i]$, and $g = f - nums[i]$. The answer is the maximum value among all $f$ and $g$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2037, "explanations": { "1": "Sort both arrays, then traverse the two arrays, calculate the distance between each student's seat and their actual seat, and add all the distances to get the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the arrays `seats` and `students`." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 2038, "explanations": { "1": "We count the number of times that the string `colors` contains three consecutive `'A'`s or three consecutive `'B'`s, denoted as $a$ and $b$, respectively.\n\nFinally, we check whether $a$ is greater than $b$. If it is, we return `true`. Otherwise, we return `false`.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string `colors`. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2039, "explanations": { "1": "First, we construct an undirected graph $g$ based on the 2D array $edges$, where $g[u]$ represents all neighboring nodes of node $u$.\n\nThen, we can use breadth-first search (BFS) to find the shortest distance $d_i$ from each node $i$ to the main server. The earliest time that node $i$ can receive a reply after sending a message is $2 \\times d_i$. Since each data server $i$ resends a message every $patience[i]$ seconds, the last time that each data server sends a message is $(2 \\times d_i - 1) / patience[i] \\times patience[i]$. Therefore, the latest time that the network becomes idle is $(2 \\times d_i - 1) / patience[i] \\times patience[i] + 2 \\times d_i$, plus 1 second for processing time. We find the latest of these times, which is the earliest time that the computer network becomes idle.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2040, "explanations": { "1": "We can use binary search to enumerate the value of the product $p$, defining the binary search interval as $[l, r]$, where $l = -\\textit{max}(|\\textit{nums1}[0]|, |\\textit{nums1}[n - 1]|) \\times \\textit{max}(|\\textit{nums2}[0]|, |\\textit{nums2}[n - 1]|)$, $r = -l$.\n\nFor each $p$, we calculate the number of products less than or equal to $p$. If this number is greater than or equal to $k$, it means the $k$-th smallest product must be less than or equal to $p$, so we can reduce the right endpoint of the interval to $p$. Otherwise, we increase the left endpoint of the interval to $p + 1$.\n\nThe key to the problem is how to calculate the number of products less than or equal to $p$. We can enumerate each number $x$ in $\\textit{nums1}$ and discuss in cases:\n\n- If $x > 0$, then $x \\times \\textit{nums2}[i]$ is monotonically increasing as $i$ increases. We can use binary search to find the smallest $i$ such that $x \\times \\textit{nums2}[i] > p$. Then, $i$ is the number of products less than or equal to $p$, which is accumulated into the count $\\textit{cnt}$;\n- If $x < 0$, then $x \\times \\textit{nums2}[i]$ is monotonically decreasing as $i$ increases. We can use binary search to find the smallest $i$ such that $x \\times \\textit{nums2}[i] \\leq p$. Then, $n - i$ is the number of products less than or equal to $p$, which is accumulated into the count $\\textit{cnt}$;\n- If $x = 0$, then $x \\times \\textit{nums2}[i] = 0$. If $p \\geq 0$, then $n$ is the number of products less than or equal to $p$, which is accumulated into the count $\\textit{cnt}$.\n\nThis way, we can find the $k$-th smallest product through binary search.\n\nThe time complexity is $O(m \\times \\log n \\times \\log M)$, where $m$ and $n$ are the lengths of $\\textit{nums1}$ and $\\textit{nums2}$, respectively, and $M$ is the maximum absolute value in $\\textit{nums1}$ and $\\textit{nums2}$." }, "is_english": true, "time_complexity": "O(m \\times \\log n \\times \\log M)", "space_complexity": null }, { "problem_id": 2041, "explanations": { "1": "We can join the `Candidates` table and the `Rounds` table based on `interview_id`, filter out candidates with at least 2 years of work experience, then group by `candidate_id` to calculate the total score for each candidate, and finally filter out candidates with a total score greater than 15." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 2042, "explanations": { "1": "We can split the string $s$ into several words by spaces. Then, for each word, check if it is a number. If it is a number, convert it to an integer, compare it with the previous number. If it is not strictly increasing, return `false`. Otherwise, assign the current number to the previous number and continue the traversal.\n\nIf the traversal ends, it means that the numbers in the string are strictly increasing, so return `true`.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2043, "explanations": { "1": "We can use an array $\\textit{balance}$ to store the balance of each account. For each operation, we simply perform the required checks and updates according to the problem statement.\n\nFor the $\\textit{transfer}$ operation, we need to check whether the account numbers are valid and whether the balance is sufficient. If the conditions are met, we perform the transfer.\n\nFor the $\\textit{deposit}$ operation, we only need to check whether the account number is valid, and then perform the deposit.\n\nFor the $\\textit{withdraw}$ operation, we need to check whether the account number is valid and whether the balance is sufficient. If the conditions are met, we perform the withdrawal.\n\nEach operation has a time complexity of $O(1)$, so the overall time complexity is $O(q)$, where $q$ is the number of operations. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 2044, "explanations": { "1": "The maximum bitwise OR value $\\textit{mx}$ in the array $\\textit{nums}$ can be obtained by performing bitwise OR on all elements in the array.\n\nThen we can use depth-first search to enumerate all subsets and count the number of subsets whose bitwise OR equals $\\textit{mx}$. We design a function $\\text{dfs(i, t)}$, which represents the number of subsets starting from index $\\textit{i}$ with the current bitwise OR value being $\\textit{t}$. Initially, $\\textit{i} = 0$ and $\\textit{t} = 0$.\n\nIn the function $\\text{dfs(i, t)}$, if $\\textit{i}$ equals the array length, it means we have enumerated all elements. At this point, if $\\textit{t}$ equals $\\textit{mx}$, we increment the answer by one. Otherwise, we can choose to either exclude the current element $\\textit{nums[i]}$ or include the current element $\\textit{nums[i]}$, so we can recursively call $\\text{dfs(i + 1, t)}$ and $\\text{dfs(i + 1, t | nums[i])}$.\n\nFinally, we return the answer.\n\nThe time complexity is $O(2^n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$.", "2": "We can use binary enumeration to count the bitwise OR results of all subsets. For an array $\\textit{nums}$ of length $n$, we can use an integer $\\textit{mask}$ to represent a subset, where the $i$-th bit of $\\textit{mask}$ being 1 means including element $\\textit{nums[i]}$, and 0 means not including it.\n\nWe can iterate through all possible $\\textit{mask}$ values from $0$ to $2^n - 1$. For each $\\textit{mask}$, we can calculate the bitwise OR result of the corresponding subset and update the maximum value $\\textit{mx}$ and answer $\\textit{ans}$.\n\nThe time complexity is $O(2^n \\cdot n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(2^n)", "space_complexity": "O(n)" }, { "problem_id": 2045, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2046, "explanations": { "1": "We first assume that the first node is already sorted. Starting from the second node, when we encounter a node with a negative value, we use the head insertion method. For non-negative values, we continue to traverse down.\n\nThe time complexity is $O(n)$, where $n$ is the length of the linked list. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2047, "explanations": { "1": "First, we split the sentence into words by spaces, and then check each word to determine if it is a valid word.\n\nFor each word, we can use a boolean variable $\\textit{st}$ to record whether a hyphen has already appeared, and then traverse each character in the word, judging according to the rules described in the problem.\n\nFor each character $s[i]$, we have the following cases:\n\n- If $s[i]$ is a digit, then $s$ is not a valid word, and we return $\\text{false}$ directly;\n- If $s[i]$ is a punctuation mark ('!', '.', ','), and $i < \\text{len}(s) - 1$, then $s$ is not a valid word, and we return $\\text{false}$ directly;\n- If $s[i]$ is a hyphen, then we need to check if the following conditions are met:\n - The hyphen can only appear once;\n - The hyphen cannot appear at the beginning or end of the word;\n - Both sides of the hyphen must be letters;\n- If $s[i]$ is a letter, then we do not need to do anything.\n\nFinally, we count the number of valid words in the sentence.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the sentence." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2048, "explanations": { "1": "We note that the range of $n$ in the problem is $[0, 10^6]$, and one of the balanced numbers greater than $10^6$ is $1224444$. Therefore, we directly enumerate $x \\in [n + 1, ..]$ and then judge whether $x$ is a balanced number. The enumerated $x$ will definitely not exceed $1224444$.\n\nThe time complexity is $O(M - n)$, where $M = 1224444$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(M - n)", "space_complexity": "O(1)" }, { "problem_id": 2049, "explanations": { "1": "First, we construct a graph $g$ based on the given parent array `parents`, where $g[i]$ represents all child nodes of node $i$. We define a variable $ans$ to represent the number of nodes with the highest score, and a variable $mx$ to represent the highest score.\n\nThen, we design a function `dfs(i, fa)` to calculate the score of node $i$ and return the number of nodes in the subtree rooted at node $i$.\n\nThe calculation process of the function `dfs(i, fa)` is as follows:\n\nWe first initialize a variable $cnt = 1$, representing the number of nodes in the subtree rooted at node $i$; a variable $score = 1$, representing the initial score of node $i$.\n\nNext, we traverse all child nodes $j$ of node $i$. If $j$ is not the parent node $fa$ of node $i$, then we recursively call `dfs(j, i)`, and multiply the return value into $score$, and add the return value to $cnt$.\n\nAfter traversing the child nodes, if $n - cnt > 0$, then we multiply $n - cnt$ into $score$.\n\nThen, we check whether $mx$ is less than $score$. If it is less, then we update $mx$ to $score$, and update $ans$ to $1$; if it is equal, then we update $ans$ to $ans + 1$.\n\nFinally, we return $cnt$.\n\nIn the end, we call `dfs(0, -1)` and return $ans$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2050, "explanations": { "1": "First, we construct a directed acyclic graph based on the given prerequisite course relationships, perform topological sorting on this graph, and then use dynamic programming to find the minimum time required to complete all courses according to the results of the topological sorting.\n\nWe define the following data structures or variables:\n\n- Adjacency list $g$ stores the directed acyclic graph, and an array $indeg$ stores the in-degree of each node;\n- Queue $q$ stores all nodes with an in-degree of $0$;\n- Array $f$ stores the earliest completion time of each node, initially $f[i] = 0$;\n- Variable $ans$ records the final answer, initially $ans = 0$;\n\nWhen $q$ is not empty, take out the head node $i$ in turn, traverse each node $j$ in $g[i]$, update $f[j] = \\max(f[j], f[i] + time[j])$, update $ans = \\max(ans, f[j])$ at the same time, and reduce the in-degree of $j$ by $1$. If the in-degree of $j$ is $0$ at this time, add $j$ to the queue $q$;\n\nFinally, return $ans$.\n\nThe time complexity is $O(m + n)$, and the space complexity is $O(m + n)$. Where $m$ is the length of the array $relations$." }, "is_english": true, "time_complexity": "O(m + n)", "space_complexity": "O(m + n)" }, { "problem_id": 2051, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2052, "explanations": { "1": "We use an array $\\textit{nums}$ to record the length of each word, and let the length of the array be $n$. Then we define a prefix sum array $\\textit{s}$ of length $n + 1$, where $\\textit{s}[i]$ represents the sum of the lengths of the first $i$ words.\n\nNext, we design a function $\\textit{dfs}(i)$, which represents the minimum cost of splitting the sentence starting from the $i$-th word. The answer is $\\textit{dfs}(0)$.\n\nThe execution process of the function $\\textit{dfs}(i)$ is as follows:\n\n- If the sum of the lengths of the words from the $i$-th word to the last word plus the number of spaces between the words is less than or equal to $k$, then these words can be placed on the last line, and the cost is $0$.\n- Otherwise, we enumerate the position $j$ of the next word to start splitting, such that the sum of the lengths of the words from the $i$-th word to the $(j-1)$-th word plus the number of spaces between the words is less than or equal to $k$. Then $\\textit{dfs}(j)$ represents the minimum cost of splitting the sentence starting from the $j$-th word, and $(k - m)^2$ represents the cost of placing the words from the $i$-th word to the $(j-1)$-th word on one line, where $m$ represents the sum of the lengths of the words from the $i$-th word to the $(j-1)$-th word plus the number of spaces between the words. We enumerate all $j$ and take the minimum value.\n\nThe answer is $\\textit{dfs}(0)$.\n\nTo avoid repeated calculations, we can use memoized search.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ is the number of words." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 2053, "explanations": { "1": "We can use a hash table $\\textit{cnt}$ to record the number of occurrences of each string. Then, we traverse the array once more. For each string, if its occurrence count is $1$, we decrement $k$ by one. When $k$ reaches $0$, we return the current string.\n\nTime complexity is $O(L)$, and space complexity is $O(L)$, where $L$ is the total length of all strings in the array $\\textit{arr}$." }, "is_english": true, "time_complexity": "O(L)", "space_complexity": "O(L)" }, { "problem_id": 2054, "explanations": { "1": "We can sort the events by their start times, and then preprocess the maximum value starting from each event, i.e., $f[i]$ represents the maximum value of choosing one event from the $i$-th event to the last event.\n\nThen we enumerate each event. For each event, we use binary search to find the first event whose start time is greater than the end time of the current event, denoted as $\\textit{idx}$. The maximum value starting from the current event is $f[\\textit{idx}]$ plus the value of the current event, which is the maximum value that can be obtained by choosing the current event as the first event. We take the maximum value among all these values.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the number of events." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2055, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2056, "explanations": { "1": "The problem has at most $4$ pieces, and each piece can move in up to $8$ directions. We can consider using DFS to search all possible move combinations.\n\nWe enumerate each piece in order. For each piece, we can choose not to move or move according to the rules. We use an array $\\textit{dist}[i]$ to record the movement of the $i$-th piece, where $\\textit{dist}[i][x][y]$ represents the time when the $i$-th piece passes through the coordinate $(x, y)$. We use an array $\\textit{end}[i]$ to record the endpoint coordinates and time of the $i$-th piece. During the search, we need to determine whether the current piece can stop moving and whether it can continue moving in the current direction.\n\nWe define a method $\\text{checkStop}(i, x, y, t)$ to determine whether the $i$-th piece can stop at coordinate $(x, y)$ at time $t$. If for all previous pieces $j$, $\\textit{dist}[j][x][y] < t$, then the $i$-th piece can stop moving.\n\nAdditionally, we define a method $\\text{checkPass}(i, x, y, t)$ to determine whether the $i$-th piece can pass through coordinate $(x, y)$ at time $t$. If any other piece $j$ also passes through coordinate $(x, y)$ at time $t$, or if any other piece $j$ stops at $(x, y)$ and the time does not exceed $t$, then the $i$-th piece cannot pass through coordinate $(x, y)$ at time $t$.\n\nThe time complexity is $O((n \\times M)^n)$, and the space complexity is $O(n \\times M)$. Here, $n$ is the number of pieces, and $M$ is the movement range of each piece." }, "is_english": true, "time_complexity": "O((n \\times M)^n)", "space_complexity": "O(n \\times M)" }, { "problem_id": 2057, "explanations": { "1": "We directly traverse the array. For each index $i$, we check if it satisfies $i \\bmod 10 = \\textit{nums}[i]$. If it does, we return the current index $i$.\n\nIf we traverse the entire array and do not find a satisfying index, we return $-1$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2058, "explanations": { "1": "Based on the problem description, we need to find the positions of the first and last critical points in the linked list, $\\textit{first}$ and $\\textit{last}$, respectively. This allows us to calculate the maximum distance $\\textit{maxDistance} = \\textit{last} - \\textit{first}$. For the minimum distance $\\textit{minDistance}$, we need to traverse the linked list, calculate the distance between two adjacent critical points, and take the minimum value.\n\nThe time complexity is $O(n)$, where $n$ is the length of the linked list. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2059, "explanations": { "1": "", "2": "", "3": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2060, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2061, "explanations": { "1": "我们从起点 $(0, 0)$ 开始模拟机器人的清扫过程,每次清扫当前位置,然后向前走一步,如果碰到墙壁或者已经清扫过的位置,就顺时针旋转 90 度,然后继续清扫。\n\n过程中,我们用一个三元组 $(i, j, k)$ 表示机器人当前的位置 $(i, j)$ 和朝向 $k$,其中 $k$ 的取值范围为 $0, 1, 2, 3$,分别表示朝右、朝下、朝左、朝上。我们用一个集合 `vis` 记录所有访问过的状态三元组。\n\n时间复杂度 $O(m \\times n)$,空间复杂度 $O(m \\times n)$。其中 $m$ 和 $n$ 分别为房间的行数和列数。", "2": "" }, "is_english": false, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 2062, "explanations": { "1": "We can enumerate the left endpoint $i$ of the substring. For the current left endpoint, maintain a hash table to record the vowels that appear in the current substring. Then enumerate the right endpoint $j$. If the character at the current right endpoint is not a vowel, break the loop. Otherwise, add the character at the current right endpoint to the hash table. If the number of elements in the hash table is $5$, it means the current substring is a vowel substring, and increment the result by $1$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(C)$. Here, $n$ is the length of the string $word$, and $C$ is the size of the character set, which is $5$ in this problem." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(C)" }, { "problem_id": 2063, "explanations": { "1": "We can enumerate each character $\\textit{word}[i]$ in the string. If $\\textit{word}[i]$ is a vowel, then $\\textit{word}[i]$ appears in $(i + 1) \\times (n - i)$ substrings. We sum up the counts of these substrings.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $\\textit{word}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2064, "explanations": { "1": "我们注意到,如果分配给任意商店商品数目的最大值为 $x$,且满足题目要求,那么 $x+1$ 也一定满足题目要求,这存在着单调性。因此我们可以通过二分查找,找到一个最小的 $x$,使得 $x$ 满足题目要求。\n\n我们定义二分查找的左边界 $left=1$,右边界 $right=10^5$。对于二分查找的每一步,我们取中间值 $mid$,判断是否存在一个分配方案,使得分配给任意商店商品数目的最大值为 $mid$,如果存在,那么我们将右边界 $right$ 移动到 $mid$,否则将左边界 $left$ 移动到 $mid+1$。\n\n二分查找结束后,答案即为 $left$。\n\n时间复杂度 $O(m \\times \\log M)$,空间复杂度 $O(1)$。其中 $m$ 为商品种类数,而 $M$ 为商品数目的最大值,本题中 $M \\leq 10^5$。" }, "is_english": false, "time_complexity": "O(m \\times \\log M)", "space_complexity": "O(1)" }, { "problem_id": 2065, "explanations": { "1": "We observe the data range of the problem and find that the number of edges in each valid path starting from $0$ does not exceed $\\frac{\\textit{maxTime}}{\\min(time_j)} = \\frac{100}{10} = 10$, and each node has at most four edges. Therefore, we can directly use naive DFS to brute-force search all valid paths.\n\nFirst, we store the edges of the graph in the adjacency list $g$. Then, we design a function $\\textit{dfs}(u, \\textit{cost}, \\textit{value})$, where $u$ represents the current node number, and $\\textit{cost}$ and $\\textit{value}$ respectively represent the cost time and value of the current path. Additionally, we use an array $\\textit{vis}$ of length $n$ to record whether each node has been visited. Initially, we mark node $0$ as visited.\n\nThe logic of the function $\\textit{dfs}(u, \\textit{cost}, \\textit{value})$ is as follows:\n\n- If the current node number $u$ equals $0$, it means we have returned to the starting point, so we update the answer to $\\max(\\textit{ans}, \\textit{value})$;\n- For each neighbor node $v$ of the current node $u$, if the current path's cost time plus the time $t$ of the edge $(u, v)$ does not exceed $\\textit{maxTime}$, then we can choose to continue visiting node $v$;\n - If node $v$ has already been visited, we directly recursively call $\\textit{dfs}(v, \\textit{cost} + t, \\textit{value})$;\n - If node $v$ has not been visited, we mark node $v$ as visited, then recursively call $\\textit{dfs}(v, \\textit{cost} + t, \\textit{value} + \\textit{values}[v])$, and finally restore the visit status of node $v$.\n\nIn the main function, we call $\\textit{dfs}(0, 0, \\textit{values}[0])$ and return the answer $\\textit{ans}$.\n\nThe time complexity is $O(n + m + 4^{\\frac{\\textit{maxTime}}{\\min(time_j)}})$, and the space complexity is $O(n + m + \\frac{\\textit{maxTime}}{\\min(time_j)})$. Here, $n$ and $m$ respectively represent the number of nodes and edges." }, "is_english": true, "time_complexity": "O(n + m + 4^{\\frac{\\textit{maxTime}}{\\min(time_j)}})", "space_complexity": "O(n + m + \\frac{\\textit{maxTime}}{\\min(time_j)})" }, { "problem_id": 2066, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2067, "explanations": { "1": "We can enumerate the number of types of letters in the substring within the range of $[1..26]$, then the length of the substring is $i \\times count$.\n\nNext, we take the current substring length as the size of the window, count the number of types of letters in the window size that are equal to $count$, and record it in $t$. If $i = t$ at this time, it means that the number of letters in the current window are all $count$, then we can increment the answer by one.\n\nThe time complexity is $O(n \\times C)$, and the space complexity is $O(C)$. Where $n$ is the length of the string $s$, and $C$ is the number of types of letters, in this problem $C = 26$." }, "is_english": true, "time_complexity": "O(n \\times C)", "space_complexity": "O(C)" }, { "problem_id": 2068, "explanations": { "1": "We can create an array $cnt$ of length $26$ to record the difference in the number of times each letter appears in the two strings. Then we traverse $cnt$, if any letter appears the difference in the number of times greater than $3$, then return `false`, otherwise return `true`.\n\nThe time complexity is $O(n)$ and the space complexity is $O(C)$. Where $n$ is the length of the string, and $C$ is the size of the character set, and in this question $C = 26$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(C)" }, { "problem_id": 2069, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2070, "explanations": { "1": "For each query, we need to find the maximum beauty value among the items with a price less than or equal to the query price. We can use the offline query method, first sort the items by price, and then sort the queries by price.\n\nNext, we traverse the queries from small to large. For each query, we use a pointer $i$ to point to the item array. If the price of the item is less than or equal to the query price, we update the current maximum beauty value and move the pointer $i$ to the right until the price of the item is greater than the query price. We record the current maximum beauty value, which is the answer to the current query. Continue to traverse the next query until all queries are processed.\n\nThe time complexity is $O(n \\times \\log n + m \\times \\log m)$, and the space complexity is $O(\\log n + m)$. Where $n$ and $m$ are the lengths of the item array and the query array, respectively.", "2": "We can sort the items by price, and then preprocess the maximum beauty value of the items that are less than or equal to each price, recorded in the array $mx$ or the original $items$ array.\n\nFor each query, we can use binary search to find the index $j$ of the first item with a price greater than the query price, then $j - 1$ is the index of the item with the maximum beauty value and a price less than or equal to the query price, which is added to the answer.\n\nThe time complexity is $O((m + n) \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ and $m$ are the lengths of the item array and the query array, respectively." }, "is_english": true, "time_complexity": "O(n \\times \\log n + m \\times \\log m)", "space_complexity": "O(\\log n + m)" }, { "problem_id": 2071, "explanations": { "1": "Sort the tasks in ascending order of completion time and the workers in ascending order of ability.\n\nSuppose the number of tasks we want to assign is $x$. We can greedily assign the first $x$ tasks to the $x$ workers with the highest strength. If it is possible to complete $x$ tasks, then it is also possible to complete $x-1$, $x-2$, $x-3$, ..., $1$, $0$ tasks. Therefore, we can use binary search to find the maximum $x$ such that it is possible to complete $x$ tasks.\n\nWe define a function $check(x)$ to determine whether it is possible to complete $x$ tasks.\n\nThe implementation of $check(x)$ is as follows:\n\nIterate through the $x$ workers with the highest strength in ascending order. Let the current worker being processed be $j$. The current available tasks must satisfy $tasks[i] \\leq workers[j] + strength$.\n\nIf the smallest required strength task $task[i]$ among the current available tasks is less than or equal to $workers[j]$, then worker $j$ can complete task $task[i]$ without using a pill. Otherwise, the current worker must use a pill. If there are pills remaining, use one pill and complete the task with the highest required strength among the current available tasks. Otherwise, return `false`.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$, where $n$ is the number of tasks." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2072, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2073, "explanations": { "1": "According to the problem description, when the $k^{th}$ person finishes buying tickets, all the people in front of the $k^{th}$ person will not buy more tickets than the $k^{th}$ person, and all the people behind the $k^{th}$ person will not buy more tickets than the $k^{th}$ person minus $1$.\n\nTherefore, we can traverse the entire queue. For the $i^{th}$ person, if $i \\leq k$, the time to buy tickets is $\\min(\\textit{tickets}[i], \\textit{tickets}[k])$; otherwise, the time to buy tickets is $\\min(\\textit{tickets}[i], \\textit{tickets}[k] - 1)$. We sum the buying time for all people to get the result.\n\nThe time complexity is $O(n)$, where $n$ is the length of the queue. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2074, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2075, "explanations": { "1": "First, we calculate the number of columns in the matrix $cols = \\textit{len}(encodedText) / rows$. Then, following the rules described in the problem, we start traversing the matrix from the top left corner, adding characters to the answer.\n\nFinally, we return the answer, making sure to remove any trailing spaces.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the string $encodedText$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2076, "explanations": { "1": "We can use a union-find set to maintain the friend relationships, and then for each request, we determine whether it meets the restriction conditions.\n\nFor the two people $(u, v)$ in the current request, if they are already friends, then the request can be directly accepted; otherwise, we traverse the restriction conditions. If there exists a restriction condition $(x, y)$ such that $u$ and $x$ are friends and $v$ and $y$ are friends, or $u$ and $y$ are friends and $v$ and $x$ are friends, then the request cannot be accepted.\n\nThe time complexity is $O(q \\times m \\times \\log(n))$, and the space complexity is $O(n)$. Where $q$ and $m$ are the number of requests and the number of restriction conditions respectively." }, "is_english": true, "time_complexity": "O(q \\times m \\times \\log(n))", "space_complexity": "O(n)" }, { "problem_id": 2077, "explanations": { "1": "长度为 `3` 的环,由三个顶点、三条边组成。我们假设三个顶点分别为 `a`, `b`, `c`。\n\n那么一定存在 `c <=> a`,`c <=> b` 以及 `a <=> b`,即环中的每个点都与其他两点直接相连。我们可以用哈希表来存放每个点的相邻点。\n\n由于环的长度为 `3`,每个相同的环会被重复统计 `3` 次,因此答案需除以 `3`。\n\n时间复杂度 $O(n^2)$,空间复杂度 $O(n)$。" }, "is_english": false, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 2078, "explanations": { "1": "时间复杂度 $O(n^2)$。", "2": "" }, "is_english": false, "time_complexity": "O(n^2)", "space_complexity": null }, { "problem_id": 2079, "explanations": { "1": "We can simulate the process of watering the plants. We use a variable $\\textit{water}$ to represent the current amount of water in the watering can, initially $\\textit{water} = \\textit{capacity}$.\n\nWe traverse the plants. For each plant:\n\n- If the current amount of water in the watering can is enough to water this plant, we move forward one step, water this plant, and update $\\textit{water} = \\textit{water} - \\textit{plants}[i]$.\n- Otherwise, we need to return to the river to refill the watering can, walk back to the current position, and then move forward one step. The number of steps we need is $i \\times 2 + 1$. Then we water this plant and update $\\textit{water} = \\textit{capacity} - \\textit{plants}[i]$.\n\nFinally, return the total number of steps.\n\nThe time complexity is $O(n)$, where $n$ is the number of plants. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2080, "explanations": { "1": "We use a hash table $g$ to store the array of indices corresponding to each value. In the constructor, we traverse the array $\\textit{arr}$, adding the index corresponding to each value to the hash table.\n\nIn the query function, we first check whether the given value exists in the hash table. If it does not exist, it means that the value does not exist in the array, so we directly return $0$. Otherwise, we get the index array $\\textit{idx}$ corresponding to the value. Then we use binary search to find the first index $l$ that is greater than or equal to $\\textit{left}$, and the first index $r$ that is greater than $\\textit{right}$. Finally, we return $r - l$.\n\nIn terms of time complexity, the time complexity of the constructor is $O(n)$, and the time complexity of the query function is $O(\\log n)$. The space complexity is $O(n)$. Where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2081, "explanations": { "1": "For a k-mirror number, we can divide it into two parts: the first half and the second half. For numbers with even length, the first and second halves are exactly the same; for numbers with odd length, the first and second halves are the same, but the middle digit can be any digit.\n\nWe can enumerate the numbers in the first half, and then construct the complete k-mirror number based on the first half. The specific steps are as follows:\n\n1. **Enumerate Lengths**: Start enumerating the length of the numbers from 1, until we find enough k-mirror numbers that meet the requirements.\n2. **Calculate the Range of the First Half**: For a number of length $l$, the range of the first half is $[10^{(l-1)/2}, 10^{(l+1)/2})$.\n3. **Construct k-Mirror Numbers**: For each number $i$ in the first half, if the length is even, use $i$ directly as the first half; if the length is odd, divide $i$ by 10 to get the first half. Then reverse the digits of the first half and append them to form the complete k-mirror number.\n4. **Check k-Mirror Numbers**: Convert the constructed number to base $k$ and check whether it is a palindrome.\n5. **Accumulate the Result**: If it is a k-mirror number, add it to the result and decrease the counter $n$. When $n$ reaches 0, return the result.\n\nThe time complexity mainly depends on the length being enumerated and the range of the first half. Since the maximum value of $n$ is 30, the number of enumerations is limited in practice. The space complexity is $O(1)$, since only a constant amount of extra space is" }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 2082, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2083, "explanations": { "1": "We can use a hash table or an array $\\textit{cnt}$ of length $26$ to record the occurrences of each character.\n\nTraverse the string $\\textit{s}$. For each character $\\textit{c}$, increment the value of $\\textit{cnt}[c]$ by $1$, and then add the value of $\\textit{cnt}[c]$ to the answer.\n\nFinally, return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $\\textit{s}$. The space complexity is $O(|\\Sigma|)$, where $\\Sigma$ is the character set. Here, it is lowercase English letters, so $|\\Sigma|=26$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 2084, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2085, "explanations": { "1": "We can use two hash tables, $cnt1$ and $cnt2$, to count the occurrences of each string in the two string arrays respectively. Then, we traverse one of the hash tables. If a string appears once in the other hash table and also appears once in the current hash table, we increment the answer by one.\n\nThe time complexity is $O(n + m)$, and the space complexity is $O(n + m)$. Where $n$ and $m$ are the lengths of the two string arrays respectively." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(n + m)" }, { "problem_id": 2086, "explanations": { "1": "从左到右遍历字符串,遇到 `H` 时,优先考虑右边是否有空位,如果有则放置水桶,并且跳过水桶的下一个位置;如果右边没有空位,则考虑左边是否有空位,如果有则放置水桶,否则无解。\n\n时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为字符串 `street` 的长度。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2087, "explanations": { "1": "设机器人当前位置为 $(i, j)$,目标位置为 $(x, y)$。\n\n- 如果 $i \\lt x$,则机器人往下移动,代价为 $rowCosts[i + 1] + rowCosts[i + 2] + \\cdots + rowCosts[x]$。\n- 如果 $i \\gt x$,则机器人往上移动,代价为 $rowCosts[x] + rowCosts[x + 1] + \\cdots + rowCosts[i - 1]$。\n- 如果 $j \\lt y$,则机器人往右移动,代价为 $colCosts[j + 1] + colCosts[j + 2] + \\cdots + colCosts[y]$。\n- 如果 $j \\gt y$,则机器人往左移动,代价为 $colCosts[y] + colCosts[y + 1] + \\cdots + colCosts[j - 1]$。\n\n时间复杂度 $O(m + n)$,空间复杂度 $O(1)$。其中 $m$ 和 $n$ 分别为 $rowCosts$ 和 $colCosts$ 的长度。" }, "is_english": false, "time_complexity": "O(m + n)", "space_complexity": "O(1)" }, { "problem_id": 2088, "explanations": { "1": "我们定义 $f[i][j]$ 表示以 $(i, j)$ 为顶点的金字塔的最大高度,那么有如下状态转移方程:\n\n$$\nf[i][j] = \\begin{cases} 0 & \\textit{grid}[i][j] = 0 \\\\ \\min(f[i + 1][j - 1], f[i + 1][j], f[i + 1][j + 1]) + 1 & \\textit{grid}[i][j] = 1 \\end{cases}\n$$\n\n因此,我们可以从下往上、从左往右遍历网格,计算出所有的 $f[i][j]$,并累加所有的 $f[i][j]$ 即可得到正金字塔的个数。\n\n接下来,我们考虑倒金字塔的个数。与金字塔类似,我们定义 $g[i][j]$ 表示以 $(i, j)$ 为顶点的倒金字塔的最大高度,那么有如下状态转移方程:\n\n$$\ng[i][j] = \\begin{cases} 0 & \\textit{grid}[i][j] = 0 \\\\ \\min(g[i - 1][j - 1], g[i - 1][j], g[i - 1][j + 1]) + 1 & \\textit{grid}[i][j] = 1 \\end{cases}\n$$\n\n因此,我们可以从上往下、从左往右遍历网格,计算出所有的 $g[i][j]$,并累加所有的 $g[i][j]$ 即可得到倒金字塔的个数。\n\n最后,正金字塔的个数加上倒金字塔的个数即为答案。实际代码中,我们可以只用一个二维数组 $f[i][j]$ 即可。\n\n时间复杂度 $O(m \\times n)$,空间复杂度 $O(m \\times n)$。其中 $m$ 和 $n$ 分别为网格的行数和列数。" }, "is_english": false, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 2089, "explanations": { "1": "将数组 `nums` 排序后,遍历数组,找出所有等于 `target` 的元素的下标,将其加入结果数组中。\n\n时间复杂度 $O(n \\times \\log n)$,空间复杂度 $O(\\log n)$。其中 $n$ 为数组 `nums` 的长度。" }, "is_english": false, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 2090, "explanations": { "1": "The length of a subarray with radius $k$ is $k \\times 2 + 1$, so we can maintain a window of size $k \\times 2 + 1$ and denote the sum of all elements in the window as $s$.\n\nWe create an answer array $\\textit{ans}$ of length $n$, initially setting each element to $-1$.\n\nNext, we traverse the array $\\textit{nums}$, adding the value of $\\textit{nums}[i]$ to the window sum $s$. If $i \\geq k \\times 2$, it means the window size is $k \\times 2 + 1$, so we set $\\textit{ans}[i-k] = \\frac{s}{k \\times 2 + 1}$. Then, we remove the value of $\\textit{nums}[i - k \\times 2]$ from the window sum $s$. Continue traversing the next element.\n\nFinally, return the answer array.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. Ignoring the space consumption of the answer array, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2091, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2092, "explanations": { "1": "The core idea of this problem is to find all people who eventually know the secret by simulating the propagation process through meetings. We can treat each meeting as an edge in an undirected graph, where each participant is a node in the graph, and the meeting time is the \"timestamp\" of the edge connecting the nodes. At each time point, we traverse all meetings and use Breadth-First Search (BFS) to simulate the propagation of the secret.\n\nWe create a boolean array $\\textit{vis}$ to record whether each person knows the secret. Initially, $\\textit{vis}[0] = \\text{true}$ and $\\textit{vis}[\\textit{firstPerson}] = \\text{true}$, indicating that person 0 and $\\textit{firstPerson}$ already know the secret.\n\nWe first sort the meetings by time to ensure that we process meetings in the correct order during each traversal.\n\nNext, we process each group of meetings at the same time. For each group of meetings at the same time (i.e., $\\textit{meetings}[i][2] = \\textit{meetings}[i+1][2]$), we treat them as events occurring at the same moment. For each meeting, we record the relationships between participants and add these participants to a set.\n\nThen, we use BFS to propagate the secret. For all participants at the current time point, if any of them already know the secret, we will traverse the adjacent nodes of that participant (i.e., other participants in the meeting) through BFS and mark them as knowing the secret. This process continues to propagate until all people who can know the secret at this meeting are updated.\n\nWhen all meetings are processed, we traverse the $\\textit{vis}$ array, add the IDs of all people who know the secret to the result list, and return it.\n\nThe time complexity is $O(m \\times \\log m + n)$, and the space complexity is $O(n)$, where $m$ and $n$ are the number of meetings and the number of experts, respectively." }, "is_english": true, "time_complexity": "O(m \\times \\log m + n)", "space_complexity": "O(n)" }, { "problem_id": 2093, "explanations": { "1": "本题属于带限制的单源最短路问题。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2094, "explanations": { "1": "First, we count the occurrence of each digit in $\\textit{digits}$, recording it in an array or hash table $\\textit{cnt}$.\n\nThen, we enumerate all even numbers in the range $[100, 1000)$, checking if each digit of the even number does not exceed the corresponding digit's count in $\\textit{cnt}$. If so, we add this even number to the answer array.\n\nFinally, we return the answer array.\n\nThe time complexity is $O(k \\times 10^k)$, where $k$ is the number of digits of the target even number, which is $3$ in this problem. Ignoring the space consumed by the answer, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(k \\times 10^k)", "space_complexity": "O(1)" }, { "problem_id": 2095, "explanations": { "1": "The fast and slow pointer technique is a common method used to solve problems related to linked lists. We can maintain two pointers, a slow pointer $\\textit{slow}$ and a fast pointer $\\textit{fast}$. Initially, $\\textit{slow}$ points to a dummy node, whose $\\textit{next}$ pointer points to the head node $\\textit{head}$ of the list, while $\\textit{fast}$ points to the head node $\\textit{head}$.\n\nThen, we move the slow pointer one position backward and the fast pointer two positions backward each time, until the fast pointer reaches the end of the list. At this point, the node next to the node pointed by the slow pointer is the middle node of the list. We can remove the middle node by setting the $\\textit{next}$ pointer of the node pointed by the slow pointer to point to the next next node.\n\nThe time complexity is $O(n)$, where $n$ is the length of the list. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2096, "explanations": { "1": "We can first find the lowest common ancestor of nodes $\\textit{startValue}$ and $\\textit{destValue}$, denoted as $\\textit{node}$. Then, starting from $\\textit{node}$, we find the paths to $\\textit{startValue}$ and $\\textit{destValue}$ respectively. The path from $\\textit{startValue}$ to $\\textit{node}$ will consist of a number of $\\textit{U}$s, and the path from $\\textit{node}$ to $\\textit{destValue}$ will be the $\\textit{path}$. Finally, we concatenate these two paths.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree.", "2": "We can start from $\\textit{root}$, find the paths to $\\textit{startValue}$ and $\\textit{destValue}$, denoted as $\\textit{pathToStart}$ and $\\textit{pathToDest}$, respectively. Then, remove the longest common prefix of $\\textit{pathToStart}$ and $\\textit{pathToDest}$. At this point, the length of $\\textit{pathToStart}$ is the number of $\\textit{U}$s in the answer, and the path of $\\textit{pathToDest}$ is the path in the answer. We just need to concatenate these two paths.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2097, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2098, "explanations": { "1": "We notice that the problem involves selecting a subsequence, so we can consider sorting the array first.\n\nNext, we greedily select the largest $k$ numbers. If the sum of these numbers is even, we directly return this sum $ans$.\n\nOtherwise, we have two greedy strategies:\n\n1. Among the largest $k$ numbers, find the smallest even number $mi1$, and then among the remaining $n - k$ numbers, find the largest odd number $mx1$. Replace $mi1$ with $mx1$. If such a replacement exists, then the sum after replacement $ans - mi1 + mx1$ is guaranteed to be even;\n2. Among the largest $k$ numbers, find the smallest odd number $mi2$, and then among the remaining $n - k$ numbers, find the largest even number $mx2$. Replace $mi2$ with $mx2$. If such a replacement exists, then the sum after replacement $ans - mi2 + mx2$ is guaranteed to be even.\n\nWe take the largest even sum as the answer. If no even sum exists, return $-1$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 2099, "explanations": { "1": "First, we create an index array $\\textit{idx}$, where each element is an index of the array $\\textit{nums}$. Then, we sort the index array $\\textit{idx}$ based on the values in $\\textit{nums}$, with the sorting rule being $\\textit{nums}[i] < \\textit{nums}[j]$, where $i$ and $j$ are two indices in the index array $\\textit{idx}$.\n\nAfter sorting, we take the last $k$ elements of the index array $\\textit{idx}$. These $k$ elements correspond to the largest $k$ elements in the array $\\textit{nums}$. Then, we sort these $k$ indices to get the order of the largest $k$ elements in the array $\\textit{nums}$.\n\nThe time complexity is $O(n \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 2100, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2101, "explanations": { "1": "We define an array $g$ of length $n$, where $g[i]$ represents the indices of all bombs that can be triggered by bomb $i$ within its explosion range.\n\nNext, we iterate over all bombs. For two bombs $(x_1, y_1, r_1)$ and $(x_2, y_2, r_2)$, we calculate the distance between them $\\textit{dist} = \\sqrt{(x_1 - x_2)^2 + (y_1 - y_2)^2}$. If $\\textit{dist} \\leq r_1$, then bomb $i$ can trigger bomb $j$ within its explosion range, so we add $j$ to $g[i]$. If $\\textit{dist} \\leq r_2$, then bomb $j$ can trigger bomb $i$ within its explosion range, so we add $i$ to $g[j]$.\n\nNext, we iterate over all bombs. For each bomb $k$, we use breadth-first search to calculate the indices of all bombs that can be triggered by bomb $k$ within its explosion range and record them. If the number of these bombs equals $n$, then we can trigger all bombs and directly return $n$. Otherwise, we record the number of these bombs and return the maximum value.\n\nThe time complexity is $O(n^3)$ and the space complexity is $O(n^2)$, where $n$ is the number of bombs." }, "is_english": true, "time_complexity": "O(n^3)", "space_complexity": "O(n^2)" }, { "problem_id": 2102, "explanations": { "1": "We can use an ordered set to store the attractions, and a variable $i$ to record the current number of queries, initially $i = -1$.\n\nWhen calling the `add` method, we take the negative of the attraction's rating, so that we can use the ordered set to sort by rating in descending order. If the ratings are the same, sort by the dictionary order of the attraction names in ascending order.\n\nWhen calling the `get` method, we increment $i$ by one, and then return the name of the $i$-th attraction in the ordered set.\n\nThe time complexity of each operation is $O(\\log n)$, where $n$ is the number of added attractions. The space complexity is $O(n)$.", "2": "We notice that the query operations in this problem are performed in strictly increasing order. Therefore, we can use a method similar to the median in the data stream. We define two priority queues `good` and `bad`. `good` is a min-heap, storing the current best attractions, and `bad` is a max-heap, storing the current $i$-th best attraction.\n\nEach time the `add` method is called, we add the attraction's rating and name to `good`, and then add the worst attraction in `good` to `bad`.\n\nEach time the `get` method is called, we add the best attraction in `bad` to `good`, and then return the worst attraction in `good`.\n\nThe time complexity of each operation is $O(\\log n)$, where $n$ is the number of added attractions. The space complexity is $O(n)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(n)" }, { "problem_id": 2103, "explanations": { "1": "We can use an array $mask$ of length $10$ to represent the color situation of the rings on each rod, where $mask[i]$ represents the color situation of the ring on the $i$th rod. If there are red, green, and blue rings on the $i$th rod, then the binary representation of $mask[i]$ is $111$, that is, $mask[i] = 7$.\n\nWe traverse the string $rings$. For each color position pair $(c, j)$, where $c$ represents the color of the ring and $j$ represents the number of the rod where the ring is located, we set the corresponding binary bit of $mask[j]$, that is, $mask[j] |= d[c]$, where $d[c]$ represents the binary bit corresponding to color $c$.\n\nFinally, we count the number of elements in $mask$ that are $7$, which is the number of rods that have collected all three colors of rings.\n\nThe time complexity is $O(n)$, and the space complexity is $O(|\\Sigma|)$, where $n$ represents the length of the string $rings$, and $|\\Sigma|$ represents the size of the character set.", "2": "" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 2104, "explanations": { "1": "循环遍历 $i$,作为子数组的起始位置。对于每个 $i$,遍历每个 $j$ 作为子数组的终止位置,此过程中不断求解子数组的最大值、最小值,然后累加差值到结果 `ans` 中。\n\n最后返回 `ans` 即可。\n\n时间复杂度 $O(n^2)$。", "2": "枚举每个元素 `nums[i]` 作为最大值出现在了多少个子数组中,以及作为最小值出现在多少个子数组中。\n\n其中 `nums[i]` 作为最大值的贡献为正,作为最小值的贡献为负。\n\n我们以 `nums[i]` 作为最大值为例。找出左侧第一个比 `nums[i]` 大的位置 `left[i]`,右侧第一个大于等于 `nums[i]` 的位置 `right[i]`。计算每个 `nums[i]` 的贡献 $(i - left[i])\\times (right[i] - i)\\times arr[i]$,累加得到结果。\n\n时间复杂度 $O(n)$。\n\n相似题目:\n\n- [907. 子数组的最小值之和](https://github.com/doocs/leetcode/blob/main/solution/0900-0999/0907.Sum%20of%20Subarray%20Minimums/README.md)" }, "is_english": false, "time_complexity": "O(n^2)", "space_complexity": null }, { "problem_id": 2105, "explanations": { "1": "We use two variables $a$ and $b$ to represent the amount of water Alice and Bob have, initially $a = \\textit{capacityA}$, $b = \\textit{capacityB}$. Then we use two pointers $i$ and $j$ to point to the head and tail of the plant array, and simulate the process of Alice and Bob watering from both ends to the middle.\n\nWhen $i < j$, we judge whether Alice and Bob have enough water to water the plants. If not, we refill the watering cans. Then we update the amount of water $a$ and $b$, and move the pointers $i$ and $j$. Finally, we need to judge whether $i$ and $j$ are equal. If they are equal, we need to judge whether $\\max(a, b)$ is less than the amount of water the plant needs. If it is less, we need to refill the watering cans again.\n\nThe time complexity is $O(n)$, where $n$ is the length of the plant array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2106, "explanations": { "1": "Let's assume the movement range is $[l, r]$ and the starting position is $\\textit{startPos}$. We need to calculate the minimum number of steps required. Based on the position of $\\textit{startPos}$, we can divide this into three cases:\n\n1. If $\\textit{startPos} \\leq l$, then we move right from $\\textit{startPos}$ to $r$. The minimum number of steps is $r - \\textit{startPos}$;\n2. If $\\textit{startPos} \\geq r$, then we move left from $\\textit{startPos}$ to $l$. The minimum number of steps is $\\textit{startPos} - l$;\n3. If $l < \\textit{startPos} < r$, we can either move left from $\\textit{startPos}$ to $l$ then right to $r$, or move right from $\\textit{startPos}$ to $r$ then left to $l$. The minimum number of steps is $r - l + \\min(\\lvert \\textit{startPos} - l \\rvert, \\lvert r - \\textit{startPos} \\rvert)$.\n\nAll three cases can be unified by the formula $r - l + \\min(\\lvert \\textit{startPos} - l \\rvert, \\lvert r - \\textit{startPos} \\rvert)$.\n\nSuppose we fix the right endpoint $r$ of the interval and move the left endpoint $l$ to the right. Let's see how the minimum number of steps changes:\n\n1. If $\\textit{startPos} \\leq l$, as $l$ increases, the minimum number of steps remains unchanged.\n2. If $\\textit{startPos} > l$, as $l$ increases, the minimum number of steps decreases.\n\nTherefore, as $l$ increases, the minimum number of steps is non-strictly monotonically decreasing. Based on this, we can use the two-pointer approach to find all qualifying maximum intervals, then take the one with the maximum total fruits among all qualifying intervals as the answer.\n\nSpecifically, we use two pointers $i$ and $j$ to point to the left and right indices of the interval, initially $i = j = 0$. We also use a variable $s$ to record the total number of fruits in the interval, initially $s = 0$.\n\nEach time we include $j$ in the interval, then update $s = s + \\textit{fruits}[j][1]$. If the minimum number of steps in the current interval $\\textit{fruits}[j][0] - \\textit{fruits}[i][0] + \\min(\\lvert \\textit{startPos} - \\textit{fruits}[i][0] \\rvert, \\lvert \\textit{startPos} - \\textit{fruits}[j][0] \\rvert)$ is greater than $k$, we move $i$ to the right in a loop until $i > j$ or the minimum number of steps in the interval is less than or equal to $k$. At this point, we update the answer $\\textit{ans} = \\max(\\textit{ans}, s)$. Continue moving $j$ until $j$ reaches the end of the array.\n\nFinally, return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2107, "explanations": { "1": "We can maintain a sliding window of size $k$, where the candies outside the window are for ourselves, and the $k$ candies inside the window are shared with our sister and mother. We can use a hash table $cnt$ to record the flavors of the candies outside the window and their corresponding quantities.\n\nInitially, the hash table $cnt$ stores the flavors of the candies from $candies[k]$ to $candies[n-1]$ and their corresponding quantities. At this time, the number of candy flavors is the size of the hash table $cnt$, that is, $ans = cnt.size()$.\n\nNext, we traverse the candies in the range $[k,..n-1]$, add the current candy $candies[i]$ to the window, and move the candy $candies[i-k]$ on the left side of the window out of the window. Then we update the hash table $cnt$, and update the number of candy flavors $ans$ to $max(ans, cnt.size())$.\n\nAfter traversing all the candies, we can get the maximum number of unique flavors of candies that can be retained.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of candies." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2108, "explanations": { "1": "We iterate through the array `words`, for each string `w`, we determine if it is a palindrome. If it is, then we return `w`; otherwise, we continue to iterate.\n\nTo determine if a string is a palindrome, we can use two pointers, one pointing to the start and the other to the end of the string, moving towards the center, and checking if the corresponding characters are equal. If, after traversing the entire string, no unequal characters are found, then the string is a palindrome.\n\nThe time complexity is $O(L)$, where $L$ is the sum of the lengths of all strings in the array `words`. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(L)", "space_complexity": "O(1)" }, { "problem_id": 2109, "explanations": { "1": "We can use two pointers $i$ and $j$ to point to the beginning of the string $s$ and the array $\\textit{spaces}$, respectively. Then, we iterate through the string $s$ from the beginning to the end. When $i$ equals $\\textit{spaces}[j]$, we add a space to the result string, and then increment $j$ by $1$. Next, we add $s[i]$ to the result string, and then increment $i$ by $1$. We continue this process until we have iterated through the entire string $s$.\n\nThe time complexity is $O(n + m)$, and the space complexity is $O(n + m)$, where $n$ and $m$ are the lengths of the string $s$ and the array $spaces$, respectively." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(n + m)" }, { "problem_id": 2110, "explanations": { "1": "We define an answer variable $\\textit{ans}$ with an initial value of $0$.\n\nNext, we use two pointers $i$ and $j$, which point to the first day of the current smooth descent period and the day after the last day, respectively. Initially, $i = 0$ and $j = 0$.\n\nWe traverse the array $\\textit{prices}$ from left to right. For each position $i$, we move $j$ to the right until $j$ reaches the end of the array or $\\textit{prices}[j - 1] - \\textit{prices}[j] \\neq 1$. At this point, $\\textit{cnt} = j - i$ is the length of the current smooth descent period, and we add $\\frac{(1 + \\textit{cnt}) \\times \\textit{cnt}}{2}$ to the answer variable $\\textit{ans}$. Then we update $i$ to $j$ and continue traversing.\n\nAfter the traversal ends, we return the answer variable $\\textit{ans}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{prices}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2111, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2112, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2113, "explanations": { "1": "First, we initialize an array $ans$ with length $m$ to store the answers, initializing all elements to $-1$.\n\nNext, we iterate through the array $queries$. For each query, we first obtain the current query time $t$ and index $i$. We then take $t$ modulo $2n$ and compare $t$ with $n$:\n\n- If $t < n$, then the number of array elements at time $t$ is $n - t$, and the array elements are the result of the original array elements shifted left by $t$ positions. Therefore, if $i < n - t$, the answer is $nums[i + t]$;\n- If $t > n$, then the number of array elements at time $t$ is $t - n$, and the array elements are the first $t - n$ elements of the original array. Therefore, if $i < t - n$, the answer is $nums[i]$.\n\nFinally, return the array $ans$.\n\nThe time complexity is $O(m)$, where $m$ is the length of the array $queries$. Ignoring the space consumed by the answer array, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m)", "space_complexity": "O(1)" }, { "problem_id": 2114, "explanations": { "1": "We iterate through the array `sentences`. For each sentence, we count the number of spaces, then the number of words is the number of spaces plus $1$. Finally, we return the maximum number of words.\n\nThe time complexity is $O(L)$, where $L$ is the total length of all strings in the array `sentences`. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(L)", "space_complexity": "O(1)" }, { "problem_id": 2115, "explanations": { "1": "首先,我们可以将每道菜看成一个节点,每个节点的入度表示其所需的原材料数量。我们可以通过拓扑排序的方式,找到所有可以做出的菜。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2116, "explanations": { "1": "We observe that a string of odd length cannot be a valid parentheses string because there will always be one unmatched parenthesis. Therefore, if the length of the string $s$ is odd, return $\\textit{false}$ immediately.\n\nNext, we perform two passes.\n\nThe first pass goes from left to right, checking if all `'('` parentheses can be matched by `')'` or changeable parentheses. If not, return $\\textit{false}$.\n\nThe second pass goes from right to left, checking if all `')'` parentheses can be matched by `'('` or changeable parentheses. If not, return $\\textit{false}$.\n\nIf both passes complete successfully, it means all parentheses can be matched, and the string $s$ is a valid parentheses string. Return $\\textit{true}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$.\n\nSimilar problems:\n\n- [678. Valid Parenthesis String](https://github.com/doocs/leetcode/blob/main/solution/0600-0699/0678.Valid%20Parenthesis%20String/README_EN.md)" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2117, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2118, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2119, "explanations": { "1": "If the number is $0$, or the last digit of the number is not $0$, then the number after reversing twice will be the same as the original number.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 2120, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2121, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2122, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2123, "explanations": { "1": "We observe that if two $1$s in the matrix are adjacent, they must belong to different groups. Therefore, we can treat all $1$s in the matrix as vertices, and connect an edge between two adjacent $1$s to construct a bipartite graph.\n\nThen, the problem can be transformed into finding the minimum vertex cover of a bipartite graph, which means selecting the minimum number of vertices to cover all edges. Since the minimum vertex cover of a bipartite graph equals the maximum matching, we can use the Hungarian algorithm to find the maximum matching of the bipartite graph.\n\nThe core idea of the Hungarian algorithm is to continuously search for augmenting paths starting from unmatched vertices until no augmenting path exists, which yields the maximum matching.\n\nThe time complexity is $O(m \\times n)$, where $n$ and $m$ are the number of $1$s in the matrix and the number of edges, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": null }, { "problem_id": 2124, "explanations": { "1": "According to the problem statement, the string $s$ consists only of characters `a` and `b`.\n\nTo ensure that all `a`s appear before all `b`s, the condition that must be met is that `b` should not appear before `a`. In other words, the substring \"ba\" should not be present in the string $s$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2125, "explanations": { "1": "We can count the number of safety devices row by row. If the current row does not have any safety devices, we skip it. Otherwise, we multiply the number of safety devices in the current row by the number of safety devices in the previous row, and add it to the answer. Then we update the number of safety devices in the previous row to be the number of safety devices in the current row.\n\nThe time complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(1)" }, { "problem_id": 2126, "explanations": { "1": "According to the problem description, we can sort the asteroids by mass in ascending order, and then iterate through the asteroids. If the planet's mass is less than the asteroid's mass, the planet will be destroyed, and we return `false`. Otherwise, the planet will gain the mass of the asteroid.\n\nIf all asteroids can be destroyed, return `true`.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Where $n$ is the number of asteroids." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 2127, "explanations": { "1": "We observe that the employee's preference relationship in the problem can be regarded as a directed graph, which can be divided into multiple \"base cycle inward trees\". Each structure contains a cycle, and each node on the cycle is connected to a tree.\n\nWhat is a \"base cycle inward tree\"? First, a base cycle tree is a directed graph with $n$ nodes and $n$ edges, and an inward tree means that in this directed graph, each node has exactly one outgoing edge. In this problem, each employee has exactly one favorite employee, so the constructed directed graph can be composed of multiple \"base cycle inward trees\".\n\n\"\"

\n\nFor this problem, we can find the length of the maximum cycle in the graph. Here we only need to find the length of the largest cycle, because if there are multiple cycles, they are not connected to each other, which does not meet the problem requirements.\n\nIn addition, for the size of the cycle equal to $2$, that is, there are two employees who like each other, then we can arrange these two employees together. If these two employees are each liked by other employees, then we only need to arrange the employees who like them next to them. If there are multiple such situations, we can arrange them all.\n\nTherefore, the problem is actually equivalent to finding the length of the maximum cycle in the graph, and all cycles of length $2$ plus their longest chain. The maximum of these two can be found. To find the longest chain to the cycle of length $2$, we can use topological sorting.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array `favorite`." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2128, "explanations": { "1": "We observe that if two rows in the matrix satisfy one of the following conditions, they can be made equal by flipping certain columns:\n\n1. The corresponding elements of the two rows are equal, i.e., if one row is $1,0,0,1$, the other row is also $1,0,0,1$;\n1. The corresponding elements of the two rows are opposite, i.e., if one row is $1,0,0,1$, the other row is $0,1,1,0$.\n\nWe call two rows that satisfy one of the above conditions \"equivalent rows.\" The answer to the problem is the maximum number of equivalent rows in the matrix.\n\nTherefore, we can traverse each row of the matrix and convert each row into an \"equivalent row\" that starts with $0$. Specifically:\n\n- If the first element of the current row is $0$, keep the row unchanged;\n- If the first element of the current row is $1$, flip every element in the row, i.e., $0$ becomes $1$, $1$ becomes $0$. In other words, we flip rows starting with $1$ into \"equivalent rows\" starting with $0$.\n\nIn this way, we only need to use a hash table to count each converted row. If the hash table contains only one element at the end, it means we can remove all $1$s from the matrix by flipping rows or columns.\n\nThe time complexity is $O(mn)$ and the space complexity is $O(m)$, where $m$ and $n$ are the number of rows and columns in the matrix, respectively.\n\nRelated problem:\n\n- [1072. Flip Columns For Maximum Number of Equal Rows](https://github.com/doocs/leetcode/blob/main/solution/1000-1099/1072.Flip%20Columns%20For%20Maximum%20Number%20of%20Equal%20Rows/README_EN.md)" }, "is_english": true, "time_complexity": "O(mn)", "space_complexity": "O(m)" }, { "problem_id": 2129, "explanations": { "1": "Directly simulate the process. Split the string by spaces to get each word, then convert each word to the appropriate case as per the problem statement. Finally, join the words with spaces.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the string `title`." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2130, "explanations": { "1": "We can store the values of the nodes in the linked list into an array, then use two pointers pointing to the beginning and end of the array to calculate the twin sum for each pair of twin nodes. The maximum twin sum is the answer.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the number of nodes in the linked list.", "2": "时间复杂度 $O(n)$,空间复杂度 $O(1)$。" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2131, "explanations": { "1": "First, we use a hash table $\\textit{cnt}$ to count the occurrences of each word.\n\nIterate through each word $k$ and its count $v$ in $\\textit{cnt}$:\n\n- If the two letters in $k$ are the same, we can concatenate $\\left \\lfloor \\frac{v}{2} \\right \\rfloor \\times 2$ copies of $k$ to the front and back of the palindrome. If there is one $k$ left, we can record it in $x$ for now.\n\n- If the two letters in $k$ are different, we need to find a word $k'$ such that the two letters in $k'$ are the reverse of $k$, i.e., $k' = k[1] + k[0]$. If $k'$ exists, we can concatenate $\\min(v, \\textit{cnt}[k'])$ copies of $k$ to the front and back of the palindrome.\n\nAfter the iteration, if $x$ is not empty, we can also place one word in the middle of the palindrome.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of words." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2132, "explanations": { "1": "According to the problem description, every empty cell must be covered by a stamp, and no occupied cell can be covered. Therefore, we can traverse the two-dimensional matrix, and for each cell, if all cells in the area of $stampHeight \\times stampWidth$ with this cell as the upper left corner are empty (i.e., not occupied), then we can place a stamp at this cell.\n\nTo quickly determine whether all cells in an area are empty, we can use a two-dimensional prefix sum. We use $s_{i,j}$ to represent the number of occupied cells in the sub-matrix from $(1,1)$ to $(i,j)$ in the two-dimensional matrix. That is, $s_{i, j} = s_{i - 1, j} + s_{i, j - 1} - s_{i - 1, j - 1} + grid_{i-1, j-1}$.\n\nThen, with $(i, j)$ as the upper left corner, and the height and width are $stampHeight$ and $stampWidth$ respectively, the lower right coordinate of the sub-matrix is $(x, y) = (i + stampHeight - 1, j + stampWidth - 1)$. We can calculate the number of occupied cells in this sub-matrix through $s_{x, y} - s_{x, j - 1} - s_{i - 1, y} + s_{i - 1, j - 1}$. If the number of occupied cells in this sub-matrix is $0$, then we can place a stamp at $(i, j)$. After placing the stamp, all cells in this $stampHeight \\times stampWidth$ area will become occupied cells. We can use a two-dimensional difference array $d$ to record this change. That is:\n\n$$\n\\begin{aligned}\nd_{i, j} &\\leftarrow d_{i, j} + 1 \\\\\nd_{i, y + 1} &\\leftarrow d_{i, y + 1} - 1 \\\\\nd_{x + 1, j} &\\leftarrow d_{x + 1, j} - 1 \\\\\nd_{x + 1, y + 1} &\\leftarrow d_{x + 1, y + 1} + 1\n\\end{aligned}\n$$\n\nFinally, we perform a prefix sum operation on the two-dimensional difference array $d$ to find out the number of times each cell is covered by a stamp. If a cell is not occupied and the number of times it is covered by a stamp is $0$, then we cannot place a stamp at this cell, so we need to return $\\texttt{false}$. If all \"unoccupied cells\" are successfully covered by stamps, return $\\texttt{true}$.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the height and width of the two-dimensional matrix, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 2133, "explanations": { "1": "Traverse each row and column of the matrix, using a hash table to record whether each number has appeared. If any number appears more than once in a row or column, return `false`; otherwise, return `true`\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ is the size of the matrix." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 2134, "explanations": { "1": "First, we count the number of $1$s in the array, denoted as $k$. The problem is actually asking for a circular subarray of length $k$ that contains the maximum number of $1$s. Therefore, the minimum number of swaps is $k$ minus the maximum number of $1$s in that subarray.\n\nWe can solve this problem using a sliding window. First, we count the number of $1$s in the first $k$ elements of the array, denoted as $cnt$. Then, we maintain a sliding window of length $k$. Each time we move the window one position to the right, we update $cnt$ and simultaneously update the maximum $cnt$ value, i.e., $mx = \\max(mx, cnt)$. Finally, the answer is $k - mx$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$.", "2": "" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2135, "explanations": { "1": "We notice that the given strings only contain lowercase letters, and each letter in a string appears at most once. Therefore, we can represent a string with a binary number of length $26$, where the $i$-th bit being $1$ indicates that the string contains the $i$-th lowercase letter, and $0$ indicates the absence of the $i$-th lowercase letter.\n\nWe can convert each string in the array $\\textit{startWords}$ into a binary number and store these binary numbers in a set $\\textit{s}$. For each string in the array $\\textit{targetWords}$, we first convert it into a binary number, then enumerate each letter in this string, remove this letter from the binary number, and check if there exists a binary number in the set $\\textit{s}$ such that the XOR result of this binary number with the removed letter's binary number is in the set $\\textit{s}$. If such a binary number exists, then this string can be obtained by performing a transformation operation on some string in $\\textit{startWords}$, and we increment the answer by one. Then, we skip this string and continue processing the next string.\n\nThe time complexity is $O(n \\times |\\Sigma|)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string array $\\textit{targetWords}$, and $|\\Sigma|$ is the size of the character set in the string, which is $26$ in this problem." }, "is_english": true, "time_complexity": "O(n \\times |\\Sigma|)", "space_complexity": "O(n)" }, { "problem_id": 2136, "explanations": { "1": "According to the problem description, we know that only one seed can be planted per day. Therefore, regardless of the planting order, the sum of the planting times for all seeds is always equal to $\\sum_{i=0}^{n-1} plantTime[i]$. To make all seeds bloom as soon as possible, we should prioritize planting the seeds with the longest growth time. Hence, we can sort all seeds by their growth time in descending order and then plant them in sequence.\n\nThe time complexity is $O(n \\log n)$, and the space complexity is $O(n)$, where $n$ is the number of seeds." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2137, "explanations": { "1": "We notice that if a water volume $x$ meets the condition, then all water volumes less than $x$ also meet the condition. Therefore, we can use binary search to find the maximum water volume that satisfies the condition.\n\nWe define the left boundary of the binary search as $l=0$ and the right boundary as $r=\\max(buckets)$. During each binary search iteration, we take the midpoint $mid$ of $l$ and $r$, and check if $mid$ meets the condition. If it does, we update $l$ to $mid$; otherwise, we update $r$ to $mid$. After the binary search concludes, the maximum water volume that satisfies the condition is $l$.\n\nThe key to the problem is to determine if a water volume $v$ meets the condition. We can iterate through all buckets, and for each bucket, if its water volume is greater than $v$, then we need to pour out $x-v$ water volume; if its water volume is less than $v$, then we need to pour in $(v-x)\\times\\frac{100}{100-\\textit{loss}}$ water volume. If the total volume poured out is greater than or equal to the volume poured in, then $v$ meets the condition.\n\nThe time complexity is $O(n \\times \\log M)$, where $n$ and $M$ are the length and the maximum value of the array $buckets$, respectively. The time complexity of binary search is $O(\\log M)$, and each binary search iteration requires traversing the array $buckets$, with a time complexity of $O(n)$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(1)" }, { "problem_id": 2138, "explanations": { "1": "We can directly simulate the process described in the problem statement, dividing the string $s$ into groups of length $k$. For the last group, if it contains fewer than $k$ characters, we use the character $\\textit{fill}$ to pad it.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2139, "explanations": { "1": "Let's start by backtracking from the final state. Assuming the final state is $target$, we can get the previous state of $target$ as $target - 1$ or $target / 2$, depending on the parity of $target$ and the value of $maxDoubles$.\n\nIf $target=1$, no operation is needed, and we can return $0$ directly.\n\nIf $maxDoubles=0$, we can only use the increment operation, so we need $target-1$ operations.\n\nIf $target$ is even and $maxDoubles>0$, we can use the doubling operation, so we need $1$ operation, and then recursively solve $target/2$ and $maxDoubles-1$.\n\nIf $target$ is odd, we can only use the increment operation, so we need $1$ operation, and then recursively solve $target-1$ and $maxDoubles$.\n\nThe time complexity is $O(\\min(\\log target, maxDoubles))$, and the space complexity is $O(\\min(\\log target, maxDoubles))$.\n\nWe can also change the above process to an iterative way to avoid the space overhead of recursion.", "2": "" }, "is_english": true, "time_complexity": "O(\\min(\\log target, maxDoubles))", "space_complexity": "O(\\min(\\log target, maxDoubles))" }, { "problem_id": 2140, "explanations": { "1": "We design a function $\\textit{dfs}(i)$, which represents the maximum score that can be obtained starting from the $i$-th question. The answer is $\\textit{dfs}(0)$.\n\nThe function $\\textit{dfs}(i)$ is calculated as follows:\n\n- If $i \\geq n$, it means all questions have been solved, so return $0$;\n- Otherwise, let the score of the $i$-th question be $p$, and the number of questions to skip be $b$. Then, $\\textit{dfs}(i) = \\max(p + \\textit{dfs}(i + b + 1), \\textit{dfs}(i + 1))$.\n\nTo avoid repeated calculations, we can use memoization by storing the values of $\\textit{dfs}(i)$ in an array $f$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of questions.", "2": "We define $f[i]$ as the maximum score that can be obtained starting from the $i$-th problem. Therefore, the answer is $f[0]$.\n\nConsidering $f[i]$, let the score of the $i$-th problem be $p$, and the number of problems to skip be $b$. If we solve the $i$-th problem, then we need to solve the problem after skipping $b$ problems, thus $f[i] = p + f[i + b + 1]$. If we skip the $i$-th problem, then we start solving from the $(i + 1)$-th problem, thus $f[i] = f[i + 1]$. We take the maximum value of the two. The state transition equation is as follows:\n\n$$\nf[i] = \\max(p + f[i + b + 1], f[i + 1])\n$$\n\nWe calculate the values of $f$ from back to front, and finally return $f[0]$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of problems." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2141, "explanations": { "1": "We notice that if we can run $n$ computers simultaneously for $t$ minutes, then we can also run $n$ computers simultaneously for $t' \\le t$ minutes, which shows monotonicity. Therefore, we can use the binary search method to find the maximum $t$.\n\nWe define the left boundary of the binary search as $l=0$ and the right boundary as $r=\\sum_{i=0}^{n-1} batteries[i]$. During each binary search iteration, we use a variable $mid$ to represent the current middle value, i.e., $mid = (l + r + 1) >> 1$. We check if there exists a scheme that allows $n$ computers to run simultaneously for $mid$ minutes. If such a scheme exists, then we update $l$ to $mid$; otherwise, we update $r$ to $mid - 1$. Finally, we return $l$ as the answer.\n\nThe problem is transformed into how to determine if there exists a scheme that allows $n$ computers to run simultaneously for $mid$ minutes. If a battery can run for more minutes than $mid$, since the computers run simultaneously for $mid$ minutes and a battery can only power one computer at a time, we can only use this battery for $mid$ minutes. If a battery can run for minutes less than or equal to $mid$, we can use all the power of this battery. Therefore, we calculate the total minutes $s$ that all batteries can power, and if $s \\ge n \\times mid$, then we can make $n$ computers run simultaneously for $mid$ minutes.\n\nThe time complexity is $O(n \\times \\log M)$, where $M$ is the total power of all batteries, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(1)" }, { "problem_id": 2142, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2143, "explanations": { "1": "我们定义 $f[i][j]$ 表示以第 $i$ 个元素结尾,且从 $nums1$ 中选取的数字和与从 $nums2$ 中选取的数字和之差为 $j$ 的平衡区间的个数。由于差值可能为负数,因此,我们统一将 $j$ 加上 $s_2 = \\sum_{k=0}^{n-1}nums2[k]$,这样就可以保证 $j$ 为非负整数。\n\n考虑 $f[i][j]$,我们可以单独将第 $i$ 个元素视为一个区间,那么 $f[i][nums1[i] + s_2]$ 和 $f[i][-nums2[i] + s_2]$ 都会增加 $1$。此外,如果 $i \\gt 0$,我们也可以将第 $i$ 个元素添加到前面的某个区间中,我们在 $[0, s_1 + s_2]$ 范围内枚举 $j$,如果 $j \\geq a$,那么 $f[i][j]$ 会增加 $f[i - 1][j - a]$,如果 $j + b \\leq s_1 + s_2$,那么 $f[i][j]$ 会增加 $f[i - 1][j + b]$。\n\n答案为 $\\sum_{i=0}^{n-1}f[i][s_2]$。\n\n时间复杂度 $O(n \\times M)$,空间复杂度 $O(n \\times M)$。其中 $n$ 和 $M$ 分别为数组 $nums1$ 的长度以及数字和的最大值。" }, "is_english": false, "time_complexity": "O(n \\times M)", "space_complexity": "O(n \\times M)" }, { "problem_id": 2144, "explanations": { "1": "We can first sort the candies by price in descending order, then for every three candies, we take two. This ensures that the candies we get for free are the most expensive, thereby minimizing the total cost.\n\nThe time complexity is $O(n \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the number of candies." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 2145, "explanations": { "1": "Since the array $\\textit{differences}$ is already determined, the difference between the maximum and minimum values of the elements in the array $\\textit{hidden}$ is also fixed. We just need to ensure that this difference does not exceed $\\textit{upper} - \\textit{lower}$.\n\nLet's assume the first element of the array $\\textit{hidden}$ is $0$. Then, $\\textit{hidden}[i] = \\textit{hidden}[i - 1] + \\textit{differences}[i - 1]$, where $1 \\leq i \\leq n$. Let the maximum value of the array $\\textit{hidden}$ be $mx$ and the minimum value be $mi$. If $mx - mi \\leq \\textit{upper} - \\textit{lower}$, then we can construct a valid $\\textit{hidden}$ array. The number of possible constructions is $\\textit{upper} - \\textit{lower} - (mx - mi) + 1$. Otherwise, it is impossible to construct a valid $\\textit{hidden}$ array, and we return $0$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{differences}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2146, "explanations": { "1": "We can start from $(\\textit{row}, \\textit{col})$ and use breadth-first search to find all items with prices in the range $[\\textit{low}, \\textit{high}]$. Store the distance, price, row coordinate, and column coordinate of these items in the array $\\textit{pq}$.\n\nFinally, sort $\\textit{pq}$ by distance, price, row coordinate, and column coordinate, and return the coordinates of the first $k$ items.\n\nThe time complexity is $O(m \\times n \\times \\log (m \\times n))$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the number of rows and columns of the 2D array $\\textit{grid}$, respectively." }, "is_english": true, "time_complexity": "O(m \\times n \\times \\log (m \\times n))", "space_complexity": "O(m \\times n)" }, { "problem_id": 2147, "explanations": { "1": "We design a function $\\textit{dfs}(i, k)$, which represents the number of ways to partition the corridor at the $i$-th position, having already placed $k$ screens. Then the answer is $\\textit{dfs}(0, 0)$.\n\nThe calculation process of the function $\\textit{dfs}(i, k)$ is as follows:\n\nIf $i \\geq \\textit{len}(\\textit{corridor})$, it means the corridor has been fully traversed. At this point, if $k = 2$, it indicates that a valid partitioning scheme has been found, so return $1$. Otherwise, return $0$.\n\nOtherwise, we need to consider the situation at the current position $i$:\n\n- If $\\textit{corridor}[i] = \\text{'S'}$, it means the current position is a seat, and we increment $k$ by $1$.\n- If $k > 2$, it means the number of screens placed at the current position exceeds $2$, so return $0$.\n- Otherwise, we can choose not to place a screen, i.e., $\\textit{dfs}(i + 1, k)$. If $k = 2$, we can also choose to place a screen, i.e., $\\textit{dfs}(i + 1, 0)$. We add the results of these two cases and take the result modulo $10^9 + 7$, i.e., $\\textit{ans} = (\\textit{ans} + \\textit{dfs}(i + 1, k)) \\bmod \\text{mod}$.\n\nFinally, we return $\\textit{dfs}(0, 0)$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the corridor.", "2": "We can divide every two seats into a group. Between two adjacent groups of seats, if the distance between the last seat of the previous group and the first seat of the next group is $x$, then there are $x$ ways to place the screen.\n\nWe traverse the corridor, using a variable $\\textit{cnt}$ to record the current number of seats, and a variable $\\textit{last}$ to record the position of the last seat.\n\nWhen we encounter a seat, we increment $\\textit{cnt}$ by $1$. If $\\textit{cnt}$ is greater than $2$ and $\\textit{cnt}$ is odd, then we need to place a screen between $\\textit{last}$ and the current seat. The number of ways to do this is $\\textit{ans} \\times (i - \\textit{last})$, where $\\textit{ans}$ is the previous number of ways. Then, we update $\\textit{last}$ to the current seat's position $i$.\n\nFinally, if $\\textit{cnt}$ is greater than $0$ and $\\textit{cnt}$ is even, return $\\textit{ans}$; otherwise, return $0$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the corridor. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2148, "explanations": { "1": "According to the problem description, we can first find the minimum value $\\textit{mi}$ and the maximum value $\\textit{mx}$ of the array $\\textit{nums}$. Then, traverse the array $\\textit{nums}$ and count the number of elements that satisfy $\\textit{mi} < x < \\textit{mx}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2149, "explanations": { "1": "First, we create an array $\\textit{ans}$ of length $n$. Then, we use two pointers $i$ and $j$ to point to the even and odd indices of $\\textit{ans}$, respectively, with initial values $i = 0$, $j = 1$.\n\nWe iterate through the array $\\textit{nums}$. If the current element $x$ is a positive integer, then we place $x$ into $\\textit{ans}[i]$ and increase $i$ by $2$; otherwise, we place $x$ into $\\textit{ans}[j]$ and increase $j$ by $2$.\n\nFinally, we return $\\textit{ans}$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2150, "explanations": { "1": "We use a hash table $\\textit{cnt}$ to record the occurrence count of each number. Then, we iterate through the hash table. For each number and its occurrence count $(x, v)$, if $v = 1$ and $\\textit{cnt}[x - 1] = 0$ and $\\textit{cnt}[x + 1] = 0$, then $x$ is a lonely number, and we add it to the answer array.\n\nAfter finishing the iteration, we return the answer array.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2151, "explanations": { "1": "二进制枚举好人的状态 $mask$,由于“好人只说真话”,我们借此判断 $statements$ 与 $mask$ 是否存在矛盾,不存在则获取 $mask$ 中好人的数量 $cnt$。迭代获取最大的合法 $cnt$。\n\n时间复杂度 $O(2^n*n^2)$,其中 $n$ 表示 $statements$ 的长度。" }, "is_english": false, "time_complexity": "O(2^n*n^2)", "space_complexity": null }, { "problem_id": 2152, "explanations": { "1": "我们可以用一个整数 `state` 来表示当前已经添加的直线,其中 `state` 的第 $i$ 位表示第 $i$ 条直线是否已经添加。如果 `state` 的第 $i$ 位为 $1$,则表示第 $i$ 条直线已经添加,否则表示第 $i$ 条直线还未添加。\n\n接下来,我们设计一个函数 $dfs(state)$,表示当前已经添加的直线为 `state` 时,至少需要添加多少条直线才能使得每个点至少在一条直线上。那么答案就是 $dfs(0)$。\n\n函数 $dfs(state)$ 的计算过程如下:\n\n- 如果 `state` 的所有位都为 $1$,则说明所有直线都已经添加,返回 $0$。\n- 否则,我们枚举当前还未添加的点 $i$,接下来枚举 $j$,我们将 $i$ 和 $j$ 的点连成一条直线,此时的状态为 $nxt = state | 1 << i | 1 << j$,其中 $1 << i$ 表示将第 $i$ 位设置为 $1$,$1 << j$ 表示将第 $j$ 位设置为 $1$。接下来,我们枚举所有 $k$,如果 $i$、$j$ 和 $k$ 三个点共线,则将 $k$ 的状态设置为 $1$,即 $nxt = nxt | 1 << k$。此时,我们可以将 $i$ 和 $j$ 以及 $k$ 这三个点连成一条直线,此时的状态为 $nxt$,此时至少需要添加 $dfs(nxt)$ 条直线,我们取所有情况的最小值,即为 $dfs(state)$ 的值。\n\n为了避免重复计算,我们可以使用记忆化搜索。\n\n时间复杂度 $O(2^n \\times n^3)$,空间复杂度 $O(2^n)$。其中 $n$ 为点的数量。" }, "is_english": false, "time_complexity": "O(2^n \\times n^3)", "space_complexity": "O(2^n)" }, { "problem_id": 2153, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2154, "explanations": { "1": "We use a hash table $\\textit{s}$ to record all the numbers in the array $\\textit{nums}$.\n\nNext, starting from $\\textit{original}$, if $\\textit{original}$ is in $\\textit{s}$, we multiply $\\textit{original}$ by $2$ until $\\textit{original}$ is not in $\\textit{s}$ anymore, then return $\\textit{original}$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2155, "explanations": { "1": "We start from $i = 0$, using two variables $\\textit{l0}$ and $\\textit{r1}$ to respectively record the number of $1$s to the left and right of $i$. Initially, $\\textit{l0} = 0$, while $\\textit{r1} = \\sum \\textit{nums}$.\n\nWe iterate through the array $\\textit{nums}$. For each $i$, we update $\\textit{l0}$ and $\\textit{r1}$, calculate the current grouping score $t = \\textit{l0} + \\textit{r1}$. If $t$ equals the current maximum grouping score $\\textit{mx}$, then we add $i$ to the answer array. If $t$ is greater than $\\textit{mx}$, we update $\\textit{mx}$ to $t$, clear the answer array, and then add $i$ to the answer array.\n\nAfter the iteration ends, we return the answer array.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2156, "explanations": { "1": "We can maintain a sliding window of length $k$ to calculate the hash value of the substring. Considering that if we traverse the string in the forward order, the calculation of the hash value involves division and modulo operations, which are relatively complicated to handle. Therefore, we can traverse the string in reverse order, so that when calculating the hash value, only multiplication and modulo operations are needed.\n\nFirst, we calculate the hash value of the last $k$ characters of the string, and then start to traverse the string in reverse order from the end of the string. Each time we calculate the hash value of the current window, if it is equal to the given hash value, we find a substring that meets the conditions and update the starting position of the answer string.\n\nFinally, return the answer string.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2157, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2158, "explanations": { "1": "线段树将整个区间分割为多个不连续的子区间,子区间的数量不超过 `log(width)`。更新某个元素的值,只需要更新 `log(width)` 个区间,并且这些区间都包含在一个包含该元素的大区间内。区间修改时,需要使用**懒标记**保证效率。\n\n- 线段树的每个节点代表一个区间;\n- 线段树具有唯一的根节点,代表的区间是整个统计范围,如 `[1, N]`;\n- 线段树的每个叶子节点代表一个长度为 1 的元区间 `[x, x]`;\n- 对于每个内部节点 `[l, r]`,它的左儿子是 `[l, mid]`,右儿子是 `[mid + 1, r]`, 其中 `mid = ⌊(l + r) / 2⌋` (即向下取整)。\n\n对于本题,线段树节点维护的信息有:\n\n1. 区间中元素大于 0 的个数 v\n1. 懒标记 add" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2159, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2160, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2161, "explanations": { "1": "We can traverse the array $\\textit{nums}$, sequentially finding all elements less than $\\textit{pivot}$, all elements equal to $\\textit{pivot}$, and all elements greater than $\\textit{pivot}$, then concatenate them in the order required by the problem.\n\nTime complexity $O(n)$, where $n$ is the length of the array $\\textit{nums}$. Ignoring the space consumption of the answer array, the space complexity is $O(1)$.", "2": "" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2162, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2163, "explanations": { "1": "The problem is essentially equivalent to finding a split point in $nums$, dividing the array into two parts. In the first part, select the smallest $n$ elements, and in the second part, select the largest $n$ elements, so that the difference between the sums of the two parts is minimized.\n\nWe can use a max heap to maintain the smallest $n$ elements in the prefix, and a min heap to maintain the largest $n$ elements in the suffix. We define $pre[i]$ as the sum of the smallest $n$ elements among the first $i$ elements of the array $nums$, and $suf[i]$ as the sum of the largest $n$ elements from the $i$-th element to the last element of the array. During the process of maintaining the max and min heaps, update the values of $pre[i]$ and $suf[i]$.\n\nFinally, we enumerate the split points in the range of $i \\in [n, 2n]$, calculate the value of $pre[i] - suf[i + 1]$, and take the minimum value.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2164, "explanations": { "1": "We can extract the elements at odd and even indices separately, then sort the array of odd indices in non-increasing order and the array of even indices in non-decreasing order. Finally, merge the two arrays back together.\n\nThe time complexity is $O(n \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2165, "explanations": { "1": "We first use an array $\\textit{cnt}$ to record the number of occurrences of each digit in $\\textit{num}$.\n\nIf $\\textit{num}$ is negative, the digits should be arranged in descending order. Therefore, we traverse $\\textit{cnt}$ from $9$ to $0$ and arrange the digits in descending order according to their occurrences.\n\nIf $\\textit{num}$ is positive, we first find the first non-zero digit and place it in the first position, then arrange the remaining digits in ascending order.\n\nThe time complexity is $O(\\log n)$, where $n$ is the size of the number $\\textit{num}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 2166, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2167, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2168, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2169, "explanations": { "1": "We can directly simulate this process by repeatedly performing the following operations:\n\n- If $\\textit{num1} \\ge \\textit{num2}$, then $\\textit{num1} = \\textit{num1} - \\textit{num2}$;\n- Otherwise, $\\textit{num2} = \\textit{num2} - \\textit{num1}$.\n- Each time an operation is performed, increment the operation count by one.\n\nWhen either $\\textit{num1}$ or $\\textit{num2}$ becomes $0$, stop the loop and return the operation count.\n\nThe time complexity is $O(m)$, where $m$ is the maximum of $\\textit{num1}$ and $\\textit{num2}$. The space complexity is $O(1)$.", "2": "Following the simulation process in Solution 1, we notice that if $\\textit{num1}$ is much larger than $\\textit{num2}$, each operation will only reduce the value of $\\textit{num1}$ slightly, leading to an excessive number of operations. We can optimize this process by directly adding the quotient of $\\textit{num1}$ divided by $\\textit{num2}$ to the answer in each operation, then taking the remainder of $\\textit{num1}$ divided by $\\textit{num2}$. This reduces the number of operations.\n\nThe time complexity is $O(\\log m)$, where $m$ is the maximum of $\\textit{num1}$ and $\\textit{num2}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m)", "space_complexity": "O(1)" }, { "problem_id": 2170, "explanations": { "1": "According to the problem description, if an array $\\textit{nums}$ is an alternating array, then the elements at odd positions and even positions must be different, and the elements at odd positions are the same, as well as the elements at even positions.\n\nTo minimize the number of operations required to transform the array $\\textit{nums}$ into an alternating array, we can count the occurrence of elements at odd and even positions. We find the two elements with the highest occurrence at even positions, $a_0$ and $a_2$, and their corresponding counts $a_1$ and $a_3$; similarly, we find the two elements with the highest occurrence at odd positions, $b_0$ and $b_2$, and their corresponding counts $b_1$ and $b_3$.\n\nIf $a_0 \\neq b_0$, then we can change all elements at even positions in the array $\\textit{nums}$ to $a_0$ and all elements at odd positions to $b_0$, making the number of operations $n - (a_1 + b_1)$; if $a_0 = b_0$, then we can change all elements at even positions in the array $\\textit{nums}$ to $a_0$ and all elements at odd positions to $b_2$, or change all elements at even positions to $a_2$ and all elements at odd positions to $b_0$, making the number of operations $n - \\max(a_1 + b_3, a_3 + b_1)$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2171, "explanations": { "1": "We can sort all the beans in the bags in ascending order, and then enumerate the number of beans $beans[i]$ in each bag as the final number of beans in the bag. The total remaining number of beans is $beans[i] \\times (n - i)$, so the number of beans that need to be taken out is $s - beans[i] \\times (n - i)$, where $s$ is the total number of beans in all bags. We need to find the minimum number of beans that need to be taken out among all schemes.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the number of bags." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 2172, "explanations": { "1": "由于每个篮子最多只能放两个数,我们不妨将篮子数乘以 $2$,这样每个篮子最多只能放一个数。\n\n接下来,我们定义 $f[i]$ 表示篮子状态为 $i$ 时的最大与和,其中 $i$ 是一个二进制数,表示每个篮子是否放了数。初始时 $f[0]=0$。\n\n接下来,我们考虑 $f[i]$ 如何进行状态转移。\n\n我们可以枚举 $i$,记 $i$ 的二进制表示中 $1$ 的个数为 $cnt$。如果 $cnt \\gt n$,那么 $i$ 不是一个合法的状态,我们可以直接跳过。否则,我们可以枚举 $i$ 的二进制表示中的每一位 $j$,如果 $i$ 的第 $j$ 位为 $1$,那么我们可以将第 $(cnt-1)$ 个数 $nums[cnt-1]$ 放入第 $j$ 个篮子中,此时有:\n\n$$\nf[i] = \\max\\{f[i], f[i \\oplus (1 << j)] + (nums[cnt-1] \\wedge (j / 2 + 1))\\}\n$$\n\n其中 $\\oplus$ 表示异或运算,而 $\\wedge$ 表示按位与运算。\n\n答案为 $\\max\\{f[i]\\}$。\n\n时间复杂度 $O(4^k \\times k \\times 2)$,空间复杂度 $O(4^k)$。其中 $k$ 表示篮子的数量,即题目中的 $numSlots$。" }, "is_english": false, "time_complexity": "O(4^k \\times k \\times 2)", "space_complexity": "O(4^k)" }, { "problem_id": 2173, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2174, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2175, "explanations": { "1": "利用 `rank()` 函数求出新老排名,然后用 `CAST` 将字段类型改为 `signed`,保证两个排名可以进行减法操作。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2176, "explanations": { "1": "We first enumerate the index $j$ in the range $[0, n)$, and then enumerate the index $i$ in the range $[0, j)$. We count the number of pairs that satisfy $\\textit{nums}[i] = \\textit{nums}[j]$ and $(i \\times j) \\bmod k = 0$.\n\nThe time complexity is $O(n^2)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(1)" }, { "problem_id": 2177, "explanations": { "1": "Assume the three consecutive integers are $x-1$, $x$, and $x+1$. Their sum is $3x$, so $\\textit{num}$ must be a multiple of $3$. If $\\textit{num}$ is not a multiple of $3$, it cannot be represented as the sum of three consecutive integers, and we return an empty array. Otherwise, let $x = \\frac{\\textit{num}}{3}$, then $x-1$, $x$, and $x+1$ are the three consecutive integers whose sum is $\\textit{num}$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 2178, "explanations": { "1": "If $\\textit{finalSum}$ is odd, it cannot be split into the sum of several distinct positive even integers, so we directly return an empty array.\n\nOtherwise, we can greedily split $\\textit{finalSum}$ in the order of $2, 4, 6, \\cdots$, until $\\textit{finalSum}$ can no longer be split into a different positive even integer. At this point, we add the remaining $\\textit{finalSum}$ to the last positive even integer.\n\nThe time complexity is $O(\\sqrt{\\textit{finalSum}})$, and ignoring the space consumption of the answer array, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\sqrt{\\textit{finalSum}})", "space_complexity": "O(1)" }, { "problem_id": 2179, "explanations": { "1": "For this problem, we first use `pos` to record the position of each number in `nums2`, and then process each element in `nums1` sequentially.\n\nConsider the number of good triplets **with the current number as the middle number**. The first number must have already been traversed and must appear earlier than the current number in `nums2`. The third number must not yet have been traversed and must appear later than the current number in `nums2`.\n\nTake `nums1 = [4,0,1,3,2]` and `nums2 = [4,1,0,2,3]` as an example. Consider the traversal process:\n\n1. First, process `4`. At this point, the state of `nums2` is `[4,X,X,X,X]`. The number of values before `4` is `0`, and the number of values after `4` is `4`. Therefore, `4` as the middle number forms `0` good triplets.\n2. Next, process `0`. The state of `nums2` becomes `[4,X,0,X,X]`. The number of values before `0` is `1`, and the number of values after `0` is `2`. Therefore, `0` as the middle number forms `2` good triplets.\n3. Next, process `1`. The state of `nums2` becomes `[4,1,0,X,X]`. The number of values before `1` is `1`, and the number of values after `1` is `2`. Therefore, `1` as the middle number forms `2` good triplets.\n4. ...\n5. Finally, process `2`. The state of `nums2` becomes `[4,1,0,2,3]`. The number of values before `2` is `4`, and the number of values after `2` is `0`. Therefore, `2` as the middle number forms `0` good triplets.\n\nWe can use a **Binary Indexed Tree (Fenwick Tree)** to update the occurrence of numbers at each position in `nums2`, and quickly calculate the number of `1`s to the left of each number and the number of `0`s to the right of each number.\n\nA Binary Indexed Tree, also known as a Fenwick Tree, efficiently supports the following operations:\n\n1. **Point Update** `update(x, delta)`: Add a value `delta` to the number at position `x` in the sequence.\n2. **Prefix Sum Query** `query(x)`: Query the sum of the sequence in the range `[1, ..., x]`, i.e., the prefix sum at position `x`.\n\nBoth operations have a time complexity of $O(\\log n)$. Therefore, the overall time complexity is $O(n \\log n)$, where $n$ is the length of the array $\\textit{nums1}$. The space complexity is $O(n)$.", "2": "We can also use a segment tree to solve this problem. A segment tree is a data structure that efficiently supports range queries and updates. The basic idea is to divide an interval into multiple subintervals, with each subinterval represented by a node.\n\nThe segment tree divides the entire interval into multiple non-overlapping subintervals, with the number of subintervals not exceeding `log(width)`. To update the value of an element, we only need to update `log(width)` intervals, all of which are contained within a larger interval that includes the element.\n\n- Each node of the segment tree represents an interval.\n- The segment tree has a unique root node, representing the entire range, such as `[1, N]`.\n- Each leaf node of the segment tree represents a unit interval `[x, x]`.\n- For each internal node `[l, r]`, its left child represents `[l, mid]`, and its right child represents `[mid + 1, r]`, where `mid = ⌊(l + r) / 2⌋` (floor division).\n\nThe time complexity is $O(n \\log n)$, where $n$ is the length of the array $\\textit{nums1}$. The space complexity is $O(n)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(n)" }, { "problem_id": 2180, "explanations": { "1": "一种最简单直接的方法是枚举 $[1,..num]$ 的所有整数 $x$,判断 $x$ 各位数字之和是否为偶数,是则答案加一。\n\n时间复杂度 $O(n \\times \\log n)$,空间复杂度 $O(1)$。其中 $n$ 为 $num$ 的值。", "2": "我们观察发现,在 $[0,..x]$ 的所有数中,每 $10$ 个数中,就有 $5$ 个数的各位数字之和为偶数。例如,在 $[0,..9]$ 中,每 $10$ 个数中,就有 $5$ 个数的各位数字之和为偶数,分别是 $0,2,4,6,8$。\n\n因此,我们可以先算出 $num$ 中有多少个 $10$ 的倍数,然后乘以 $5$ 再减去 $1$(排除 $0$ 这个偶数),可以得到初始答案 $ans=\\left\\lfloor \\frac{num}{10} \\right\\rfloor \\times 5 - 1$。\n\n接下来,我们还需要考虑剩下的 $num \\% 10 + 1$ 个数字中,有多少个数的各位数字之和为偶数。这些数字是否是偶数,跟数字的前面数字之和有关,因此,我们可以算出 $num$ 的前面数字之和 $s$,那么剩余的数字中,还有 $\\left\\lfloor \\frac{num \\% 10 + 2 - (s \\& 1)}{2} \\right\\rfloor$ 个数的各位数字之和为偶数。累加到答案 $ans$ 中即可。\n\n我们不妨举个例子,假设 $num$ 为 $123$,那么前面 $[0,..119]$ 中一共有 $12$ 个 $10$ 的倍数,每个 $10$ 的倍数中有 $5$ 个数的各位数字之和为偶数,因此,初始答案为 $ans=12 \\times 5 - 1=59$。\n\n剩下的数字分别是 $120,121,122,123$,每个数字的前两位数字之和为 $s = 1+2=3$,是奇数,因此,剩下的数字中,只有 $2$ 个数的各位数字之和为偶数,累加到答案 $ans$ 中,最终答案为 $ans+2=61$。\n\n时间复杂度 $O(\\log n)$,空间复杂度 $O(1)$。其中 $n$ 为 $num$ 的值。" }, "is_english": false, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(1)" }, { "problem_id": 2181, "explanations": { "1": "We define a dummy head node $\\textit{dummy}$, a pointer $\\textit{tail}$ pointing to the current node, and a variable $\\textit{s}$ to record the sum of the values of the current nodes.\n\nNext, we traverse the linked list starting from the second node. If the value of the current node is not 0, we add it to $\\textit{s}$. Otherwise, we add $\\textit{s}$ to the node after $\\textit{tail}$, set $\\textit{s}$ to 0, and update $\\textit{tail}$ to the next node.\n\nFinally, we return the node next to $\\textit{dummy}$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the linked list." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2182, "explanations": { "1": "First, we use an array $cnt$ of length $26$ to count the number of occurrences of each character in string $s$. Then, we enumerate the $i$th letter of the alphabet in descending order, each time taking out at most $\\min(cnt[i], repeatLimit)$ of letter $i$. If after taking them out $cnt[i]$ is still greater than $0$, we continue to take the $j$th letter of the alphabet, where $j$ is the largest index satisfying $j < i$ and $cnt[j] > 0$, until all letters are taken.\n\nThe time complexity is $O(n + |\\Sigma|)$, and the space complexity is $O(|\\Sigma|)$. Here, $n$ is the length of string $s$, and $\\Sigma$ is the character set. In this problem, $|\\Sigma| = 26$." }, "is_english": true, "time_complexity": "O(n + |\\Sigma|)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 2183, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2184, "explanations": { "1": "首先通过 DFS 构造出所有合法的排列。然后所有排列进行两两比较,找出每种排列相邻的合法排列,记录在 `g` 数组中。\n\n然后进行动态规划。\n\n过程是这样的:计算以某种排列结束的所有方案数。\n\n初始化第一排每种排列的方案数为 1;每一排选取某种排列的总方案数为上一排能与自己相邻的排列的方案数之和。\n\n答案为最后一排的方案数之和。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2185, "explanations": { "1": "根据题目描述,我们遍历字符串数组 `words` 中的每个字符串 $w$,判断其是否以 $pref$ 作为前缀,如果是,则答案加一。\n\n时间复杂度 $O(n \\times m)$,空间复杂度 $O(1)$。其中 $n$ 和 $m$ 分别是字符串数组 `words` 和字符串 $pref$ 的长度。", "2": "我们还可以使用前缀树来查询答案。\n\n定义前缀树的每个节点结构如下:\n\n- `children`:长度为 $26$ 的数组,用于存储当前节点的所有子节点,其中 `children[i]` 表示当前节点的子节点;\n- `cnt`:所有以当前节点为前缀的字符串的数量。\n\n另外,我们还需要定义两个函数:\n\n- 其中一个函数 $insert(w)$ 用于将字符串 $w$ 插入前缀树中;\n- 另一个函数 $search(pref)$ 用于查询以字符串 $pref$ 作为前缀的字符串的数量。查询时,我们从前缀树的根节点开始,遍历字符串 $pref$,如果当前节点的子节点中不存在 $pref[i]$,则说明 $pref$ 不是任何字符串的前缀,直接返回 $0$。否则,我们继续遍历 $pref$ 的下一个字符,直到遍历完 $pref$,返回当前节点的 `cnt` 即可。\n\n有了上述函数,我们就可以查询答案了。\n\n遍历字符串数组 `words`,对于每个字符串 $w$,调用 $insert(w)$ 函数将其插入前缀树中。最后调用 $search(pref)$ 函数作为答案返回即可。\n\n时间复杂度 $O(L)$,空间复杂度 $O(L)$。其中 $L$ 是字符串数组 `words` 中所有字符串的长度之和。" }, "is_english": false, "time_complexity": "O(n \\times m)", "space_complexity": "O(1)" }, { "problem_id": 2186, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2187, "explanations": { "1": "We notice that if we can complete at least $totalTrips$ trips in $t$ time, then we can also complete at least $totalTrips$ trips in $t' > t$ time. Therefore, we can use the method of binary search to find the smallest $t$.\n\nWe define the left boundary of the binary search as $l = 1$, and the right boundary as $r = \\min(time) \\times totalTrips$. For each binary search, we calculate the middle value $\\textit{mid} = \\frac{l + r}{2}$, and then calculate the number of trips that can be completed in $\\textit{mid}$ time. If this number is greater than or equal to $totalTrips$, then we reduce the right boundary to $\\textit{mid}$, otherwise we increase the left boundary to $\\textit{mid} + 1$.\n\nFinally, return the left boundary.\n\nThe time complexity is $O(n \\times \\log(m \\times k))$, where $n$ and $k$ are the length of the array $time$ and $totalTrips$ respectively, and $m$ is the minimum value in the array $time$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\log(m \\times k))", "space_complexity": "O(1)" }, { "problem_id": 2188, "explanations": { "1": "我们注意到,连续使用同一个轮胎 $(f, r)$ 跑 $i$ 圈,那么第 $i$ 圈的耗时不应该超过 $changeTime + f$,否则我们可以在第 $i$ 圈的时候换轮胎,这样总耗时会更少。即:\n\n$$\nf \\times r^{i-1} \\leq changeTime + f\n$$\n\n我们可以求出满足上式的最大的 $i$,要使得 $i$ 最大,那么 $f$ 和 $r$ 应该尽可能小,根据题目的数据范围,我们取 $f=1$, $r=2$,那么 $2^{i-1} \\leq changeTime + 1$,即 $i \\leq \\log_2(changeTime + 1) + 1$。根据这个结论,以及题目中 $changeTime$ 的数据范围,我们可以知道 $i$ 最大为 $17$。\n\n我们定义 $cost[i]$ 表示使用同一个轮胎跑 $i$ 圈的最小耗时,那么我们可以预处理出 $cost$ 数组,然后使用动态规划求解即可。定义 $f[i]$ 表示跑 $i$ 圈的最小耗时,那么我们可以得到状态转移方程:\n\n$$\nf[i] = (\\min_{1 \\leq j \\leq \\min(17, i)} f[i-j] + cost[j]) + changeTime\n$$\n\n初始时 $f[0] = -changeTime$,最终答案为 $f[numLaps]$。\n\n时间复杂度 $O((n + numLaps) \\times \\log T_{max})$,空间复杂度 $O(n + \\log T_{max})$,其中 $T_{max}$ 是题目中 $f_i$, $r_i$ 和 $changeTime$ 的最大值。本题中 $\\log T_{max} \\approx 17$。" }, "is_english": false, "time_complexity": "O((n + numLaps) \\times \\log T_{max})", "space_complexity": "O(n + \\log T_{max})" }, { "problem_id": 2189, "explanations": { "1": "We notice that the number of cards in each layer is $3 \\times k + 2$, and the number of cards in each layer is different. Therefore, the problem can be transformed into: how many ways can the integer $n$ be expressed as the sum of numbers of the form $3 \\times k + 2$. This is a classic knapsack problem that can be solved using memoization search.\n\nWe design a function $\\text{dfs}(n, k)$, which represents the number of ways to build different houses of cards when the remaining number of cards is $n$ and the current layer is $k$. The answer is $\\text{dfs}(n, 0)$.\n\nThe execution logic of the function $\\text{dfs}(n, k)$ is as follows:\n\n- If $3 \\times k + 2 \\gt n$, then the current layer cannot place any cards, return $0$;\n- If $3 \\times k + 2 = n$, then the current layer can place cards, and after placing them, the entire house of cards is completed, return $1$;\n- Otherwise, we can choose not to place cards or to place cards. If we choose not to place cards, the remaining number of cards does not change, and the number of layers increases by $1$, i.e., $\\text{dfs}(n, k + 1)$. If we choose to place cards, the remaining number of cards decreases by $3 \\times k + 2$, and the number of layers increases by $1$, i.e., $\\text{dfs}(n - (3 \\times k + 2), k + 1)$. The sum of these two cases is the answer.\n\nDuring the process, we can use memoization to avoid repeated calculations.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ is the number of cards." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 2190, "explanations": { "1": "We use a hash table or an array $\\textit{cnt}$ to record the number of occurrences of each $\\textit{target}$, and use a variable $\\textit{mx}$ to maintain the maximum number of occurrences of $\\textit{target}$. Initially, $\\textit{mx} = 0$.\n\nTraverse the array $\\textit{nums}$. If $\\textit{nums}[i] = \\textit{key}$, increment the count of $\\textit{nums}[i + 1]$ in $\\textit{cnt}[\\textit{nums}[i + 1]]$. If $\\textit{mx} \\lt \\textit{cnt}[\\textit{nums}[i + 1]]$, update $\\textit{mx} = \\textit{cnt}[\\textit{nums}[i + 1]]$ and update the answer $\\textit{ans} = \\textit{nums}[i + 1]$.\n\nAfter the traversal, return the answer $\\textit{ans}$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(M)$. Here, $n$ and $M$ are the length of the array $\\textit{nums}$ and the maximum value of the elements in the array $\\textit{nums}$, respectively." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(M)" }, { "problem_id": 2191, "explanations": { "1": "We traverse each element $nums[i]$ in the array $nums$, store its mapped value $y$ and index $i$ into the array $arr$, then sort the array $arr$. Finally, we extract the index $i$ from the sorted array $arr$, convert it to the element $nums[i]$ in the original array $nums$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2192, "explanations": { "1": "First, we construct the adjacency list $g$ based on the two-dimensional array $edges$, where $g[i]$ represents all successor nodes of node $i$.\n\nThen, we enumerate node $i$ as the ancestor node from small to large, use BFS to search all successor nodes of node $i$, and add node $i$ to the ancestor list of these successor nodes.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Where $n$ is the number of nodes." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 2193, "explanations": { "1": "由于题目保证原串一定可以变成回文串,那么原串中最多只有一种字母出现奇数次。如果有一种字母出现奇数次,那么将该字母中排在最中间的字符移动到字符串中间,剩下的字符可以转化为所有字母均出现偶数次的情况。\n\n贪心算法是:每次固定字符串最左边的字母 $a$ 不变,找出距离字符串右侧最近的 $a$,把它交换到字符串最右边。这样字符串的头尾字母就相等了。把字符串的头尾去掉,就变成了子问题。把所有子问题的答案加起来就是最少交换次数。\n\n由于数据范围较小,通过 ${O}(n^2)$ 的模拟即可通过本题。\n\n证明:\n\n构造回文串的过程,实际上是每次选择一对字母并把它们交换到字符串头尾的过程。考虑字母 $x$ 和字母 $y$ 哪个先选,分以下情况讨论:\n\n- 字母 $x$ 和 $y$ 的位置满足 $\\underbrace{\\cdots}_{a\\textit{ 个}}x\\underbrace{\\cdots}_{b\\textit{ 个}}y\\underbrace{\\cdots}_{c\\textit{ 个}}y\\underbrace{\\cdots}_{d\\textit{ 个}}x\\underbrace{\\cdots}_{e\\textit{ 个}}$。如果先把 $x$ 换到头尾,再把 $y$ 换到头尾,那么需要 $(a + e) + (b + d)$ 次交换;如果先换 $y$ 再换 $x$,那么需要 $(a + b + 1 + d + e + 1) + (a + e)$ 次交换。显然先换 $x$ 更优。\n- 字母 $x$ 和 $y$ 的位置满足 $\\underbrace{\\cdots}_{a\\textit{ 个}}x\\underbrace{\\cdots}_{b\\textit{ 个}}y\\underbrace{\\cdots}_{c\\textit{ 个}}x\\underbrace{\\cdots}_{d\\textit{ 个}}y\\underbrace{\\cdots}_{e\\textit{ 个}}$。如果先换 $x$ 再换 $y$,那么需要 $(a + d + e + 1) + (a + b + e)$ 次交换;如果先换 $y$ 再换 $x$,那么需要 $(a + b + 1 + e) + (a + d + e)$ 次交换。先换哪个都一样。\n- 字母 $x$ 和 $y$ 的位置满足 $\\underbrace{\\cdots}_{a\\textit{ 个}}x\\underbrace{\\cdots}_{b\\textit{ 个}}x\\underbrace{\\cdots}_{c\\textit{ 个}}y\\underbrace{\\cdots}_{d\\textit{ 个}}y\\underbrace{\\cdots}_{e\\textit{ 个}}$。如果先换 $x$ 再换 $y$,那么需要 $(a + c + d + e + 2) + (a + b + c + e)$ 次交换;如果先换 $y$ 再换 $x$,那么需要 $(a + b + c + 2 + e) + (a + c + d + e)$ 次交换。先换哪个都一样。\n\n上述讨论可以得到结论:每次交换最外边出现的字母不劣。因此贪心解法成立。\n\n> 出处:https://leetcode.cn/problems/minimum-number-of-moves-to-make-palindrome/solution/tan-xin-zheng-ming-geng-da-shu-ju-fan-we-h57i/" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2194, "explanations": { "1": "We directly traverse all the cells within the range and add them to the answer array.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$, where $m$ and $n$ are the range of rows and columns, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 2195, "explanations": { "1": "We can add two sentinel nodes to the array, which are $0$ and $2 \\times 10^9$.\n\nThen we sort the array. For any two adjacent elements $a$ and $b$ in the array, the integers in the interval $[a+1, b-1]$ do not appear in the array, and we can add these integers to the array.\n\nTherefore, we traverse the adjacent element pairs $(a, b)$ in the array from small to large. For each adjacent element pair, we calculate the number of integers $m$ in the interval $[a+1, b-1]$. The sum of these $m$ integers is $\\frac{m \\times (a+1 + a+m)}{2}$. We add this sum to the answer and subtract $m$ from $k$. If $k$ is reduced to $0$, we can stop the traversal and return the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 2196, "explanations": { "1": "We can use a hash table $\\textit{nodes}$ to store all nodes, where the keys are the values of the nodes, and the values are the nodes themselves. Additionally, we use a set $\\textit{children}$ to store all child nodes.\n\nWe iterate through the $\\textit{descriptions}$, and for each description $[\\textit{parent}, \\textit{child}, \\textit{isLeft}]$, if $\\textit{parent}$ is not in $\\textit{nodes}$, we add $\\textit{parent}$ to $\\textit{nodes}$ and initialize a node with the value $\\textit{parent}$. If $\\textit{child}$ is not in $\\textit{nodes}$, we add $\\textit{child}$ to $\\textit{nodes}$ and initialize a node with the value $\\textit{child}$. Then, we add $\\textit{child}$ to $\\textit{children}$.\n\nIf $\\textit{isLeft}$ is true, we set $\\textit{child}$ as the left child of $\\textit{parent}$; otherwise, we set $\\textit{child}$ as the right child of $\\textit{parent}$.\n\nFinally, we iterate through $\\textit{nodes}$, and if a node's value is not in $\\textit{children}$, then this node is the root node, and we return this node.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of $\\textit{descriptions}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2197, "explanations": { "1": "If there exist three adjacent numbers $x$, $y$, $z$ that can be merged, then the result of first merging $x$ and $y$, then merging $z$, is the same as the result of first merging $y$ and $z$, then merging $x$. Both results are $\\textit{LCM}(x, y, z)$.\n\nTherefore, we can always prefer to merge the adjacent numbers on the left, and then merge the result with the adjacent number on the right.\n\nWe use a stack to simulate this process. We traverse the array, and for each number, we push it into the stack. Then we continuously check whether the top two numbers of the stack are coprime. If they are not coprime, we pop these two numbers out of the stack, and then push their least common multiple into the stack, until the top two numbers of the stack are coprime, or there are less than two elements in the stack.\n\nThe final elements in the stack are the final result.\n\nThe time complexity is $O(n \\times \\log M)$, and the space complexity is $O(n)$. Where $M$ is the maximum value in the array." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(n)" }, { "problem_id": 2198, "explanations": { "1": "We notice that the range of elements in the array `nums` is $[1, 100]$. Therefore, we can enumerate three numbers $a, b, c$, where $a, b, c \\in [1, 100]$, and then determine whether $a + b + c$ can only be divided by one of $a, b, c$. If so, we can calculate the number of single-factor triples with $a, b, c$ as elements. The specific calculation method is as follows:\n\n- If $a = b$, then the number of single-factor triples with $a, b, c$ as elements is $x \\times (x - 1) \\times z$, where $x$, $y$, $z$ represent the number of occurrences of $a$, $b$, $c$ in the array `nums` respectively.\n- If $a = c$, then the number of single-factor triples with $a, b, c$ as elements is $x \\times (x - 1) \\times y$.\n- If $b = c$, then the number of single-factor triples with $a, b, c$ as elements is $x \\times y \\times (y - 1)$.\n- If $a, b, c$ are all different, then the number of single-factor triples with $a, b, c$ as elements is $x \\times y \\times z$.\n\nFinally, we add up the numbers of all single-factor triples.\n\nThe time complexity is $O(M^3)$, and the space complexity is $O(M)$. Where $M$ is the range of elements in the array `nums`." }, "is_english": true, "time_complexity": "O(M^3)", "space_complexity": "O(M)" }, { "problem_id": 2199, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2200, "explanations": { "1": "We enumerate the index $i$ in the range $[0, n)$, and for each index $i$, we enumerate the index $j$ in the range $[0, n)$. If $|i - j| \\leq k$ and $nums[j] = key$, then $i$ is a K-nearest neighbor index. We add $i$ to the answer array, then break the inner loop and enumerate the next index $i$.\n\nThe time complexity is $O(n^2)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$.", "2": "We can preprocess to get the indices of all elements equal to $key$, recorded in the array $idx$. All index elements in the array $idx$ are sorted in ascending order.\n\nNext, we enumerate the index $i$. For each index $i$, we can use binary search to find elements in the range $[i - k, i + k]$ in the array $idx$. If there are elements, then $i$ is a K-nearest neighbor index. We add $i$ to the answer array.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$.", "3": "We enumerate the index $i$, and use a pointer $j$ to point to the smallest index that satisfies $j \\geq i - k$ and $nums[j] = key$. If $j$ exists and $j \\leq i + k$, then $i$ is a K-nearest neighbor index. We add $i$ to the answer array.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(1)" }, { "problem_id": 2201, "explanations": { "1": "We can use a hash table $s$ to record all the excavated cells, then traverse all the workpieces, and check whether all parts of the workpiece are in the hash table. If so, we can extract the workpiece, and the answer is increased by one.\n\nThe time complexity is $O(m + k)$, and the space complexity is $O(k)$. Here, $m$ is the number of workpieces, and $k$ is the number of excavated cells." }, "is_english": true, "time_complexity": "O(m + k)", "space_complexity": "O(k)" }, { "problem_id": 2202, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2203, "explanations": { "1": "最短路问题。\n\n我们假设从 $src1$ 出发到 $dest$ 的一条最短路径为 $A$,从 $src2$ 出发到 $dest$ 的一条最短路径为 $B$。\n\n$A$, $B$ 两条路径一定存在着公共点 $p$,因为 $dest$ 一定是其中一个公共点。那么问题可以转换为求以下三条路径和的最小值:\n\n1. 从 $src1$ 到 $p$ 的最短路\n1. 从 $src2$ 到 $p$ 的最短路\n1. 从 $p$ 到 $dest$ 的最短路(这里我们可以将原图的所有边反向,然后转换为从 $dest$ 到 $p$ 的最短路)\n\n我们进行三次 Dijkstra 算法,就可以求出 $src1$, $src2$, $dest$ 到其他点的最短路径。\n\n公共点可以有多个,因此我们在 $[0,n)$ 范围内枚举公共点 $p$,找出边权之和最小的值即可。\n\n时间复杂度 $O(mlogn)$,其中 m 表示数组 $edges$ 的长度。" }, "is_english": false, "time_complexity": "O(mlogn)", "space_complexity": null }, { "problem_id": 2204, "explanations": { "1": "We can first convert the edges in $edges$ into an adjacency list $g$, where $g[i]$ represents all adjacent nodes of node $i$, represented as a set.\n\nNext, we delete nodes layer by layer from the outside to the inside until only a cycle remains. The specific method is as follows:\n\nWe first find all nodes with a degree of $1$ and remove these nodes from the graph. If after deletion, the degree of its adjacent node becomes $1$, then we add it to the queue $q$. During this process, we record all deleted nodes in order as $seq$; and we use an array $f$ to record the adjacent node of each node that is closer to the cycle, i.e., $f[i]$ represents the adjacent node of node $i$ that is closer to the cycle.\n\nFinally, we initialize an answer array $ans$ of length $n$, where $ans[i]$ represents the minimum distance from node $i$ to any node in the cycle, initially $ans[i] = 0$. Then, we start traversing from the end of $seq$. For each node $i$, we can get the value of $ans[i]$ from its adjacent node $f[i]$, i.e., $ans[i] = ans[f[i]] + 1$.\n\nAfter the traversal, return the answer array $ans$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes.\n\nSimilar problems:\n\n- [2603. Collect Coins in a Tree](https://github.com/doocs/leetcode/blob/main/solution/2600-2699/2603.Collect%20Coins%20in%20a%20Tree/README_EN.md)" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2205, "explanations": { "1": "注意需要判断的是单次购买金额是否大于等于 `minAmount`,而不是累计购买金额是否大于等于 `minAmount`。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2206, "explanations": { "1": "According to the problem description, as long as each element in the array appears an even number of times, the array can be divided into $n$ pairs.\n\nTherefore, we can use a hash table or an array $\\textit{cnt}$ to record the number of occurrences of each element, then traverse $\\textit{cnt}$. If any element appears an odd number of times, return $\\textit{false}$; otherwise, return $\\textit{true}$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2207, "explanations": { "1": "We can use two variables $x$ and $y$ to record the current counts of $\\textit{pattern}[0]$ and $\\textit{pattern}[1]$ in the string, respectively.\n\nThen, traverse the string $\\textit{text}$. For the current character $c$:\n\n- If $c$ equals $\\textit{pattern}[1]$, increment $y$ by one. At this point, all previously encountered $\\textit{pattern}[0]$ can form a $\\textit{pattern}$ subsequence with the current $c$, so add $x$ to the answer.\n- If $c$ equals $\\textit{pattern}[0]$, increment $x$ by one.\n\nAfter the traversal, since we can insert one character, if we add $\\textit{pattern}[0]$ at the beginning of the string, we can get $y$ $\\textit{pattern}$ subsequences. If we add $\\textit{pattern}[1]$ at the end of the string, we can get $x$ $\\textit{pattern}$ subsequences. Therefore, we add the larger value of $x$ and $y$ to the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $\\textit{text}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2208, "explanations": { "1": "According to the problem description, each operation will halve a number in the array. To minimize the number of operations that reduce the array sum by at least half, each operation should halve the current maximum value in the array.\n\nTherefore, we first calculate the total sum $s$ that the array needs to reduce, and then use a priority queue (max heap) to maintain all the numbers in the array. Each time we take the maximum value $t$ from the priority queue, halve it, and then put the halved number back into the priority queue, while updating $s$, until $s \\le 0$. The number of operations at this time is the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2209, "explanations": { "1": "We design a function $\\textit{dfs}(i, j)$ to represent the minimum number of white tiles that are not covered starting from index $i$ using $j$ carpets. The answer is $\\textit{dfs}(0, \\textit{numCarpets})$.\n\nFor index $i$, we discuss the following cases:\n\n- If $i \\ge n$, it means all tiles have been covered, return $0$;\n- If $\\textit{floor}[i] = 0$, then we do not need to use a carpet, just skip it, i.e., $\\textit{dfs}(i, j) = \\textit{dfs}(i + 1, j)$;\n- If $j = 0$, then we can directly use the prefix sum array $s$ to calculate the number of remaining uncovered white tiles, i.e., $\\textit{dfs}(i, j) = s[n] - s[i]$;\n- If $\\textit{floor}[i] = 1$, then we can choose to use a carpet or not, and take the minimum of the two, i.e., $\\textit{dfs}(i, j) = \\min(\\textit{dfs}(i + 1, j), \\textit{dfs}(i + \\textit{carpetLen}, j - 1))$.\n\nWe use memoization search to solve this problem.\n\nThe time complexity is $O(n \\times m)$, and the space complexity is $O(n \\times m)$. Here, $n$ and $m$ are the length of the string $\\textit{floor}$ and the value of $\\textit{numCarpets}$, respectively." }, "is_english": true, "time_complexity": "O(n \\times m)", "space_complexity": "O(n \\times m)" }, { "problem_id": 2210, "explanations": { "1": "We initialize a pointer $j$ to point to the position with index $0$, and then traverse the array in the range $[1, n-1]$. For each position $i$:\n\n- If $nums[i] = nums[i+1]$, then skip.\n- Otherwise, if $nums[i]$ is greater than $nums[j]$ and $nums[i]$ is greater than $nums[i+1]$, then $i$ is a peak; if $nums[i]$ is less than $nums[j]$ and $nums[i]$ is less than $nums[i+1]$, then $i$ is a valley.\n- Then, we update $j$ to $i$ and continue to traverse.\n\nAfter the traversal, we can get the number of peaks and valleys.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2211, "explanations": { "1": "According to the problem description, when two cars moving in opposite directions collide, the collision count increases by $2$, meaning both cars stop, and the answer increases by $2$. When a moving car collides with a stationary car, the collision count increases by $1$, meaning one car stops, and the answer increases by $1$.\n\nObviously, the prefix $\\textit{L}$ and the suffix $\\textit{R}$ will not collide, so we only need to count the number of characters in the middle that are not $\\textit{S}$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$ or $O(1)$. Here, $n$ is the length of the string $\\textit{directions}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2212, "explanations": { "1": "Since there are only $12$ regions, we use binary enumeration to determine in which regions $\\textit{Bob}$ scores. We use a variable $\\textit{st}$ to represent the scheme in which $\\textit{Bob}$ obtains the maximum score, and $\\textit{mx}$ to represent the maximum score $\\textit{Bob}$ obtains.\n\nWe enumerate $\\textit{Bob}$'s scoring schemes in the range $[1, 2^m)$, where $m$ is the length of $\\textit{aliceArrows}$. For each scheme, we calculate $\\textit{Bob}$'s score $\\textit{s}$ and the number of arrows $\\textit{cnt}$. If $\\textit{cnt} \\leq \\textit{numArrows}$ and $\\textit{s} > \\textit{mx}$, we update $\\textit{mx}$ and $\\textit{st}$.\n\nThen, we calculate $\\textit{Bob}$'s scoring scheme based on $\\textit{st}$. If there are any remaining arrows, we allocate the remaining arrows to the first region, which is the region with index $0$.\n\nThe time complexity is $O(2^m \\times m)$, where $m$ is the length of $\\textit{aliceArrows}$. Ignoring the space consumption of the answer array, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(2^m \\times m)", "space_complexity": "O(1)" }, { "problem_id": 2213, "explanations": { "1": "The segment tree divides the entire interval into multiple non-continuous sub-intervals, and the number of sub-intervals does not exceed $\\log(\\textit{width})$. To update the value of an element, you only need to update $\\log(\\textit{width})$ intervals, and these intervals are all contained in a large interval that contains the element. When modifying the interval, you need to use **lazy tags** to ensure efficiency.\n\n- Each node of the segment tree represents an interval;\n- The segment tree has a unique root node, which represents the entire statistical range, such as $[1, n]$;\n- Each leaf node of the segment tree represents an elementary interval of length $1$, $[x, x]$;\n- For each internal node $[l, r]$, its left child is $[l, mid]$, and the right child is $[mid + 1, r]$, where $mid = \\frac{l + r}{2}$;\n\nFor this problem, the information maintained by the segment tree node includes:\n\n1. The number of longest consecutive characters in the prefix, $lmx$;\n2. The number of longest consecutive characters in the suffix, $rmx$;\n3. The number of longest consecutive characters in the interval, $mx$.\n4. The left endpoint $l$ and the right endpoint $r$ of the interval.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n \\times \\log n)$. Where $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n \\times \\log n)" }, { "problem_id": 2214, "explanations": { "1": "We can greedily choose to use the armor skill in the round with the highest damage. Suppose the maximum damage is $\\textit{mx}$, then we can avoid $\\min(\\textit{mx}, \\textit{armor})$ damage. Therefore, the minimum health required is $\\sum(\\textit{damage}) - \\min(\\textit{mx}, \\textit{armor}) + 1$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{damage}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2215, "explanations": { "1": "We define two hash tables $s1$ and $s2$ to store the elements in arrays $nums1$ and $nums2$ respectively. Then we traverse each element in $s1$. If this element is not in $s2$, we add it to the first list in the answer. Similarly, we traverse each element in $s2$. If this element is not in $s1$, we add it to the second list in the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2216, "explanations": { "1": "According to the problem description, we know that a beautiful array has an even number of elements, and if we divide every two adjacent elements in this array into a group, then the two elements in each group are not equal. This means that the elements within a group cannot be repeated, but the elements between groups can be repeated.\n\nTherefore, we consider traversing the array from left to right. As long as we encounter two adjacent elements that are equal, we delete one of them, that is, the deletion count increases by one; otherwise, we can keep these two elements.\n\nFinally, we check whether the length of the array after deletion is even. If not, it means that we need to delete one more element to make the final array length even.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. We only need to traverse the array once. The space complexity is $O(1)$.", "2": "" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2217, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2218, "explanations": { "1": "We define $f[i][j]$ as the maximum value sum of taking $j$ coins from the first $i$ piles. The answer is $f[n][k]$, where $n$ is the number of piles.\n\nFor the $i$-th pile, we can choose to take the first $0$, $1$, $2$, $\\cdots$, $k$ coins. We can use a prefix sum array $s$ to quickly calculate the value sum of taking the first $h$ coins.\n\nThe state transition equation is:\n\n$$\nf[i][j] = \\max(f[i][j], f[i - 1][j - h] + s[h])\n$$\n\nwhere $0 \\leq h \\leq j$, and $s[h]$ represents the value sum of taking the first $h$ coins from the $i$-th pile.\n\nThe time complexity is $O(k \\times L)$, and the space complexity is $O(n \\times k)$. Here, $L$ is the total number of coins, and $n$ is the number of piles.", "2": "We can observe that for the $i$-th pile, we only need to use $f[i - 1][j]$ and $f[i][j - h]$, so we can optimize the two-dimensional array to a one-dimensional array.\n\nThe time complexity is $O(k \\times L)$, and the space complexity is $O(k)$." }, "is_english": true, "time_complexity": "O(k \\times L)", "space_complexity": "O(n \\times k)" }, { "problem_id": 2219, "explanations": { "1": "We can use two variables $l$ and $r$ to represent the prefix sum and suffix sum of the array, respectively. Initially, $l = 0$ and $r = \\sum_{i=0}^{n-1} \\textit{nums}[i]$.\n\nNext, we traverse the array $\\textit{nums}$. For each element $x$, we add $x$ to $l$ and update the answer $\\textit{ans} = \\max(\\textit{ans}, l, r)$, then subtract $x$ from $r$.\n\nAfter the traversal, return the answer $\\textit{ans}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2220, "explanations": { "1": "According to the problem description, we only need to count the number of 1s in the binary representation of $\\textit{start} \\oplus \\textit{goal}$.\n\nThe time complexity is $O(\\log n)$, where $n$ is the size of the integers in the problem. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 2221, "explanations": { "1": "We can directly simulate the operations described in the problem. Perform $n - 1$ rounds of operations on the array $\\textit{nums}$, updating the array $\\textit{nums}$ according to the rules described in the problem for each round. Finally, return the only remaining element in the array $\\textit{nums}$.\n\nThe time complexity is $O(n^2)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(1)" }, { "problem_id": 2222, "explanations": { "1": "According to the problem description, we need to choose $3$ buildings, and two adjacent buildings cannot be of the same type.\n\nWe can enumerate the middle building, assuming it is $x$, then the types of buildings on the left and right sides can only be $x \\oplus 1$, where $\\oplus$ denotes the XOR operation. Therefore, we can use two arrays $l$ and $r$ to record the number of building types on the left and right sides, respectively. Then, we enumerate the middle building and calculate the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2223, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2224, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2225, "explanations": { "1": "We use a hash table `cnt` to record the number of matches each player has lost.\n\nThen we traverse the hash table, put the players who lost 0 matches into `ans[0]`, and put the players who lost 1 match into `ans[1]`.\n\nFinally, we sort `ans[0]` and `ans[1]` in ascending order and return the result.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the number of matches." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2226, "explanations": { "1": "We notice that if each child can receive $v$ candies, then for any $v' \\lt v$, each child can also receive $v'$ candies. Therefore, we can use binary search to find the maximum $v$ such that each child can receive $v$ candies.\n\nWe define the left boundary of the binary search as $l = 0$ and the right boundary as $r = \\max(\\text{candies})$, where $\\max(\\text{candies})$ represents the maximum value in the array $\\text{candies}$. During the binary search, we take the middle value $v = \\left\\lfloor \\frac{l + r + 1}{2} \\right\\rfloor$ each time, and then calculate the total number of candies each child can receive. If the total is greater than or equal to $k$, it means each child can receive $v$ candies, so we update the left boundary $l = v$. Otherwise, we update the right boundary $r = v - 1$. Finally, when $l = r$, we have found the maximum $v$.\n\nThe time complexity is $O(n \\times \\log M)$, where $n$ is the length of the array $\\text{candies}$, and $M$ is the maximum value in the array $\\text{candies}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(1)" }, { "problem_id": 2227, "explanations": { "1": "We use a hash table $\\textit{mp}$ to record the encryption result of each character, and another hash table $\\textit{cnt}$ to record the number of occurrences of each encryption result.\n\nIn the constructor, we traverse $\\textit{keys}$ and $\\textit{values}$, storing each character and its corresponding encryption result in $\\textit{mp}$. Then, we traverse $\\textit{dictionary}$ to count the occurrences of each encryption result. The time complexity is $O(n + m)$, where $n$ and $m$ are the lengths of $\\textit{keys}$ and $\\textit{dictionary}$, respectively.\n\nIn the encryption function, we traverse each character of the input string $\\textit{word1}$, look up its encryption result, and concatenate them. If a character does not have a corresponding encryption result, it means encryption is not possible, and we return an empty string. The time complexity is $O(k)$, where $k$ is the length of $\\textit{word1}$.\n\nIn the decryption function, we directly return the count of $\\textit{word2}$ in $\\textit{cnt}$. The time complexity is $O(1)$.\n\nThe space complexity is $O(n + m)$." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(n + m)" }, { "problem_id": 2228, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2229, "explanations": { "1": "We can use a hash table $\\textit{s}$ to store all the elements in the array $\\textit{nums}$, and use two variables $\\textit{mi}$ and $\\textit{mx}$ to represent the minimum and maximum values in the array, respectively.\n\nIf all elements in the array are distinct and the length of the array equals the difference between the maximum and minimum values plus $1$, then the array is consecutive, and we return $\\textit{true}$; otherwise, we return $\\textit{false}$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2230, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2231, "explanations": { "1": "We can use an array $\\textit{cnt}$ of length $10$ to count the occurrences of each digit in the integer $\\textit{num}$. We also use an index array $\\textit{idx}$ to record the largest available even and odd digits, initially set to $[8, 9]$.\n\nNext, we traverse each digit of the integer $\\textit{num}$. If the digit is odd, we take the digit corresponding to index $1$ in $\\textit{idx}$; otherwise, we take the digit corresponding to index $0$. If the count of the digit is $0$, we decrement the digit by $2$ and continue checking until we find a digit that meets the condition. Then, we update the answer and the count of the digit, and continue traversing until we have processed all digits of the integer $\\textit{num}$.\n\nThe time complexity is $O(\\log \\textit{num})$, and the space complexity is $O(\\log \\textit{num})$." }, "is_english": true, "time_complexity": "O(\\log \\textit{num})", "space_complexity": "O(\\log \\textit{num})" }, { "problem_id": 2232, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2233, "explanations": { "1": "According to the problem description, to maximize the product, we need to increase the smaller numbers as much as possible. Therefore, we can use a min-heap to maintain the array $\\textit{nums}$. Each time, we take the smallest number from the min-heap, increase it by $1$, and then put it back into the min-heap. After repeating this process $k$ times, we multiply all the numbers currently in the min-heap to get the answer.\n\nThe time complexity is $O(k \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(k \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2234, "explanations": { "1": "We note that if the number of flowers in a garden is already greater than or equal to $\\textit{target}$, then this garden is already a perfect garden and cannot be changed. For imperfect gardens, we can plant more flowers to make them perfect gardens.\n\nLet's enumerate how many gardens will eventually become perfect gardens. Suppose initially there are $x$ perfect gardens, then we can enumerate in the range $[x, n]$. Which imperfect gardens should we choose to become perfect gardens? In fact, we should choose the gardens with more flowers so that the remaining flowers can be used to increase the minimum value of the imperfect gardens. Therefore, we sort the array $\\textit{flowers}$.\n\nNext, we enumerate the number of perfect gardens $x$. The current garden to become a perfect garden is $\\textit{target}[n-x]$, and the number of flowers needed is $\\max(0, \\textit{target} - \\textit{flowers}[n - x])$.\n\nWe update the remaining flowers $\\textit{newFlowers}$. If it is less than $0$, it means we can no longer make more gardens perfect, so we stop the enumeration.\n\nOtherwise, we perform a binary search in the range $[0,..n-x-1]$ to find the maximum index of the imperfect gardens that can be turned into perfect gardens. Let the index be $l$, then the number of flowers needed is $\\textit{cost} = \\textit{flowers}[l] \\times (l + 1) - s[l + 1]$, where $s[i]$ is the sum of the first $i$ numbers in the $\\textit{flowers}$ array. If we can still increase the minimum value, we calculate the increase $\\frac{\\textit{newFlowers} - \\textit{cost}}{l + 1}$, and ensure that the final minimum value does not exceed $\\textit{target}-1$. That is, the minimum value $y = \\min(\\textit{flowers}[l] + \\frac{\\textit{newFlowers} - \\textit{cost}}{l + 1}, \\textit{target} - 1)$. Then the beauty value of the garden is $x \\times \\textit{full} + y \\times \\textit{partial}$. The answer is the maximum of all beauty values.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the $\\textit{flowers}$ array." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2235, "explanations": { "1": "我们可以直接使用加法运算符 `+` 来计算两个整数的和。\n\n时间复杂度 $O(1)$,空间复杂度 $O(1)$。", "2": "我们也可以在不使用加法运算符的前提下,使用位运算来计算两个整数的和。\n\n假设 $num1_i$ 和 $num2_i$ 分别表示 $num1$ 和 $num2$ 的第 $i$ 个二进制位。一共有 $4$ 种情况:\n\n| $num1_i$ | $num2_i$ | 不进位的和 | 进位 |\n| -------- | -------- | ---------- | ---- |\n| 0 | 0 | 0 | 0 |\n| 0 | 1 | 1 | 0 |\n| 1 | 0 | 1 | 0 |\n| 1 | 1 | 0 | 1 |\n\n观察可以发现,“不进位的和”与“异或运算”有相同规律,而进位则与“与”运算规律相同,并且需要左移一位。\n\n因此:\n\n- 对两数进行按位 `&` 与运算,然后左移一位,得到进位,记为 $carry$;\n- 对两数进行按位 `^` 异或运算,得到不进位的和;\n- 问题转换为求:“不进位的数 + 进位” 之和;\n- 循环,直至第二个数为 $0$,返回第一个数即可(也可以用递归实现)。\n\n时间复杂度 $O(\\log M)$,其中 $M$ 为题目中数字的最大值。空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 2236, "explanations": { "1": "我们直接判断根节点的值是否等于左右子节点的值之和即可。\n\n时间复杂度 $O(1)$,空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 2237, "explanations": { "1": "To add a value $v$ to a continuous interval $[i, j]$ simultaneously, we can use a difference array.\n\nWe define an array $\\textit{d}$ of length $n + 1$. For each streetlight, we calculate its left boundary $i = \\max(0, p - r)$ and right boundary $j = \\min(n - 1, p + r)$, then add $1$ to $\\textit{d}[i]$ and subtract $1$ from $\\textit{d}[j + 1]$.\n\nNext, we perform a prefix sum operation on $\\textit{d}$. For each position $i$, if the prefix sum of $\\textit{d}[i]$ is greater than or equal to $\\textit{requirement}[i]$, it means that the position meets the requirement, and we increment the answer by one.\n\nFinally, return the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of streetlights." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2238, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2239, "explanations": { "1": "We define a variable $\\textit{d}$ to record the current minimum distance, initially $\\textit{d}=\\infty$. Then we traverse the array, for each element $x$, we calculate $y=|x|$. If $y \\lt d$ or $y=d$ and $x \\gt \\textit{ans}$, we update the answer $\\textit{ans}=x$ and $\\textit{d}=y$.\n\nAfter the traversal, return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2240, "explanations": { "1": "We can enumerate the number of pens to buy, denoted as $x$. For each $x$, the maximum number of pencils we can buy is $\\frac{\\textit{total} - x \\times \\textit{cost1}}{\\textit{cost2}}$. The number of ways for each $x$ is this value plus 1. We sum up the number of ways for all $x$ to get the answer.\n\nThe time complexity is $O(\\frac{\\textit{total}}{\\textit{cost1}})$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\frac{\\textit{total}}{\\textit{cost1}})", "space_complexity": "O(1)" }, { "problem_id": 2241, "explanations": { "1": "We use an array $\\textit{d}$ to record the denominations of the bills and an array $\\textit{cnt}$ to record the number of bills for each denomination.\n\nFor the `deposit` operation, we simply add the number of bills to the corresponding denomination. The time complexity is $O(1)$.\n\nFor the `withdraw` operation, we enumerate the bills from largest to smallest denomination, taking out as many bills as possible without exceeding $\\textit{amount}$. We then subtract the total value of the withdrawn bills from $\\textit{amount}$. If $\\textit{amount}$ is still greater than $0$ at the end, it means we cannot withdraw the requested amount, and we return $-1$. Otherwise, we return the number of withdrawn bills. The time complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": null }, { "problem_id": 2242, "explanations": { "1": "枚举中间边 $(a, b)$,假设与 $a$ 相邻的点为 $c$,与 $b$ 相邻的点为 $d$。对于相邻点,取分数最大的三个点进行枚举。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2243, "explanations": { "1": "According to the problem statement, we can simulate the operations described in the problem until the length of the string is less than or equal to $k$. Finally, return the string.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2244, "explanations": { "1": "We use a hash table to count the number of tasks for each difficulty level. Then we traverse the hash table. For each difficulty level, if the number of tasks is $1$, then it is impossible to complete all tasks, so we return $-1$. Otherwise, we calculate the number of rounds needed to complete tasks of this difficulty level and add it to the answer.\n\nFinally, we return the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the `tasks` array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2245, "explanations": { "1": "Firstly, we need to understand that for a product, the number of trailing zeros depends on the smaller count of $2$ and $5$ in its factors. Also, each corner path should cover as many numbers as possible, so it must start from a boundary, reach a turning point, and then reach another boundary.\n\nTherefore, we can create four two-dimensional arrays $r2$, $c2$, $r5$, $c5$ to record the counts of $2$ and $5$ in each row and column. Where:\n\n- `r2[i][j]` represents the count of $2$ from the first column to the $j$-th column in the $i$-th row;\n- `c2[i][j]` represents the count of $2$ from the first row to the $i$-th row in the $j$-th column;\n- `r5[i][j]` represents the count of $5$ from the first column to the $j$-th column in the $i$-th row;\n- `c5[i][j]` represents the count of $5$ from the first row to the $i$-th row in the $j$-th column.\n\nNext, we traverse the two-dimensional array `grid`. For each number, we calculate its counts of $2$ and $5$, and then update the four two-dimensional arrays.\n\nThen, we enumerate the turning point $(i, j)$. For each turning point, we calculate four values:\n\n- `a` represents the smaller count of $2$ and $5$ in the path that moves right from $(i, 1)$ to $(i, j)$, then turns and moves up to $(1, j)$;\n- `b` represents the smaller count of $2$ and $5$ in the path that moves right from $(i, 1)$ to $(i, j)$, then turns and moves down to $(m, j)$;\n- `c` represents the smaller count of $2$ and $5$ in the path that moves left from $(i, n)$ to $(i, j)$, then turns and moves up to $(1, j)$;\n- `d` represents the smaller count of $2$ and $5$ in the path that moves left from $(i, n)$ to $(i, j)$, then turns and moves down to $(m, j)$.\n\nEach time we enumerate, we take the maximum of these four values, and then update the answer.\n\nFinally, we return the answer.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns of the `grid` array, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 2246, "explanations": { "1": "First, we construct an adjacency list $g$ based on the array $parent$, where $g[i]$ represents all child nodes of node $i$.\n\nThen we start DFS from the root node. For each node $i$, we traverse each child node $j$ in $g[i]$. If $s[i] \\neq s[j]$, then we can start from node $i$, pass through node $j$, and reach a leaf node. The length of this path is $x = 1 + \\textit{dfs}(j)$. We use $mx$ to record the longest path length starting from node $i$. At the same time, we update the answer $ans = \\max(ans, mx + x)$ during the traversal process.\n\nFinally, we return $ans + 1$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of nodes." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2247, "explanations": { "1": "We notice that the problem requires exactly $k$ roads to be passed, and each city can only be visited once. The number of cities is $n$, so we can pass at most $n - 1$ roads. Therefore, if $k \\ge n$, we cannot meet the requirements of the problem, and we can directly return $-1$.\n\nIn addition, we can also find that the number of cities $n$ does not exceed $15$, which suggests that we can consider using the method of state compression dynamic programming to solve this problem. We use a binary number of length $n$ to represent the cities that have been passed, where the $i$-th bit is $1$ indicates that the $i$-th city has been passed, and $0$ indicates that the $i$-th city has not been passed yet.\n\nWe use $f[i][j]$ to represent the maximum travel cost when the cities that have been passed are $i$ and the last city passed is $j$. Initially, $f[2^i][i]=0$, and the rest $f[i][j]=-\\infty$.\n\nConsider how $f[i][j]$ transitions. For $f[i]$, we enumerate all cities $j$. If the $j$-th bit of $i$ is $1$, then we can reach city $j$ from other city $h$ through the road, at this time the value of $f[i][j]$ is the maximum value of $f[i][h]+cost(h, j)$, where $cost(h, j)$ represents the travel cost from city $h$ to city $j$. Therefore, we can get the state transition equation:\n\n$$\nf[i][j]=\\max_{h \\in \\textit{city}}\\{f[i \\backslash j][h]+cost(h, j)\\}\n$$\n\nwhere $i \\backslash j$ represents changing the $j$-th bit of $i$ to $0$.\n\nAfter calculating $f[i][j]$, we judge whether the number of cities passed is $k+1$, that is, whether the number of $1$s in the binary representation of $i$ is $k+1$. If so, we update the answer as $ans = \\max(ans, f[i][j])$.\n\nThe time complexity is $O(2^n \\times n^2)$, and the space complexity is $O(2^n \\times n)$, where $n$ represents the number of cities." }, "is_english": true, "time_complexity": "O(2^n \\times n^2)", "space_complexity": "O(2^n \\times n)" }, { "problem_id": 2248, "explanations": { "1": "Traverse the array `nums`. For each sub-array `arr`, count the occurrence of each number in `arr`. Then traverse the count array, count the numbers that appear as many times as the length of the array `nums`, which are the answers.\n\nThe time complexity is $O(N)$, and the space complexity is $O(1000)$. Where $N$ is the total number of numbers in the array `nums`.", "2": "" }, "is_english": true, "time_complexity": "O(N)", "space_complexity": "O(1000)" }, { "problem_id": 2249, "explanations": { "1": "枚举所有的格点,判断其是否在圆内,如果在圆内,则答案加一。\n\n枚举的时候,可以将所有圆的最大横纵坐标求出来,作为枚举的上界。\n\n时间复杂度 $O(X \\times Y \\times n)$,空间复杂度 $O(1)$。其中 $X$ 和 $Y$ 分别为所有圆的最大横纵坐标,而 $n$ 为圆的个数。" }, "is_english": false, "time_complexity": "O(X \\times Y \\times n)", "space_complexity": "O(1)" }, { "problem_id": 2250, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2251, "explanations": { "1": "We sort the flowers by their start and end times. Then, for each person, we can use binary search to find the number of flowers in bloom when they arrive. This means finding the number of flowers that have started blooming by the time each person arrives, minus the number of flowers that have wilted by that time, to get the answer.\n\nThe time complexity is $O((m + n) \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ and $m$ are the lengths of the arrays $\\textit{flowers}$ and $\\textit{people}$, respectively.", "2": "We can use a difference array to maintain the number of flowers at each time point. Next, we sort $people$ by their arrival times in ascending order. When each person arrives, we perform a prefix sum operation on the difference array to get the answer.\n\nThe time complexity is $O(m \\times \\log m + n \\times \\log n)$, and the space complexity is $O(n + m)$. Here, $n$ and $m$ are the lengths of the arrays $\\textit{flowers}$ and $\\textit{people}$, respectively." }, "is_english": true, "time_complexity": "O((m + n) \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2252, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2253, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2254, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2255, "explanations": { "1": "We directly traverse the array words, and for each string w, we check if s starts with w as a prefix. If it does, we increment the answer by one.\n\nAfter the traversal, we return the answer.\n\nThe time complexity is $O(m \\times n)$, where $m$ and $n$ are the lengths of the array words and the string s, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(1)" }, { "problem_id": 2256, "explanations": { "1": "We directly traverse the array $nums$. For each index $i$, we maintain the sum of the first $i+1$ elements $pre$ and the sum of the last $n-i-1$ elements $suf$. We calculate the absolute difference of the average of the first $i+1$ elements and the average of the last $n-i-1$ elements, denoted as $t$. If $t$ is less than the current minimum value $mi$, we update the answer $ans=i$ and the minimum value $mi=t$.\n\nAfter the traversal, we return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2257, "explanations": { "1": "We create a two-dimensional array $g$ of size $m \\times n$, where $g[i][j]$ represents the cell in row $i$ and column $j$. Initially, the value of $g[i][j]$ is $0$, indicating that the cell is not guarded.\n\nThen, we traverse all guards and walls, and set the value of $g[i][j]$ to $2$, indicating that these positions cannot be accessed.\n\nNext, we traverse all guard positions, simulate in four directions from that position until we encounter a wall or guard, or go out of bounds. During the simulation, we set the value of the encountered cell to $1$, indicating that the cell is guarded.\n\nFinally, we traverse $g$ and count the number of cells with a value of $0$, which is the answer.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the number of rows and columns in the grid, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 2258, "explanations": { "1": "We notice that if a stay time $t$ satisfies the condition, then all stay times less than $t$ also satisfy the condition. Therefore, we can consider using binary search to find the maximum stay time that satisfies the condition.\n\nWe define the left boundary of binary search as $l=-1$ and the right boundary as $r=m \\times n$. In each iteration of binary search, we take the midpoint $mid$ of $l$ and $r$ as the current stay time and check if it satisfies the condition. If it does, we update $l$ to $mid$, otherwise we update $r$ to $mid-1$. Finally, if $l=m \\times n$, it means there is no stay time that satisfies the condition, so we return $10^9$, otherwise we return $l$.\n\nThe key problem is how to determine whether a stay time $t$ satisfies the condition. We can use breadth-first search to simulate the spread of fire within $t$ time. If the fire spreads to the starting position after staying for $t$ time, it means the condition is not satisfied and we return early. Otherwise, we use breadth-first search again, searching in four directions from the current position each time, and after each round, we need to spread the fire in four directions. If we find a path from the starting position to the ending position during this process, it means the condition is satisfied.\n\nThe time complexity is $O(m \\times n \\times \\log (m \\times n))$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the number of rows and columns in the grid, respectively." }, "is_english": true, "time_complexity": "O(m \\times n \\times \\log (m \\times n))", "space_complexity": "O(m \\times n)" }, { "problem_id": 2259, "explanations": { "1": "We can enumerate all positions $\\textit{i}$ in the string $\\textit{number}$. If $\\textit{number}[i] = \\textit{digit}$, we take the prefix $\\textit{number}[0:i]$ and the suffix $\\textit{number}[i+1:]$ of $\\textit{number}$ and concatenate them. This gives the result after removing $\\textit{number}[i]$. We then take the maximum of all possible results.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $\\textit{number}$.", "2": "We can enumerate all positions $\\textit{i}$ in the string $\\textit{number}$. If $\\textit{number}[i] = \\textit{digit}$, we record the last occurrence position of $\\textit{digit}$ as $\\textit{last}$. If $\\textit{i} + 1 < \\textit{n}$ and $\\textit{number}[i] < \\textit{number}[i + 1]$, then we can directly return $\\textit{number}[0:i] + \\textit{number}[i+1:]$ as the result after removing $\\textit{number}[i]$. This is because if $\\textit{number}[i] < \\textit{number}[i + 1]$, removing $\\textit{number}[i]$ will result in a larger number.\n\nAfter the traversal, we return $\\textit{number}[0:\\textit{last}] + \\textit{number}[\\textit{last}+1:]$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 2260, "explanations": { "1": "We initialize the answer as $+\\infty$. We traverse the array, and for each number $x$, if $\\textit{last}[x]$ exists, it means $x$ has a matching pair of cards. In this case, we update the answer to $\\textit{ans} = \\min(\\textit{ans}, i - \\textit{last}[x] + 1)$. Finally, if the answer is $+\\infty$, we return $-1$; otherwise, we return the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2261, "explanations": { "1": "We can enumerate the left endpoint $i$ of the subarray, and then enumerate the right endpoint $j$ in the range $[i, n)$. During the enumeration of the right endpoint, we use double hashing to store the hash value of the subarray into a set. Finally, we return the size of the set.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ is the length of the array.", "2": "" }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 2262, "explanations": { "1": "We can enumerate all the substrings that end with each character $s[i]$ and calculate their gravitational value sum $t$. Finally, we add up all the $t$ to get the total gravitational value sum.\n\nWhen we reach $s[i]$, which is added to the end of the substring that ends with $s[i-1]$, we consider the change of the gravitational value sum $t$:\n\nIf $s[i]$ has not appeared before, then the gravitational value of all substrings that end with $s[i-1]$ will increase by $1$, and there are a total of $i$ such substrings. Therefore, $t$ increases by $i$, plus the gravitational value of $s[i]$ itself, which is $1$. Therefore, $t$ increases by a total of $i+1$.\n\nIf $s[i]$ has appeared before, let the last appearance position be $j$. Then we add $s[i]$ to the end of the substrings $s[0..i-1]$, $[1..i-1]$, $s[2..i-1]$, $\\cdots$, $s[j..i-1]$. The gravitational value of these substrings will not change because $s[i]$ has already appeared in these substrings. The gravitational value of the substrings $s[j+1..i-1]$, $s[j+2..i-1]$, $\\cdots$, $s[i-1]$ will increase by $1$, and there are a total of $i-j-1$ such substrings. Therefore, $t$ increases by $i-j-1$, plus the gravitational value of $s[i]$ itself, which is $1$. Therefore, $t$ increases by a total of $i-j$.\nTherefore, we can use an array $pos$ to record the last appearance position of each character. Initially, all positions are set to $-1$.\n\nNext, we traverse the string, and each time we update the gravitational value sum $t$ of the substring that ends with the current character to $t = t + i - pos[c]$, where $c$ is the current character. We add $t$ to the answer. Then we update $pos[c]$ to the current position $i$. We continue to traverse until the end of the string.\n\nThe time complexity is $O(n)$, and the space complexity is $O(|\\Sigma|)$, where $n$ is the length of the string $s$, and $|\\Sigma|$ is the size of the character set. In this problem, $|\\Sigma| = 26$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 2263, "explanations": { "1": "我们定义 $f[i][j]$ 表示将数组 $nums$ 的前 $i$ 个元素变为非递减序列,且第 $i$ 个元素的值为 $j$ 所需的最小操作次数。由于数组 $nums$ 元素的取值范围为 $[0, 1000]$,因此我们可以将 $f$ 数组的第二维定义为 $1001$。\n\n状态转移方程如下:\n\n$$\nf[i][j] = \\min_{0 \\leq k \\leq j} f[i - 1][k] + \\left| j - nums[i - 1] \\right|\n$$\n\n时间复杂度 $O(n \\times M)$,空间复杂度 $O(n \\times M)$。其中 $n$ 和 $M$ 分别为数组 $nums$ 的长度和数组 $nums$ 元素的取值范围。本题中 $M = 1001$。\n\n由于我们定义的是非递减序列的最小操作次数,因此我们可以将数组 $nums$ 翻转,然后求出非递减序列的最小操作次数,也即是非递增序列的最小操作次数。最后取两者的最小值即可。" }, "is_english": false, "time_complexity": "O(n \\times M)", "space_complexity": "O(n \\times M)" }, { "problem_id": 2264, "explanations": { "1": "We can enumerate each digit $i$ from large to small, where $0 \\le i \\le 9$, and then check whether the string $s$ consisting of three consecutive $i$ is a substring of $num$. If it is, we directly return $s$.\n\nIf we have enumerated all the possible values of $i$ and still haven't found a substring that satisfies the condition, we return an empty string.\n\nThe time complexity is $O(10 \\times n)$, where $n$ is the length of the string $num$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(10 \\times n)", "space_complexity": "O(1)" }, { "problem_id": 2265, "explanations": { "1": "We design a function $\\textit{dfs}$, which calculates the sum and the number of nodes of the subtree rooted at the current node.\n\nThe execution process of the function $\\textit{dfs}$ is as follows:\n\n- If the current node is null, return $(0, 0)$.\n- Otherwise, we recursively calculate the sum and the number of nodes of the left and right subtrees, denoted as $(\\textit{ls}, \\textit{ln})$ and $(\\textit{rs}, \\textit{rn})$, respectively. Then, the sum $\\textit{s}$ and the number of nodes $\\textit{n}$ of the subtree rooted at the current node are $\\textit{ls} + \\textit{rs} + \\textit{root.val}$ and $\\textit{ln} + \\textit{rn} + 1$, respectively. If $\\textit{s} / \\textit{n} = \\textit{root.val}$, it means the current node meets the requirement of the problem, and we increment the answer $\\textit{ans}$ by $1$.\n- Finally, the function $\\textit{dfs}$ returns $\\textit{s}$ and $\\textit{n}$.\n\nWe initialize the answer $\\textit{ans}$ to $0$, then call the $\\textit{dfs}$ function, and finally return the answer $\\textit{ans}$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ represents the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2266, "explanations": { "1": "According to the problem description, for consecutive identical characters in the string $\\textit{pressedKeys}$, we can group them together and then calculate the number of ways for each group. Finally, we multiply the number of ways for all groups.\n\nThe key problem is how to calculate the number of ways for each group.\n\nIf a group of characters is '7' or '9', we can consider the last $1$, $2$, $3$, or $4$ characters of the group as one letter, then reduce the size of the group and transform it into a smaller subproblem.\n\nSimilarly, if a group of characters is '2', '3', '4', '5', '6', or '8', we can consider the last $1$, $2$, or $3$ characters of the group as one letter, then reduce the size of the group and transform it into a smaller subproblem.\n\nTherefore, we define $f[i]$ to represent the number of ways for a group of length $i$ with identical characters that are not '7' or '9', and $g[i]$ to represent the number of ways for a group of length $i$ with identical characters that are '7' or '9'.\n\nInitially, $f[0] = f[1] = 1$, $f[2] = 2$, $f[3] = 4$, $g[0] = g[1] = 1$, $g[2] = 2$, $g[3] = 4$.\n\nFor $i \\ge 4$, we have:\n\n$$\n\\begin{aligned}\nf[i] & = f[i-1] + f[i-2] + f[i-3] \\\\\ng[i] & = g[i-1] + g[i-2] + g[i-3] + g[i-4]\n\\end{aligned}\n$$\n\nFinally, we traverse $\\textit{pressedKeys}$, group consecutive identical characters, calculate the number of ways for each group, and multiply the number of ways for all groups.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $\\textit{pressedKeys}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2267, "explanations": { "1": "Let $m$ be the number of rows and $n$ be the number of columns in the matrix.\n\nIf $m + n - 1$ is odd, or the parentheses in the top-left and bottom-right corners do not match, then there is no valid path, and we directly return $\\text{false}$.\n\nOtherwise, we design a function $\\textit{dfs}(i, j, k)$, which represents whether there is a valid path starting from $(i, j)$ with the current balance of parentheses being $k$. The balance $k$ is defined as the number of left parentheses minus the number of right parentheses in the path from $(0, 0)$ to $(i, j)$.\n\nIf the balance $k$ is less than $0$ or greater than $m + n - i - j$, then there is no valid path, and we directly return $\\text{false}$. If $(i, j)$ is the bottom-right cell, then there is a valid path only if $k = 0$. Otherwise, we enumerate the next cell $(x, y)$ of $(i, j)$. If $(x, y)$ is a valid cell and $\\textit{dfs}(x, y, k)$ is $\\text{true}$, then there is a valid path.\n\nThe time complexity is $O(m \\times n \\times (m + n))$, and the space complexity is $O(m \\times n \\times (m + n))$. Here, $m$ and $n$ are the number of rows and columns in the matrix, respectively." }, "is_english": true, "time_complexity": "O(m \\times n \\times (m + n))", "space_complexity": "O(m \\times n \\times (m + n))" }, { "problem_id": 2268, "explanations": { "1": "First, we count the occurrence of each character in the string $s$, and record it in an array or hash table $\\textit{cnt}$.\n\nThe problem requires minimizing the number of key presses, so the $9$ most frequent characters should correspond to keys $1$ to $9$, the $10$th to $18$th most frequent characters should correspond to keys $1$ to $9$ again, and so on.\n\nTherefore, we can sort the values in $\\textit{cnt}$ in descending order, and then allocate them to the keys in the order from $1$ to $9$, adding $1$ to the number of key presses after allocating every $9$ characters.\n\nThe time complexity is $O(n + |\\Sigma| \\times \\log |\\Sigma|)$, and the space complexity is $O(|\\Sigma|)$. Here, $n$ is the length of the string $s$, and $\\Sigma$ is the set of characters appearing in the string $s$. In this problem, $\\Sigma$ is the set of lowercase letters, so $|\\Sigma| = 26$." }, "is_english": true, "time_complexity": "O(n + |\\Sigma| \\times \\log |\\Sigma|)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 2269, "explanations": { "1": "We can convert $num$ to a string $s$, then enumerate all substrings of $s$ with length $k$, convert them to an integer $t$, and check if $t$ is divisible by $num$. If it is, we increment the answer.\n\nThe time complexity is $O(\\log num \\times k)$, and the space complexity is $O(\\log num + k)$.", "2": "We can maintain a sliding window of length $k$. Initially, the window contains the lowest $k$ digits of $num$. Then, for each iteration, we move the window one digit to the right, update the number in the window, and check if the number in the window is divisible by $num$. If it is, we increment the answer.\n\nThe time complexity is $O(\\log num)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log num \\times k)", "space_complexity": "O(\\log num + k)" }, { "problem_id": 2270, "explanations": { "1": "First, we calculate the total sum $s$ of the array $\\textit{nums}$. Then, we traverse the first $n-1$ elements of the array $\\textit{nums}$, using the variable $t$ to record the prefix sum. If $t \\geq s - t$, we increment the answer by one.\n\nAfter the traversal, we return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2271, "explanations": { "1": "直觉上,毯子的左端点一定与某块瓷砖的左端点重合,这样才能使得毯子覆盖的瓷砖最多。\n\n我们可以来简单证明一下。\n\n如果毯子落在某块瓷砖的中间某个位置,将毯子右移一个,毯子覆盖的瓷砖数量可能减少,也可能不变,但不可能增加;将毯子左移一个,毯子覆盖的瓷砖数量可能不变,也可能增加,但不可能减少。\n\n也就是说,将毯子左移至某块瓷砖的左端点,一定可以使得毯子覆盖的瓷砖数量最多。\n\n因此,我们可以将所有瓷砖按照左端点从小到大排序,然后枚举每块瓷砖的左端点,计算出以该左端点为起点的毯子覆盖的瓷砖数量,取最大值即可。\n\n为了计算以某块瓷砖的左端点为起点的毯子覆盖的瓷砖数量,我们可以使用滑动窗口的思想,维护一个右端点不断右移的窗口,窗口内的瓷砖数量即为毯子覆盖的瓷砖数量。\n\n时间复杂度 $O(n\\log n)$,其中 $n$ 为瓷砖的数量。" }, "is_english": false, "time_complexity": "O(n\\log n)", "space_complexity": null }, { "problem_id": 2272, "explanations": { "1": "Since the character set only contains lowercase letters, we can consider enumerating the most frequent character $a$ and the least frequent character $b$. For a substring, the difference in the number of occurrences of these two characters is the variance of the substring.\n\nSpecifically, we use a double loop to enumerate $a$ and $b$. We use $f[0]$ to record the number of consecutive occurrences of character $a$ ending at the current character, and $f[1]$ to record the variance of the substring ending at the current character and containing both $a$ and $b$. We iterate to find the maximum value of $f[1]$.\n\nThe recurrence formula is as follows:\n\n1. If the current character is $a$, then both $f[0]$ and $f[1]$ are incremented by $1$;\n2. If the current character is $b$, then $f[1] = \\max(f[1] - 1, f[0] - 1)$, and $f[0] = 0$;\n3. Otherwise, no need to consider.\n\nNote that initially setting $f[1]$ to a negative maximum value ensures that updating the answer is valid.\n\nThe time complexity is $O(n \\times |\\Sigma|^2)$, where $n$ is the length of the string, and $|\\Sigma|$ is the size of the character set. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times |\\Sigma|^2)", "space_complexity": "O(1)" }, { "problem_id": 2273, "explanations": { "1": "We first add $\\textit{words}[0]$ to the answer array, then traverse from $\\textit{words}[1]$. If $\\textit{words}[i - 1]$ and $\\textit{words}[i]$ are not anagrams, we add $\\textit{words}[i]$ to the answer array.\n\nThe problem is converted to determining whether two strings are anagrams. We define a helper function $\\textit{check}(s, t)$ to achieve this. If $s$ and $t$ are not anagrams, we return $\\text{true}$; otherwise, we return $\\text{false}$.\n\nIn the function $\\textit{check}(s, t)$, we first check if the lengths of $s$ and $t$ are equal. If they are not, we return $\\text{true}$. Otherwise, we use an array $\\textit{cnt}$ of length $26$ to count the occurrences of each character in $s$, then traverse each character in $t$ and decrement $\\textit{cnt}[c]$ by $1$. If $\\textit{cnt}[c]$ is less than $0$, we return $\\text{true}$. If we traverse all characters in $t$ without issues, it means $s$ and $t$ are anagrams, and we return $\\text{false}$.\n\nThe time complexity is $O(L)$, and the space complexity is $O(|\\Sigma|)$. Here, $L$ is the length of the array $\\textit{words}$, and $\\Sigma$ is the character set, which is lowercase English letters, so $|\\Sigma| = 26$." }, "is_english": true, "time_complexity": "O(L)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 2274, "explanations": { "1": "We can sort the special floors in ascending order, then calculate the number of floors between each pair of adjacent special floors. Finally, we calculate the number of floors between the first special floor and $\\textit{bottom}$, as well as the number of floors between the last special floor and $\\textit{top}$. The maximum of these floor counts is the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array $\\textit{special}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 2275, "explanations": { "1": "The problem requires finding the maximum length of a combination of numbers where the bitwise AND result is greater than $0$. This implies that there must be a certain binary bit where all numbers have a $1$ at that position. Therefore, we can enumerate each binary bit and count the number of $1$s at that bit position for all numbers. Finally, we take the maximum count.\n\nThe time complexity is $O(n \\times \\log M)$, where $n$ and $M$ are the length of the array $\\textit{candidates}$ and the maximum value in the array, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(1)" }, { "problem_id": 2276, "explanations": { "1": "According to the problem description, we need to maintain a set of intervals that supports adding intervals and querying operations. For adding intervals, we can use a segment tree to maintain the interval set.\n\nThe segment tree divides the entire interval into multiple non-contiguous sub-intervals, with the number of sub-intervals not exceeding $\\log(width)$. To update the value of an element, we only need to update $\\log(width)$ intervals, and these intervals are all contained within a larger interval that includes the element. When modifying intervals, we need to use **lazy propagation** to ensure efficiency.\n\n- Each node of the segment tree represents an interval;\n- The segment tree has a unique root node representing the entire range, such as $[1, N]$;\n- Each leaf node of the segment tree represents a unit interval of length 1, $[x, x]$;\n- For each internal node $[l, r]$, its left child is $[l, mid]$ and its right child is $[mid+1, r]$, where $mid = \\lfloor (l + r) / 2 \\rfloor$ (i.e., floor division).\n\nSince the data range in the problem is large, we can use a dynamically opened segment tree. A dynamically opened segment tree means that we only open nodes when needed, rather than opening all nodes at the beginning, which saves space.\n\nIn terms of time complexity, each operation has a time complexity of $O(\\log n)$. The space complexity is $O(m \\times \\log n)$, where $m$ is the number of operations and $n$ is the data range." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(m \\times \\log n)" }, { "problem_id": 2277, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2278, "explanations": { "1": "We can traverse the string $\\textit{s}$ and count the number of characters that are equal to $\\textit{letter}$. Then, we calculate the percentage using the formula $\\textit{count} \\times 100 \\, / \\, \\textit{len}(\\textit{s})$.\n\nTime complexity is $O(n)$, where $n$ is the length of the string $\\textit{s}$. Space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2279, "explanations": { "1": "First, we calculate the remaining capacity of each bag, then sort the remaining capacities. Next, we traverse the remaining capacities from smallest to largest, putting the extra stones into the bags until the extra stones are used up or the remaining capacities of the bags are exhausted. Finally, we return the number of bags at this point.\n\nTime complexity is $O(n \\times \\log n)$, and space complexity is $O(\\log n)$. Here, $n$ is the number of bags." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 2280, "explanations": { "1": "需要注意:\n\n1. 只有一个点时,需要的线段数为 0;\n1. 利用除法计算斜率时,会有浮点误差,可以改成乘法比较。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2281, "explanations": { "1": "相似题目:\n\n- [907. 子数组的最小值之和](https://github.com/doocs/leetcode/blob/main/solution/0900-0999/0907.Sum%20of%20Subarray%20Minimums/README.md)" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2282, "explanations": { "1": "We observe that for the $i$-th person, the people he can see must have heights that are strictly monotonically increasing from left to right (or from top to bottom).\n\nTherefore, for each row, we can use a monotonic stack to find the number of people each person can see.\n\nSpecifically, we can traverse the array in reverse order, using a stack $stk$ that is monotonically increasing from top to bottom to record the heights of the people we have traversed.\n\nFor the $i$-th person, if the stack is not empty and the top element of the stack is less than $heights[i]$, we increment the number of people the $i$-th person can see, and then pop the top element of the stack, repeating this until the stack is empty or the top element of the stack is greater than or equal to $heights[i]$. If the stack is not empty at this point, it means the top element of the stack is greater than or equal to $heights[i]$, so we increment the number of people the $i$-th person can see by 1. Next, if the stack is not empty and the top element of the stack is equal to $heights[i]$, we pop the top element of the stack. Finally, we push $heights[i]$ onto the stack and continue to the next person.\n\nAfter processing this way, we can get the number of people each person can see for each row.\n\nSimilarly, we can process each column to get the number of people each person can see for each column. Finally, we add the answers for each row and each column to get the final answer.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(\\max(m, n))$. Where $m$ and $n$ are the number of rows and columns of the array $heights$, respectively.\n\nSimilar problems:\n\n- [1944. Number of Visible People in a Queue](https://github.com/doocs/leetcode/blob/main/solution/1900-1999/1944.Number%20of%20Visible%20People%20in%20a%20Queue/README_EN.md)" }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(\\max(m, n))" }, { "problem_id": 2283, "explanations": { "1": "We can use an array $\\textit{cnt}$ of length $10$ to count the occurrences of each digit in the string $\\textit{num}$. Then, we enumerate each digit in the string $\\textit{num}$ and check if its occurrence count equals the digit itself. If this condition is satisfied for all digits, we return $\\text{true}$; otherwise, we return $\\text{false}$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(|\\Sigma|)$. Here, $n$ is the length of the string $\\textit{num}$, and $|\\Sigma|$ is the range of possible digit values, which is $10$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 2284, "explanations": { "1": "We can use a hash table $\\textit{cnt}$ to record the word count for each sender. Then, we traverse the hash table to find the sender with the highest word count. If there are multiple senders with the highest word count, we return the name that is lexicographically largest.\n\nThe time complexity is $O(n + L)$, and the space complexity is $O(n)$, where $n$ is the number of messages and $L$ is the total length of all messages." }, "is_english": true, "time_complexity": "O(n + L)", "space_complexity": "O(n)" }, { "problem_id": 2285, "explanations": { "1": "We consider the contribution of each city to the total importance of all roads, recorded in the array $\\textit{deg}$. Then, we sort $\\textit{deg}$ by contribution from smallest to largest and allocate $[1, 2, ..., n]$ to the cities in order.\n\nThe time complexity is $O(n \\log n)$, and the space complexity is $O(n)$." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2286, "explanations": { "1": "From the problem description, we can deduce the following:\n\n- For the `gather(k, maxRow)` operation, the goal is to seat $k$ people on the same row with consecutive seats. In other words, we need to find the smallest row where the remaining seats are greater than or equal to $k$.\n- For the `scatter(k, maxRow)` operation, we just need to find $k$ seats in total, but we want to minimize the row number. Therefore, we need to find the first row that has more than $0$ seats remaining, allocate seats there, and continue searching for the rest.\n\nWe can implement this using a segment tree. Each segment tree node contains the following information:\n\n- `l`: The left endpoint of the node's interval\n- `r`: The right endpoint of the node's interval\n- `s`: The total remaining seats in the interval corresponding to the node\n- `mx`: The maximum remaining seats in the interval corresponding to the node\n\nNote that the index range for the segment tree starts from $1$.\n\nThe operations of the segment tree are as follows:\n\n- `build(u, l, r)`: Builds node $u$, corresponding to the interval $[l, r]$, and recursively builds its left and right children.\n- `modify(u, x, v)`: Starting from node $u$, finds the first node corresponding to the interval $[l, r]$ where $l = r = x$, and modifies the `s` and `mx` values of this node to $v$, then updates the tree upwards.\n- `query_sum(u, l, r)`: Starting from node $u$, calculates the sum of `s` values in the interval $[l, r]$.\n- `query_idx(u, l, r, k)`: Starting from node $u$, finds the first node in the interval $[l, r]$ where `mx` is greater than or equal to $k$, and returns the left endpoint `l` of this node. When searching, we start from the largest interval $[1, maxRow]$. Since we need to find the leftmost node with `mx` greater than or equal to $k$, we check whether the `mx` of the first half of the interval meets the condition. If so, the answer is in the first half, and we recursively search that half. Otherwise, the answer is in the second half, and we search that half recursively.\n- `pushup(u)`: Updates the information of node $u$ using the information from its children.\n\nFor the `gather(k, maxRow)` operation, we first use `query_idx(1, 1, n, k)` to find the first row where the remaining seats are greater than or equal to $k$, denoted as $i$. Then, we use `query_sum(1, i, i)` to get the remaining seats in this row, denoted as $s$. Next, we use `modify(1, i, s - k)` to modify the remaining seats of this row to $s - k$, and update the tree upwards. Finally, we return the result $[i - 1, m - s]$.\n\nFor the `scatter(k, maxRow)` operation, we first use `query_sum(1, 1, maxRow)` to calculate the total remaining seats in the first $maxRow$ rows, denoted as $s$. If $s \\lt k$, there are not enough seats, so we return `false`. Otherwise, we use `query_idx(1, 1, maxRow, 1)` to find the first row where the remaining seats are greater than or equal to $1$, denoted as $i$. Starting from this row, we use `query_sum(1, i, i)` to get the remaining seats in row $i$, denoted as $s_i$. If $s_i \\geq k$, we directly use `modify(1, i, s_i - k)` to modify the remaining seats of this row to $s_i - k$, update the tree upwards, and return `true`. Otherwise, we update $k = k - s_i$, modify the remaining seats of this row to $0$, and update the tree upwards. Finally, we return `true`.\n\nTime complexity:\n\n- The initialization time complexity is $O(n)$.\n- The time complexity of `gather(k, maxRow)` is $O(\\log n)$.\n- The time complexity of `scatter(k, maxRow)` is $O((n + q) \\times \\log n)$.\n\nThe overall time complexity is $O(n + q \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the number of rows, and $q$ is the number of operations." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2287, "explanations": { "1": "We count the occurrences of each character in the strings $\\textit{s}$ and $\\textit{target}$, denoted as $\\textit{cnt1}$ and $\\textit{cnt2}$. For each character in $\\textit{target}$, we calculate the number of times it appears in $\\textit{cnt1}$ divided by the number of times it appears in $\\textit{cnt2}$, and take the minimum value.\n\nThe time complexity is $O(n + m)$, and the space complexity is $O(|\\Sigma|)$. Where $n$ and $m$ are the lengths of the strings $\\textit{s}$ and $\\textit{target}$, respectively. And $|\\Sigma|$ is the size of the character set, which is 26 in this problem." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 2288, "explanations": { "1": "We can split the sentence into an array of words by spaces, then iterate through the array of words. For each word, if it represents a price, we update it to the price after applying the discount. Finally, we concatenate the updated array of words into a space-separated string.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string `sentence`." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2289, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2290, "explanations": { "1": "This problem is essentially a shortest path model, but we need to find the minimum number of obstacles to remove.\n\nIn an undirected graph with edge weights of only $0$ and $1$, we can use a double-ended queue to perform BFS. The principle is that if the weight of the current point that can be expanded is $0$, it is added to the front of the queue; if the weight is $1$, it is added to the back of the queue.\n\n> If the weight of an edge is $0$, then the newly expanded node has the same weight as the current front node, and it can obviously be used as the starting point for the next expansion.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Where $m$ and $n$ are the number of rows and columns of the grid, respectively.\n\nSimilar problems:\n\n- [1368. Minimum Cost to Make at Least One Valid Path in a Grid](https://github.com/doocs/leetcode/blob/main/solution/1300-1399/1368.Minimum%20Cost%20to%20Make%20at%20Least%20One%20Valid%20Path%20in%20a%20Grid/README_EN.md)" }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 2291, "explanations": { "1": "We define $f[i][j]$ to represent the maximum profit when considering the first $i$ stocks with a budget of $j$. The answer is $f[n][\\textit{budget}]$.\n\nFor the $i$-th stock, we have two choices:\n\n- Do not buy it, then $f[i][j] = f[i - 1][j]$;\n- Buy it, then $f[i][j] = f[i - 1][j - \\textit{present}[i]] + \\textit{future}[i] - \\textit{present}[i]$.\n\nFinally, return $f[n][\\textit{budget}]$.\n\nThe time complexity is $O(n \\times \\textit{budget})$, and the space complexity is $O(n \\times \\textit{budget})$. Where $n$ is the length of the array.", "2": "We can observe that for each row, we only need the values from the previous row, so we can optimize the space complexity to $O(\\text{budget})$." }, "is_english": true, "time_complexity": "O(n \\times \\textit{budget})", "space_complexity": "O(n \\times \\textit{budget})" }, { "problem_id": 2292, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2293, "explanations": { "1": "According to the problem statement, we can simulate the entire process, and the remaining number will be the answer. In implementation, we do not need to create an additional array; we can directly operate on the original array.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2294, "explanations": { "1": "The problem requires dividing into subsequences, not subarrays, so the elements in a subsequence can be non-continuous. We can sort the array $\\textit{nums}$. Assuming the first element of the current subsequence is $a$, the difference between the maximum and minimum values in the subsequence will not exceed $k$. Therefore, we can iterate through the array $\\textit{nums}$. If the difference between the current element $b$ and $a$ is greater than $k$, then update $a$ to $b$ and increase the number of subsequences by 1. After the iteration, we can obtain the minimum number of subsequences, noting that the initial number of subsequences is $1$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 2295, "explanations": { "1": "First, we use a hash table $d$ to record the indices of each number in the array $\\textit{nums}$. Then, we iterate through the operation array $\\textit{operations}$. For each operation $[x, y]$, we replace the number at index $d[x]$ in $\\textit{nums}$ with $y$, and update the index of $y$ in $d$ to $d[x]$.\n\nFinally, we return $\\textit{nums}$.\n\nThe time complexity is $O(n + m)$, and the space complexity is $O(n)$. Here, $n$ and $m$ are the lengths of the array $\\textit{nums}$ and the operation array $\\textit{operations}$, respectively." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(n)" }, { "problem_id": 2296, "explanations": { "1": "We can use two stacks, $\\textit{left}$ and $\\textit{right}$, where the stack $\\textit{left}$ stores the characters to the left of the cursor, and the stack $\\textit{right}$ stores the characters to the right of the cursor.\n\n- When calling the $\\text{addText}$ method, we push the characters in $\\text{text}$ onto the $\\text{left}$ stack one by one. The time complexity is $O(|\\text{text}|)$.\n- When calling the $\\text{deleteText}$ method, we pop characters from the $\\text{left}$ stack up to $k$ times. The time complexity is $O(k)$.\n- When calling the $\\text{cursorLeft}$ method, we pop characters from the $\\text{left}$ stack up to $k$ times, then push the popped characters onto the $\\text{right}$ stack one by one, and finally return up to 10 characters from the $\\text{left}$ stack. The time complexity is $O(k)$.\n- When calling the $\\text{cursorRight}$ method, we pop characters from the $\\text{right}$ stack up to $k$ times, then push the popped characters onto the $\\text{left}$ stack one by one, and finally return up to 10 characters from the $\\text{left}$ stack. The time complexity is $O(k)$." }, "is_english": true, "time_complexity": "O(|\\text{text}|)", "space_complexity": null }, { "problem_id": 2297, "explanations": { "1": "According to the problem description, we need to find the next position $j$ where $\\textit{nums}[j]$ is greater than or equal to $\\textit{nums}[i]$, and the next position $j$ where $\\textit{nums}[j]$ is less than $\\textit{nums}[i]$. We can use a monotonic stack to find these two positions in $O(n)$ time, and then construct an adjacency list $g$, where $g[i]$ represents the indices that index $i$ can jump to.\n\nThen we use dynamic programming to find the minimum cost. Let $f[i]$ represent the minimum cost to jump to index $i$. Initially, $f[0] = 0$ and the rest $f[i] = \\infty$. We enumerate the indices $i$ from small to large. For each $i$, we enumerate each index $j$ in $g[i]$ and perform the state transition $f[j] = \\min(f[j], f[i] + \\textit{costs}[j])$. The answer is $f[n - 1]$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2298, "explanations": { "1": "`WEEKDAY()` 函数返回日期的工作日编号,从 0 开始,0 表示星期一,1 表示星期二,以此类推,6 表示星期日。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2299, "explanations": { "1": "According to the problem description, we can simulate the process of checking whether the password meets the requirements.\n\nFirst, we check if the length of the password is less than $8$. If it is, we return $\\textit{false}$.\n\nNext, we use a mask $\\textit{mask}$ to record whether the password contains lowercase letters, uppercase letters, digits, and special characters. We traverse the password, and for each character, we first check if it is the same as the previous character. If it is, we return $\\textit{false}$. Then, we update the mask $\\textit{mask}$ based on the character type. Finally, we check if the mask $\\textit{mask}$ is $15$. If it is, we return $\\textit{true}$; otherwise, we return $\\textit{false}$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the password." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2300, "explanations": { "1": "We can sort the potion array, then traverse the spell array. For each spell $v$, we use binary search to find the first potion that is greater than or equal to $\\frac{success}{v}$. We mark its index as $i$. The length of the potion array minus $i$ is the number of potions that can successfully combine with this spell.\n\nThe time complexity is $O((m + n) \\times \\log m)$, and the space complexity is $O(\\log n)$. Here, $m$ and $n$ are the lengths of the potion array and the spell array, respectively." }, "is_english": true, "time_complexity": "O((m + n) \\times \\log m)", "space_complexity": "O(\\log n)" }, { "problem_id": 2301, "explanations": { "1": "First, we use a hash table $d$ to record the set of characters that each character can be replaced with.\n\nThen we enumerate all substrings of length $sub$ in $s$, and judge whether the string $sub$ can be obtained by replacement. If it can, return `true`, otherwise enumerate the next substring.\n\nAt the end of the enumeration, it means that $sub$ cannot be obtained by replacing any substring in $s$, so return `false`.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(C^2)$. Here, $m$ and $n$ are the lengths of the strings $s$ and $sub$ respectively, and $C$ is the size of the character set.", "2": "Since the character set only contains uppercase and lowercase English letters and numbers, we can directly use a $128 \\times 128$ array $d$ to record the set of characters that each character can be replaced with.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(C^2)$." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(C^2)" }, { "problem_id": 2302, "explanations": { "1": "First, we calculate the prefix sum array $s$ of the array $\\textit{nums}$, where $s[i]$ represents the sum of the first $i$ elements of $\\textit{nums}$.\n\nNext, we enumerate each element of $\\textit{nums}$ as the last element of a subarray. For each element, we can use binary search to find the maximum length $l$ such that $s[i] - s[i - l] \\times l < k$. The number of subarrays ending at this element is $l$, and summing up all $l$ gives the final answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$.", "2": "We can use the two-pointer technique to maintain a sliding window such that the sum of elements in the window is less than $k$. The number of subarrays ending at the current element is equal to the length of the window. Summing up all the window lengths gives the final answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2303, "explanations": { "1": "We traverse `brackets`, and for each tax bracket, we calculate the tax amount for that bracket, then accumulate it.\n\nThe time complexity is $O(n)$, where $n$ is the length of `brackets`. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2304, "explanations": { "1": "We define $f[i][j]$ to represent the minimum path cost from the first row to the $i$th row and $j$th column. Since we can only move from a column in the previous row to a column in the current row, the value of $f[i][j]$ can be transferred from $f[i - 1][k]$, where the range of $k$ is $[0, n - 1]$. Therefore, the state transition equation is:\n\n$$\nf[i][j] = \\min_{0 \\leq k < n} \\{f[i - 1][k] + \\textit{moveCost}[grid[i - 1][k]][j] + grid[i][j]\\}\n$$\n\nwhere $\\textit{moveCost}[grid[i - 1][k]][j]$ represents the cost of moving from the $k$th column of the $i - 1$th row to the $j$th column of the $i$th row.\n\nThe final answer is $\\min_{0 \\leq j < n} \\{f[m - 1][j]\\}$.\n\nSince each transition only needs the state of the previous row, we can use a rolling array to optimize the space complexity to $O(n)$.\n\nThe time complexity is $O(m \\times n^2)$, and the space complexity is $O(n)$. Here, $m$ and $n$ are the number of rows and columns of the grid, respectively." }, "is_english": true, "time_complexity": "O(m \\times n^2)", "space_complexity": "O(n)" }, { "problem_id": 2305, "explanations": { "1": "First, we sort the array $cookies$ in descending order (to reduce the number of searches), and then create an array $cnt$ of length $k$ to store the number of cookies each child gets. Also, we use a variable $ans$ to maintain the current minimum degree of unfairness, initialized to a very large value.\n\nNext, we start from the first snack pack. For the current snack pack $i$, we enumerate each child $j$. If the cookies $cookies[i]$ in the current snack pack are given to child $j$, making the degree of unfairness greater than or equal to $ans$, or the number of cookies the current child already has is the same as the previous child, then we don't need to consider giving the cookies in the current snack pack to child $j$, just skip it (pruning). Otherwise, we give the cookies $cookies[i]$ in the current snack pack to child $j$, and then continue to consider the next snack pack. When we have considered all the snack packs, we update the value of $ans$, then backtrack to the previous snack pack, and continue to enumerate which child to give the cookies in the current snack pack to.\n\nFinally, we return $ans$." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 2306, "explanations": { "1": "We define $f[i][j]$ to represent the number of strings in $\\textit{ideas}$ that start with the $i$-th letter and, when replaced with the $j$-th letter, do not exist in $\\textit{ideas}$. Initially, $f[i][j] = 0$. Additionally, we use a hash table $s$ to record the strings in $\\textit{ideas}$, allowing us to quickly determine whether a string is in $\\textit{ideas}$.\n\nNext, we traverse the strings in $\\textit{ideas}$. For the current string $v$, we enumerate the first letter $j$ after replacement. If the string obtained by replacing $v$ is not in $\\textit{ideas}$, we update $f[i][j] = f[i][j] + 1$.\n\nFinally, we traverse the strings in $\\textit{ideas}$ again. For the current string $v$, we enumerate the first letter $j$ after replacement. If the string obtained by replacing $v$ is not in $\\textit{ideas}$, we update the answer $\\textit{ans} = \\textit{ans} + f[j][i]$.\n\nThe final answer is $\\textit{ans}$.\n\nThe time complexity is $O(n \\times m \\times |\\Sigma|)$, and the space complexity is $O(|\\Sigma|^2)$. Here, $n$ and $m$ are the number of strings in $\\textit{ideas}$ and the maximum length of the strings, respectively, and $|\\Sigma|$ is the character set of the strings, with $|\\Sigma| \\leq 26$ in this problem." }, "is_english": true, "time_complexity": "O(n \\times m \\times |\\Sigma|)", "space_complexity": "O(|\\Sigma|^2)" }, { "problem_id": 2307, "explanations": { "1": "First, we convert the strings into integers starting from $0$. Then, we traverse all the equations, map the two strings in each equation to the corresponding integers $a$ and $b$. If these two integers are not in the same set, we merge them into the same set and record the weights of the two integers, which is the ratio of $a$ to $b$. If these two integers are in the same set, we check whether their weights satisfy the equation. If not, we return `true`.\n\nThe time complexity is $O(n \\times \\log n)$ or $O(n \\times \\alpha(n))$, and the space complexity is $O(n)$. Here, $n$ is the number of equations.\n\nSimilar problems:\n\n- [399. Evaluate Division](https://github.com/doocs/leetcode/blob/main/solution/0300-0399/0399.Evaluate%20Division/README_EN.md)" }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2308, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2309, "explanations": { "1": "First, we use a hash table $ss$ to record all the letters that appear in the string $s$. Then we start enumerating from the last letter of the uppercase alphabet. If both the uppercase and lowercase forms of the current letter are in $ss$, we return that letter.\n\nAt the end of the enumeration, if no letter that meets the conditions is found, we return an empty string.\n\nThe time complexity is $O(n)$, and the space complexity is $O(C)$. Here, $n$ and $C$ are the length of the string $s$ and the size of the character set, respectively.", "2": "We can use two integers $mask1$ and $mask2$ to record the lowercase and uppercase letters that appear in the string $s$, respectively. The $i$-th bit of $mask1$ indicates whether the $i$-th lowercase letter appears, and the $i$-th bit of $mask2$ indicates whether the $i$-th uppercase letter appears.\n\nThen we perform a bitwise AND operation on $mask1$ and $mask2$. The $i$-th bit of the resulting $mask$ indicates whether the $i$-th letter appears in both uppercase and lowercase.\n\nNext, we just need to get the position of the highest $1$ in the binary representation of $mask$, and convert it to the corresponding uppercase letter. If all binary bits are not $1$, it means that there is no letter that appears in both uppercase and lowercase, so we return an empty string.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(C)" }, { "problem_id": 2310, "explanations": { "1": "Each number that meets the splitting condition can be represented as $10x_i + k$. If there are $n$ such numbers, then $\\textit{num} - n \\times k$ must be a multiple of $10$.\n\nWe enumerate $n$ from small to large, and find the first $n$ that satisfies $\\textit{num} - n \\times k$ being a multiple of $10$. Since $n$ cannot exceed $\\textit{num}$, the maximum value of $n$ is $\\textit{num}$.\n\nWe can also only consider the units digit. If the units digit satisfies the condition, the higher digits can be arbitrary.\n\nThe time complexity is $O(n)$, where $n$ is the size of $\\textit{num}$. The space complexity is $O(1)$.", "2": "", "3": "" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2311, "explanations": { "1": "The longest binary subsequence must include all the $0$s in the original string. On this basis, we traverse $s$ from right to left. If we encounter a $1$, we check if adding this $1$ to the subsequence keeps the binary number $v \\leq k$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2312, "explanations": { "1": "First, we define a 2D array $d$, where $d[i][j]$ represents the price of a wood block with height $i$ and width $j$.\n\nThen, we design a function $dfs(h, w)$ to denote the maximum amount of money obtained by cutting a wood block with height $h$ and width $w$. The answer will be $dfs(m, n)$.\n\nThe process of function $dfs(h, w)$ is as follows:\n\n- If $(h, w)$ has been calculated before, return the answer directly.\n- Otherwise, initialize the answer as $d[h][w]$, then enumerate the cutting positions, calculate the maximum amount of money obtained by cutting the wood block into two pieces, and take the maximum value.\n\nThe time complexity is $O(m \\times n \\times (m + n) + p)$, and the space complexity is $O(m \\times n)$. Here, $p$ represents the length of the price array, while $m$ and $n$ represent the height and width of the wood blocks, respectively.", "2": "We can transform the memoization search in Solution 1 into dynamic programming.\n\nSimilar to Solution 1, we define a 2D array $d$, where $d[i][j]$ represents the price of a wood block with height $i$ and width $j$. Initially, we iterate through the price array $prices$ and store the price $p$ of each wood block $(h, w, p)$ in $d[h][w]$, while the rest of the prices are set to $0$.\n\nThen, we define another 2D array $f$, where $f[i][j]$ represents the maximum amount of money obtained by cutting a wood block with height $i$ and width $j$. The answer will be $f[m][n]$.\n\nConsidering how $f[i][j]$ transitions, initially $f[i][j] = d[i][j]$. We enumerate the cutting positions, calculate the maximum amount of money obtained by cutting the wood block into two pieces, and take the maximum value.\n\nThe time complexity is $O(m \\times n \\times (m + n) + p)$, and the space complexity is $O(m \\times n)$. Here, $p$ represents the length of the price array, while $m$ and $n$ represent the height and width of the wood blocks, respectively.\n\nSimilar problems:\n\n- [1444. Number of Ways of Cutting a Pizza](https://github.com/doocs/leetcode/blob/main/solution/1400-1499/1444.Number%20of%20Ways%20of%20Cutting%20a%20Pizza/README_EN.md)" }, "is_english": true, "time_complexity": "O(m \\times n \\times (m + n) + p)", "space_complexity": "O(m \\times n)" }, { "problem_id": 2313, "explanations": { "1": "We define a function $dfs(root)$, which returns an array of length 2. The first element represents the minimum number of flips needed to change the value of the $root$ node to `false`, and the second element represents the minimum number of flips needed to change the value of the $root$ node to `true`. The answer is $dfs(root)[result]$.\n\nThe implementation of the function $dfs(root)$ is as follows:\n\nIf $root$ is null, return $[+\\infty, +\\infty]$.\n\nOtherwise, let $x$ be the value of $root$, $l$ be the return value of the left subtree, and $r$ be the return value of the right subtree. Then we discuss the following cases:\n\n- If $x \\in \\{0, 1\\}$, return $[x, x \\oplus 1]$.\n- If $x = 2$, which means the boolean operator is `OR`, to make the value of $root$ `false`, we need to make both the left and right subtrees `false`. Therefore, the first element of the return value is $l[0] + r[0]$. To make the value of $root$ `true`, we need at least one of the left or right subtrees to be `true`. Therefore, the second element of the return value is $\\min(l[0] + r[1], l[1] + r[0], l[1] + r[1])$.\n- If $x = 3$, which means the boolean operator is `AND`, to make the value of $root$ `false`, we need at least one of the left or right subtrees to be `false`. Therefore, the first element of the return value is $\\min(l[0] + r[0], l[0] + r[1], l[1] + r[0])$. To make the value of $root$ `true`, we need both the left and right subtrees to be `true`. Therefore, the second element of the return value is $l[1] + r[1]$.\n- If $x = 4$, which means the boolean operator is `XOR`, to make the value of $root$ `false`, we need both the left and right subtrees to be either `false` or `true`. Therefore, the first element of the return value is $\\min(l[0] + r[0], l[1] + r[1])$. To make the value of $root$ `true`, we need the left and right subtrees to be different. Therefore, the second element of the return value is $\\min(l[0] + r[1], l[1] + r[0])$.\n- If $x = 5$, which means the boolean operator is `NOT`, to make the value of $root$ `false`, we need at least one of the left or right subtrees to be `true`. Therefore, the first element of the return value is $\\min(l[1], r[1])$. To make the value of $root$ `true`, we need at least one of the left or right subtrees to be `false`. Therefore, the second element of the return value is $\\min(l[0], r[0])$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2314, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2315, "explanations": { "1": "We define an integer variable $\\textit{ok}$ to indicate whether we can count when encountering `*`. Initially, $\\textit{ok}=1$, meaning we can count.\n\nTraverse the string $s$. If we encounter `*`, we decide whether to count based on the value of $\\textit{ok}$. If we encounter `|`, we toggle the value of $\\textit{ok}$.\n\nFinally, return the count result.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2316, "explanations": { "1": "For any two nodes in an undirected graph, if there is a path between them, then they are mutually reachable.\n\nTherefore, we can use depth-first search to find the number of nodes $t$ in each connected component, and then multiply the current number of nodes $t$ in the connected component by the number of nodes $s$ in all previous connected components to obtain the number of unreachable node pairs in the current connected component, which is $s \\times t$. Then, we add $t$ to $s$ and continue to search for the next connected component until all connected components have been searched, and we can obtain the final answer.\n\nThe time complexity is $O(n + m)$, and the space complexity is $O(n + m)$. Here, $n$ and $m$ are the number of nodes and edges, respectively." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(n + m)" }, { "problem_id": 2317, "explanations": { "1": "In one operation, we can update $\\textit{nums}[i]$ to $\\textit{nums}[i] \\text{ AND } (\\textit{nums}[i] \\text{ XOR } x)$. Since $x$ is any non-negative integer, the result of $\\textit{nums}[i] \\oplus x$ can be any value. By performing a bitwise AND operation with $\\textit{nums}[i]$, we can change some of the $1$ bits in the binary representation of $\\textit{nums}[i]$ to $0$.\n\nThe problem requires us to find the maximum bitwise XOR sum of all elements in $\\textit{nums}$. For a binary bit, as long as there is an element in $\\textit{nums}$ with the corresponding binary bit set to $1$, the contribution of this binary bit to the maximum bitwise XOR sum is $1$. Therefore, the answer is the result of the bitwise OR operation of all elements in $\\textit{nums}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2318, "explanations": { "1": "三维 DP。\n\n设 $dp[k][i][j]$ 表示序列长度为 $k$,且序列的最后两个数字分别为 $i$, $j$ 的所有满足要求的不同序列的数量。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2319, "explanations": { "1": "We can directly traverse the matrix and check if each element satisfies the conditions of an $X$ matrix. If any element does not satisfy the conditions, return $\\textit{false}$ immediately. If all elements satisfy the conditions after traversal, return $\\textit{true}$.\n\nThe time complexity is $O(n^2)$, where $n$ is the number of rows or columns of the matrix. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(1)" }, { "problem_id": 2320, "explanations": { "1": "Since the placement of houses on both sides of the street does not affect each other, we can consider the placement on one side only, and then square the number of ways for one side to get the final result modulo.\n\nWe define $f[i]$ to represent the number of ways to place houses on the first $i+1$ plots, with the last plot having a house. We define $g[i]$ to represent the number of ways to place houses on the first $i+1$ plots, with the last plot not having a house. Initially, $f[0] = g[0] = 1$.\n\nWhen placing the $(i+1)$-th plot, there are two cases:\n\n- If the $(i+1)$-th plot has a house, then the $i$-th plot must not have a house, so the number of ways is $f[i] = g[i-1]$;\n- If the $(i+1)$-th plot does not have a house, then the $i$-th plot can either have a house or not, so the number of ways is $g[i] = f[i-1] + g[i-1]$.\n\nFinally, we square $f[n-1] + g[n-1]$ modulo to get the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the street." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2321, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2322, "explanations": { "1": "We denote the XOR sum of the tree as $s$, i.e., $s = \\text{nums}[0] \\oplus \\text{nums}[1] \\oplus \\ldots \\oplus \\text{nums}[n-1]$.\n\nNext, we enumerate each node $i$ in $[0..n)$ as the root of the tree, and treat the edge connecting the root node to some child node $j$ as the first edge to be removed. This gives us two connected components. We denote the XOR sum of the connected component containing root node $i$ as $s_1$, then we perform DFS on the connected component containing root node $i$ to calculate the XOR sum of each subtree, denoting each XOR sum calculated by DFS as $s_2$. The XOR sums of the three connected components are $s \\oplus s_1$, $s_2$, and $s_1 \\oplus s_2$. We need to calculate the maximum and minimum values of these three XOR sums, denoted as $\\textit{mx}$ and $\\textit{mn}$. For each enumerated case, the score is $\\textit{mx} - \\textit{mn}$. We find the minimum value among all cases as the answer.\n\nThe XOR sum of each subtree can be calculated through DFS. We define a function $\\text{dfs}(i, fa)$, which represents starting DFS from node $i$, where $fa$ is the parent node of node $i$. The function returns the XOR sum of the subtree rooted at node $i$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$, where $n$ is the number of nodes in the tree." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 2323, "explanations": { "1": "To minimize the number of days required to complete all jobs, we can try to assign longer jobs to workers who can work longer hours.\n\nTherefore, we can first sort $\\textit{jobs}$ and $\\textit{workers}$, then assign jobs to workers based on their indices. Finally, we calculate the maximum ratio of job time to worker time.\n\nThe time complexity is $O(n \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the number of jobs." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 2324, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2325, "explanations": { "1": "我们可以使用数组或哈希表 $d$ 存储对照表,然后遍历 `message` 中的每个字符,将其替换为对应的字符即可。\n\n时间复杂度 $O(m + n)$,空间复杂度 $O(C)$。其中 $m$ 和 $n$ 分别为 `key` 和 `message` 的长度;而 $C$ 为字符集大小。" }, "is_english": false, "time_complexity": "O(m + n)", "space_complexity": "O(C)" }, { "problem_id": 2326, "explanations": { "1": "We define a two-dimensional array $\\textit{ans}$ to store the elements in the linked list, initially all filled with $-1$. We define three variables $i, j, k$, representing the current row, column, and direction respectively. We define an array $\\textit{dirs}$ to represent the offsets of the four directions.\n\nThen we start traversing the linked list. Each time we traverse a node, we fill the current node's value into $\\textit{ans}[i][j]$, then update the linked list pointer. If the linked list is empty, it means all elements have been filled and we exit the loop.\n\nOtherwise, we need to find the position of the next element. We can calculate the next position $(x, y)$ through the current position $(i, j)$ and the current direction $k$. If $(x, y)$ is within the range of the matrix, and $\\textit{ans}[x][y]$ is $-1$, it means $(x, y)$ has not been filled yet, so we take $(x, y)$ as the next position. Otherwise, we need to change the direction.\n\nAfter traversing the linked list, we get a spiral matrix and return it.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$, where $m$ and $n$ represent the number of rows and columns of the matrix, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 2327, "explanations": { "1": "We use a difference array $d[i]$ to record the change in the number of people who know the secret on day $i$, and an array $cnt[i]$ to record the number of people who newly learn the secret on day $i$.\n\nFor the $cnt[i]$ people who newly learn the secret on day $i$, they can share the secret with another $cnt[i]$ people each day during the interval $[i+\\text{delay}, i+\\text{forget})$.\n\nThe answer is $\\sum_{i=1}^{n} d[i]$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$, where $n$ is the given integer." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 2328, "explanations": { "1": "We design a function $dfs(i, j)$, which represents the number of strictly increasing paths that can be reached from the grid graph starting at the $i$-th row and $j$-th column. Then the answer is $\\sum_{i=0}^{m-1} \\sum_{j=0}^{n-1} dfs(i, j)$. In the search process, we can use a two-dimensional array $f$ to record the calculated results to avoid repeated calculation.\n\nThe calculation process of the function $dfs(i, j)$ is as follows:\n\n- If $f[i][j]$ is not $0$, it means that it has been calculated, and $f[i][j]$ is returned directly;\n- Otherwise, we initialize $f[i][j] = 1$, and then enumerate the four directions of $(i, j)$. If the grid $(x, y)$ in a certain direction satisfies $0 \\leq x \\lt m$, $0 \\leq y \\lt n$, and $grid[i][j] \\lt grid[x][y]$, we can start from the grid $(i, j)$ to the grid $(x, y)$, and the number on the path is strictly increasing, so $f[i][j] += dfs(x, y)$.\n\nFinally, we return $f[i][j]$.\n\nThe answer is $\\sum_{i=0}^{m-1} \\sum_{j=0}^{n-1} dfs(i, j)$.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Where $m$ and $n$ are the number of rows and columns in the grid graph, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 2329, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2330, "explanations": { "1": "We can use two pointers $i$ and $j$, pointing to the beginning and end of the string, respectively, and then move towards the center, counting the number of different characters. If the number of different characters is greater than $2$, return $\\textit{false}$; otherwise, return $\\textit{true}$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2331, "explanations": { "1": "We can use recursion to solve this problem.\n\nFor the current node $\\textit{root}$:\n\n- If its left child is null, it means the current node is a leaf node. If the value of the current node is $1$, then return $\\textit{true}$; otherwise, return $\\textit{false}$;\n- If the value of the current node is $2$, then return the logical OR of the recursion results of its left and right children; otherwise, return the logical AND of the recursion results of its left and right children.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2332, "explanations": { "1": "First, we sort, and then use double pointers to simulate the process of passengers getting on the bus: traverse the bus $bus$, passengers follow the principle of \"first come, first served\".\n\nAfter the simulation ends, judge whether the last bus still has seats:\n\n- If there are seats, we can arrive at the bus station when the bus departs at $bus[|bus|-1]$; if there are people at this time, we can find the time when no one arrives by going forward.\n- If there are no seats, we can find the last passenger who got on the bus, and find the time when no one arrives by going forward from him.\n\nThe time complexity is $O(n \\times \\log n + m \\times \\log m)$, and the space complexity is $O(\\log n + \\log m)$. Where $n$ and $m$ are the numbers of buses and passengers respectively." }, "is_english": true, "time_complexity": "O(n \\times \\log n + m \\times \\log m)", "space_complexity": "O(\\log n + \\log m)" }, { "problem_id": 2333, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2334, "explanations": { "1": "考虑**从大到小遍历**数组 $nums$ 中的每个元素 $v$,用并查集来维护以 $v$ 作为子数组最小值的连通块。\n\n遍历过程中:\n\n$v$ 在数组 $nums$ 中的下标为 $i$,若下标 $i-1$ 对应的元素遍历过,可以将 $i-1$ 与 $i$ 进行合并,同理,若下标 $i+1$ 对应的元素也遍历过了,将 $i$ 与 $i+1$ 合并。合并过程中更新连通块的大小。\n\n$v$ 作为当前连通块的最小值,当前连通块的大小为 $size[find(i)]$,若 $v>\\frac{\\textit{threshold}}{size[find(i)]}$,说明找到了满足条件的子数组,返回 $true$。\n\n否则遍历结束,返回 $-1$。\n\n时间复杂度 $O(nlogn)$。\n\n相似题目:\n\n- [1562. 查找大小为 M 的最新分组](https://github.com/doocs/leetcode/blob/main/solution/1500-1599/1562.Find%20Latest%20Group%20of%20Size%20M/README.md)", "2": "利用单调栈,得到以当前元素 $nums[i]$ 作为最小元素的左右边界 $left[i]$(左边第一个比 $nums[i]$ 小的元素的位置), $right[i]$(右边第一个比 $nums[i]$ 小的元素的位置)。\n\n那么对于当前元素 $nums[i]$,有 $k=right[i]-left[i]-1$,若 $nums[i]>\\frac{\\textit{threshold}}{k}$,说明找到了满足条件的子数组,返回 $true$。\n\n否则遍历结束,返回 $-1$。\n\n时间复杂度 $O(n)$。" }, "is_english": false, "time_complexity": "O(nlogn)", "space_complexity": null }, { "problem_id": 2335, "explanations": { "1": "我们可以每次贪心地选择其中较大的两个数进行减一操作(最多减为 $0$),直至所有数变为 $0$。\n\n时间复杂度 $O(S)$,空间复杂度 $O(1)$。其中 $S$ 为数组 `amount` 中所有数的和,本题中 $S \\leq 300$。", "2": "我们可以将数组 `amount` 排序,设 $a$, $b$, $c$ 分别为数组 `amount` 中的三个数,有以下两种情况:\n\n- 如果 $a + b \\leq c$,此时我们只需要 $c$ 次操作即可将所有数变为 $0$,因此答案为 $c$。\n- 如果 $a + b > c$,每一次操作我们都可以将其中两个数减一,最终匹配完,或者剩下最后一个数(取决于总和是偶数还是奇数),因此答案为 $\\left \\lfloor \\frac{a + b + c + 1}{2} \\right \\rfloor$。\n\n时间复杂度 $O(1)$,空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(S)", "space_complexity": "O(1)" }, { "problem_id": 2336, "explanations": { "1": "We note that the range of elements in the set given by the problem is $[1, 1000]$, and the operations we need to support are:\n\n- `popSmallest`: Pop the smallest element from the set\n- `addBack`: Add an element back to the set\n\nTherefore, we can use an ordered set to simulate this. Let's denote the ordered set as $s$, and the elements in the set as $s_1, s_2, \\cdots, s_n$, where $n$ is the number of elements in the ordered set. In this problem, $n \\le 1000$.\n\nDuring initialization, we add all elements in $[1, 1000]$ to the ordered set. The time complexity is $O(n \\times \\log n)$.\n\nIn the `popSmallest` operation, we just need to pop the first element from the ordered set. The time complexity for a single operation is $O(\\log n)$.\n\nIn the `addBack` operation, we just need to add the element back to the ordered set. The time complexity for a single operation is $O(\\log n)$.\n\nThe space complexity is $O(n)$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2337, "explanations": { "1": "替换操作实际上是将 `L` 往左移动(`L` 左边为 `_` 时才能移动),`R` 往右移动(`R` 右边是 `_` 时才能移动),但 `L` 无法穿过 `R`。所以,如果去掉 `start` 和 `target` 中的所有 `_`,剩下的字符应该是相同的,否则返回 `false`。\n\n我们使用双指针 $i$ 和 $j$ 从头到尾遍历 `start` 和 `target`:\n\n- 如果当前字符为 `L` 且 $i\\lt j$,那么这个 `L` 无法向右移动,返回 `false`;\n- 如果当前字符为 `R` 且 $i\\gt j$,那么这个 `R` 无法向左移动,返回 `false`。\n\n如果双指针均遍历到末尾,返回 `true`。\n\n时间复杂度 $O(n)$,其中 $n$ 表示字符串 `start` 或 `target` 的长度。\n\n相似题目:\n\n- [777. 在 LR 字符串中交换相邻字符](https://github.com/doocs/leetcode/blob/main/solution/0700-0799/0777.Swap%20Adjacent%20in%20LR%20String/README.md)", "2": "" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": null }, { "problem_id": 2338, "explanations": { "1": "Let $f[i][j]$ represent the number of sequences ending with $i$ and consisting of $j$ distinct elements. The initial value is $f[i][1] = 1$.\n\nConsider $n$ balls, which are eventually divided into $j$ parts. Using the \"separator method,\" we can insert $j-1$ separators into the $n-1$ positions, and the number of combinations is $c_{n-1}^{j-1}$.\n\nWe can preprocess the combination numbers $c[i][j]$ using the recurrence relation $c[i][j] = c[i-1][j] + c[i-1][j-1]$. Specifically, when $j=0$, $c[i][j] = 1$.\n\nThe final answer is:\n\n$$\n\\sum\\limits_{i=1}^{k}\\sum\\limits_{j=1}^{\\log_2 k + 1} f[i][j] \\times c_{n-1}^{j-1}\n$$\n\nwhere $k$ represents the maximum value of the array, i.e., $\\textit{maxValue}$.\n\n- **Time Complexity**: $O(m \\times \\log^2 m)$\n- **Space Complexity**: $O(m \\times \\log m)$", "2": "" }, "is_english": true, "time_complexity": "O(m \\times \\log^2 m)", "space_complexity": "O(m \\times \\log m)" }, { "problem_id": 2339, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2340, "explanations": { "1": "We can use indices $i$ and $j$ to record the index of the first minimum value and the last maximum value in the array $\\textit{nums}$, respectively. Traverse the array $\\textit{nums}$ to update the values of $i$ and $j$.\n\nNext, we need to consider the number of swaps.\n\n- If $i = j$, it means the array $\\textit{nums}$ is already a valid array, and no swaps are needed. Return $0$.\n- If $i < j$, it means the minimum value in the array $\\textit{nums}$ is to the left of the maximum value. The number of swaps needed is $i + n - 1 - j$, where $n$ is the length of the array $\\textit{nums}$.\n- If $i > j$, it means the minimum value in the array $\\textit{nums}$ is to the right of the maximum value. The number of swaps needed is $i + n - 1 - j - 1$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2341, "explanations": { "1": "We can count the occurrences of each number $x$ in the array $\\textit{nums}$ and record them in a hash table or array $\\textit{cnt}$.\n\nThen, we traverse $\\textit{cnt}$. For each number $x$, if the occurrence count $v$ of $x$ is greater than $1$, we can select two $x$'s from the array to form a pair. We divide $v$ by $2$ and take the floor value to get the number of pairs that can be formed by the current number $x$. We then add this number to the variable $s$.\n\nThe remaining count is the length of the array $\\textit{nums}$ minus the number of pairs formed multiplied by $2$, i.e., $n - s \\times 2$.\n\nThe answer is $[s, n - s \\times 2]$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(C)$. Here, $n$ is the length of the array $\\textit{nums}$, and $C$ is the range of numbers in the array $\\textit{nums}$, which is $101$ in this problem." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(C)" }, { "problem_id": 2342, "explanations": { "1": "We can use a hash table $d$ to record the maximum value corresponding to each digit sum, and initialize an answer variable $ans = -1$.\n\nNext, we traverse the array $nums$. For each number $v$, we calculate its digit sum $x$. If $x$ exists in the hash table $d$, then we update the answer $ans = \\max(ans, d[x] + v)$. Then update the hash table $d[x] = \\max(d[x], v)$.\n\nFinally, return the answer $ans$.\n\nSince the maximum element in $nums$ is $10^9$, the maximum digit sum is $9 \\times 9 = 81$. We can directly define an array $d$ of length $100$ to replace the hash table.\n\nThe time complexity is $O(n \\times \\log M)$, and the space complexity is $O(D)$. Here, $n$ is the length of the array $nums$, and $M$ and $D$ are the maximum value of the elements in the array $nums$ and the maximum value of the digit sum, respectively. In this problem, $M \\leq 10^9$, $D \\leq 81$." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(D)" }, { "problem_id": 2343, "explanations": { "1": "According to the problem description, we can simulate the cropping process, then sort the cropped strings, and finally find the corresponding number based on the index.\n\nThe time complexity is $O(m \\times n \\times \\log n \\times s)$, and the space complexity is $O(n)$. Here, $m$ and $n$ are the lengths of $\\textit{nums}$ and $\\textit{queries}$ respectively, and $s$ is the length of the string $\\textit{nums}[i]$." }, "is_english": true, "time_complexity": "O(m \\times n \\times \\log n \\times s)", "space_complexity": "O(n)" }, { "problem_id": 2344, "explanations": { "1": "如果一个元素能整除数组 `numsDivide` 所有元素,那么这个元素是所有 $numsDivide[i]$ 的最大公约数 $x$ 的因子。因此,我们可以先求出 `numsDivide` 的最大公约数 $x$。\n\n接下来,将数组 `nums` 排序,然后从头到尾遍历数组 `nums`,找到第一个是最大公约数 $x$ 的因子的元素,返回当前元素下标即可。\n\n时间复杂度 $O(m + \\log M + n \\times \\log n)$,其中 $n$ 和 $m$ 分别是数组 `nums` 和 `numsDivide` 的长度,而 $M$ 是数组 `numsDivide` 中的最大值。\n\n实际上,我们也可以不用排序数组 `nums`,而是直接遍历数组 `nums`,找到最小的能整除 $x$ 的元素,然后我们再遍历一次数组 `nums`,统计小于等于这个元素的元素个数即可。\n\n时间复杂度 $O(m + \\log M + n)$。", "2": "", "3": "" }, "is_english": false, "time_complexity": "O(m + \\log M + n \\times \\log n)", "space_complexity": null }, { "problem_id": 2345, "explanations": { "1": "We first convert each mountain $(x, y)$ into a horizontal interval $(x - y, x + y)$, then sort the intervals by left endpoint in ascending order and right endpoint in descending order.\n\nNext, we initialize the right endpoint of the current interval as $-\\infty$. We traverse each mountain. If the right endpoint of the current mountain is less than or equal to the right endpoint of the current interval, we skip this mountain. Otherwise, we update the right endpoint of the current interval to the right endpoint of the current mountain. If the interval of the current mountain appears only once, we increment the answer.\n\nFinally, we return the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the number of mountains." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2346, "explanations": { "1": "注意空值判断。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2347, "explanations": { "1": "We first traverse the array $\\textit{suits}$ to check if adjacent elements are equal. If they are, we return `\"Flush\"`.\n\nNext, we use a hash table or array $\\textit{cnt}$ to count the quantity of each card:\n\n- If any card appears $3$ times, return `\"Three of a Kind\"`;\n- Otherwise, if any card appears $2$ times, return `\"Pair\"`;\n- Otherwise, return `\"High Card\"`.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{ranks}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2348, "explanations": { "1": "We traverse the array $\\textit{nums}$ and use a variable $\\textit{cnt}$ to record the current number of consecutive $0$s. For the current element $x$ we are traversing, if $x$ is $0$, then $\\textit{cnt}$ is incremented by $1$, and the number of all-zero subarrays ending with the current $x$ is $\\textit{cnt}$, which we add to the answer. Otherwise, we set $\\textit{cnt}$ to $0$.\n\nAfter the traversal, we return the answer.\n\nTime complexity $O(n)$, where $n$ is the length of the array $\\textit{nums}$. Space complexity $O(1)$.\n\nSimilar problems:\n\n- [413. Arithmetic Slices](https://github.com/doocs/leetcode/blob/main/solution/0400-0499/0413.Arithmetic%20Slices/README_EN.md)\n- [1513. Number of Substrings With Only 1s](https://github.com/doocs/leetcode/blob/main/solution/1500-1599/1513.Number%20of%20Substrings%20With%20Only%201s/README_EN.md)" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2349, "explanations": { "1": "We use a hash table $d$ to record the mapping relationship between indices and numbers, and another hash table $g$ to record the set of indices corresponding to each number. Here, we can use an ordered set to store the indices, which allows us to conveniently find the smallest index.\n\nWhen calling the `change` method, we first check if the index already exists. If it does, we remove the original number from its corresponding index set and then add the new number to the corresponding index set. The time complexity is $O(\\log n)$.\n\nWhen calling the `find` method, we simply return the first element of the index set corresponding to the number. The time complexity is $O(1)$.\n\nThe space complexity is $O(n)$, where $n$ is the number of numbers." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(n)" }, { "problem_id": 2350, "explanations": { "1": "时间复杂度 $O(n)$。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": null }, { "problem_id": 2351, "explanations": { "1": "We traverse the string $s$, using an array or hash table `cnt` to record the occurrence of each letter. When a letter appears twice, we return that letter.\n\nThe time complexity is $O(n)$ and the space complexity is $O(C)$. Here, $n$ is the length of the string $s$, and $C$ is the size of the character set. In this problem, $C = 26$.", "2": "We can also use an integer `mask` to record whether each letter has appeared, where the $i$-th bit of `mask` indicates whether the $i$-th letter has appeared. When a letter appears twice, we return that letter.\n\nThe time complexity is $O(n)$ and the space complexity is $O(1)$. Here, $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(C)" }, { "problem_id": 2352, "explanations": { "1": "We directly compare each row and column of the matrix $grid$. If they are equal, then it is a pair of equal row-column pairs, and we increment the answer by one.\n\nThe time complexity is $O(n^3)$, where $n$ is the number of rows or columns in the matrix $grid$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n^3)", "space_complexity": "O(1)" }, { "problem_id": 2353, "explanations": { "1": "We can use a hash table $\\textit{d}$ to store the foods for each cuisine, where the key is the cuisine and the value is an ordered set. Each element in the ordered set is a tuple $(\\textit{rating}, \\textit{food})$, sorted by rating in descending order, and if the ratings are the same, sorted by food name in lexicographical order.\n\nWe can also use a hash table $\\textit{g}$ to store the rating and cuisine for each food. That is, $\\textit{g}[\\textit{food}] = (\\textit{rating}, \\textit{cuisine})$.\n\nIn the constructor, we iterate through $\\textit{foods}$, $\\textit{cuisines}$, and $\\textit{ratings}$, storing the rating and cuisine for each food in $\\textit{d}$ and $\\textit{g}$.\n\nIn the $\\textit{changeRating}$ function, we first get the original rating $\\textit{oldRating}$ and cuisine $\\textit{cuisine}$ of the food $\\textit{food}$, then update the rating of $\\textit{g}[\\textit{food}]$ to $\\textit{newRating}$, remove $(\\textit{oldRating}, \\textit{food})$ from $\\textit{d}[\\textit{cuisine}]$, and add $(\\textit{newRating}, \\textit{food})$ to $\\textit{d}[\\textit{cuisine}]$.\n\nIn the $\\textit{highestRated}$ function, we directly return the food name of the first element in $\\textit{d}[\\textit{cuisine}]$.\n\nIn terms of time complexity, the constructor has a time complexity of $O(n \\log n)$, where $n$ is the number of foods. The other operations have a time complexity of $O(\\log n)$. The space complexity is $O(n)$." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2354, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2355, "explanations": { "1": "We directly compare each row and column of the matrix $grid$. If they are equal, then it is a pair of equal row-column pairs, and we increment the answer by one.\n\nThe time complexity is $O(n^3)$, where $n$ is the number of rows or columns in the matrix $grid$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n^3)", "space_complexity": "O(1)" }, { "problem_id": 2356, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2357, "explanations": { "1": "We observe that in each operation, all identical nonzero elements in the array $\\textit{nums}$ can be reduced to $0$. Therefore, we only need to count the number of distinct nonzero elements in $\\textit{nums}$, which is the minimum number of operations required. To count the distinct nonzero elements, we can use a hash table or an array.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2358, "explanations": { "1": "Observing the conditions in the problem, the number of students in the $i$-th group must be less than that in the $(i+1)$-th group, and the total score of students in the $i$-th group must be less than that in the $(i+1)$-th group. We only need to sort the students by their scores in ascending order, and then assign $1$, $2$, ..., $k$ students to each group in order. If the last group does not have enough students for $k$, we can distribute these students to the previous last group.\n\nTherefore, we need to find the largest $k$ such that $\\frac{(1 + k) \\times k}{2} \\leq n$, where $n$ is the total number of students. We can use binary search to solve this.\n\nWe define the left boundary of binary search as $l = 1$ and the right boundary as $r = n$. Each time, the midpoint is $mid = \\lfloor \\frac{l + r + 1}{2} \\rfloor$. If $(1 + mid) \\times mid \\gt 2 \\times n$, it means $mid$ is too large, so we shrink the right boundary to $mid - 1$; otherwise, we increase the left boundary to $mid$.\n\nFinally, we return $l$ as the answer.\n\nThe time complexity is $O(\\log n)$ and the space complexity is $O(1)$, where $n$ is the total number of students." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 2359, "explanations": { "1": "We can first use BFS to calculate the distance from $node1$ and $node2$ to every node, denoted as $d_1$ and $d_2$ respectively. Then, enumerate all common nodes $i$, and for each, compute $\\max(d_1[i], d_2[i])$. The answer is the node with the minimal such value.\n\nThe complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of nodes.\n\nRelated problems:\n\n- [2203. Minimum Weighted Subgraph With the Required Paths](https://github.com/doocs/leetcode/blob/main/solution/2200-2299/2203.Minimum%20Weighted%20Subgraph%20With%20the%20Required%20Paths/README_EN.md)" }, "is_english": true, "time_complexity": null, "space_complexity": "O(n)" }, { "problem_id": 2360, "explanations": { "1": "We can traverse each node in the range $[0,..,n-1]$. If a node has not been visited, we start from this node and search for adjacent nodes until we encounter a cycle or a node that has already been visited. If we encounter a cycle, we update the answer.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the number of nodes.\n\nSimilar problems:\n\n- [2127. Maximum Employees to Be Invited to a Meeting](https://github.com/doocs/leetcode/blob/main/solution/2100-2199/2127.Maximum%20Employees%20to%20Be%20Invited%20to%20a%20Meeting/README.md)" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2361, "explanations": { "1": "We define $f[i]$ as the minimum cost from station $0$ to station $i$ when arriving at station $i$ by the regular route, and $g[i]$ as the minimum cost from station $0$ to station $i$ when arriving at station $i$ by the express route. Initially, $f[0]=0, g[0]=\\infty$.\n\nNext, we consider how to transition the states of $f[i]$ and $g[i]$.\n\nIf we arrive at station $i$ by the regular route, we can either come from station $i-1$ by the regular route or switch from the express route at station $i-1$ to the regular route. Therefore, we can get the state transition equation:\n\n$$\nf[i]=\\min\\{f[i-1]+a_i, g[i-1]+a_i\\}\n$$\n\nwhere $a_i$ represents the cost of taking the regular route from station $i-1$ to station $i$.\n\nIf we arrive at station $i$ by the express route, we can either switch from the regular route at station $i-1$ to the express route or continue on the express route from station $i-1$. Therefore, we can get the state transition equation:\n\n$$\ng[i]=\\min\\{f[i-1]+expressCost+b_i, g[i-1]+b_i\\}\n$$\n\nwhere $b_i$ represents the cost of taking the express route from station $i-1$ to station $i$.\n\nWe denote the answer array as $cost$, where $cost[i]$ represents the minimum cost from station $0$ to station $i$. Since we can reach station $i$ from any route, we have $cost[i]=\\min\\{f[i], g[i]\\}$.\n\nFinally, we return $cost$.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the number of stations." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2362, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2363, "explanations": { "1": "We can use a hash table or array `cnt` to count the total weight of each item in `items1` and `items2`. Then, we traverse the values in ascending order, adding each value and its corresponding total weight to the result array.\n\nThe time complexity is $O(n + m)$ and the space complexity is $O(n + m)$, where $n$ and $m$ are the lengths of `items1` and `items2` respectively." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(n + m)" }, { "problem_id": 2364, "explanations": { "1": "According to the problem description, for any $i \\lt j$, if $j - i \\neq \\textit{nums}[j] - \\textit{nums}[i]$, then $(i, j)$ is a bad pair.\n\nWe can transform the equation into $i - \\textit{nums}[i] \\neq j - \\textit{nums}[j]$. This suggests using a hash table $cnt$ to count the occurrences of $i - \\textit{nums}[i]$.\n\nWhile iterating through the array, for the current element $\\textit{nums}[i]$, we add $i - cnt[i - \\textit{nums}[i]]$ to the answer, and then increment the count of $i - \\textit{nums}[i]$ by $1$.\n\nFinally, we return the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2365, "explanations": { "1": "We can use a hash table $day$ to record the next time each task can be executed. Initially, all values in $day$ are $0$. We use a variable $ans$ to record the current time.\n\nWe iterate through the array $tasks$. For each task $task$, we increment the current time $ans$ by one, indicating that one day has passed since the last task execution. If $day[task] > ans$ at this time, it means that task $task$ can only be executed on the $day[task]$ day. Therefore, we update the current time $ans = \\max(ans, day[task])$. Then we update the value of $day[task]$ to $ans + space + 1$, indicating that the next time task $task$ can be executed is at $ans + space + 1$.\n\nAfter the iteration, we return $ans$.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of the array $tasks$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2366, "explanations": { "1": "We observe that to make the array $nums$ non-decreasing or monotonically increasing, the elements towards the end of the array should be as large as possible. Therefore, it is unnecessary to replace the last element $nums[n-1]$ of the array $nums$ with multiple smaller numbers.\n\nIn other words, we can traverse the array $nums$ from the end to the beginning, maintaining the current maximum value $mx$, initially $mx = nums[n-1]$.\n\n- If the current element $nums[i] \\leq mx$, there is no need to replace $nums[i]$. We simply update $mx = nums[i]$.\n- Otherwise, we need to replace $nums[i]$ with multiple numbers that sum to $nums[i]$. The maximum of these numbers is $mx$, and the total number of replacements is $k=\\left \\lceil \\frac{nums[i]}{mx} \\right \\rceil$. Therefore, we need to perform $k-1$ operations, which are added to the answer. Among these $k$ numbers, the smallest number is $\\left \\lfloor \\frac{nums[i]}{k} \\right \\rfloor$. Therefore, we update $mx = \\left \\lfloor \\frac{nums[i]}{k} \\right \\rfloor$.\n\nAfter the traversal, we return the total number of operations.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2367, "explanations": { "1": "We notice that the length of the array $nums$ is no more than $200$. Therefore, we can directly enumerate $i$, $j$, $k$, and check whether they meet the conditions. If they do, we increment the count of the triplet.\n\nThe time complexity is $O(n^3)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$.", "2": "We can first store the elements of $nums$ in a hash table or array $vis$. Then, for each element $x$ in $nums$, we check if $x+diff$ and $x+diff+diff$ are also in $vis$. If they are, we increment the count of the triplet.\n\nAfter the enumeration, we return the answer.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n^3)", "space_complexity": "O(1)" }, { "problem_id": 2368, "explanations": { "1": "First, we construct an adjacency list $g$ based on the given edges, where $g[i]$ represents the list of nodes adjacent to node $i$. Then we define a hash table $vis$ to record the restricted nodes or nodes that have been visited, and initially add the restricted nodes to $vis$.\n\nNext, we define a depth-first search function $dfs(i)$, which represents the number of nodes that can be reached starting from node $i$. In the $dfs(i)$ function, we first add node $i$ to $vis$, then traverse the nodes $j$ adjacent to node $i$. If $j$ is not in $vis$, we recursively call $dfs(j)$ and add the return value to the result.\n\nFinally, we return $dfs(0)$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes.", "2": "Similar to Solution 1, we first construct an adjacency list $g$ based on the given edges, then define a hash table $vis$ to record the restricted nodes or nodes that have been visited, and initially add the restricted nodes to $vis$.\n\nNext, we use breadth-first search to traverse the entire graph and count the number of reachable nodes. We define a queue $q$, initially add node $0$ to $q$, and add node $0$ to $vis$. Then we continuously take out node $i$ from $q$, accumulate the answer, and add the unvisited adjacent nodes of node $i$ to $q$ and $vis$.\n\nAfter the traversal, we return the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2369, "explanations": { "1": "We design a function $dfs(i)$, which represents whether there is a valid partition starting from index $i$. So the answer is $dfs(0)$.\n\nThe execution process of the function $dfs(i)$ is as follows:\n\n- If $i \\ge n$, return $true$.\n- If the elements at index $i$ and $i+1$ are equal, we can choose to make $i$ and $i+1$ a subarray, and recursively call $dfs(i+2)$.\n- If the elements at index $i$, $i+1$ and $i+2$ are equal, we can choose to make $i$, $i+1$ and $i+2$ a subarray, and recursively call $dfs(i+3)$.\n- If the elements at index $i$, $i+1$ and $i+2$ increase by $1$ in turn, we can choose to make $i$, $i+1$ and $i+2$ a subarray, and recursively call $dfs(i+3)$.\n- If none of the above conditions are met, return $false$, otherwise return $true$.\n\nThat is:\n\n$$\ndfs(i) = \\textit{OR}\n\\begin{cases}\ntrue,&i \\ge n\\\\\ndfs(i+2),&i+1 < n\\ \\textit{and}\\ \\textit{nums}[i] = \\textit{nums}[i+1]\\\\\ndfs(i+3),&i+2 < n\\ \\textit{and}\\ \\textit{nums}[i] = \\textit{nums}[i+1] = \\textit{nums}[i+2]\\\\\ndfs(i+3),&i+2 < n\\ \\textit{and}\\ \\textit{nums}[i+1] - \\textit{nums}[i] = 1\\ \\textit{and}\\ \\textit{nums}[i+2] - \\textit{nums}[i+1] = 1\n\\end{cases}\n$$\n\nTo avoid repeated calculations, we use the method of memoization search.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array.", "2": "We can convert the memoization search in Solution 1 into dynamic programming.\n\nLet $f[i]$ represent whether there is a valid partition for the first $i$ elements of the array. Initially, $f[0] = true$, and the answer is $f[n]$.\n\nThe state transition equation is as follows:\n\n$$\nf[i] = \\textit{OR}\n\\begin{cases}\ntrue,&i = 0\\\\\nf[i-2],&i-2 \\ge 0\\ \\textit{and}\\ \\textit{nums}[i-1] = \\textit{nums}[i-2]\\\\\nf[i-3],&i-3 \\ge 0\\ \\textit{and}\\ \\textit{nums}[i-1] = \\textit{nums}[i-2] = \\textit{nums}[i-3]\\\\\nf[i-3],&i-3 \\ge 0\\ \\textit{and}\\ \\textit{nums}[i-1] - \\textit{nums}[i-2] = 1\\ \\textit{and}\\ \\textit{nums}[i-2] - \\textit{nums}[i-3] = 1\n\\end{cases}\n$$\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2370, "explanations": { "1": "设 $dp[i]$ 表示以字符 $s[i]$ 结尾的最长理想子序列的长度,利用哈希表 $d$ 记录每个字符最新出现的位置。初始时 $dp[0]=1$, $d[s[0]]=0$。\n\n在 $[1,..n-1]$ 范围内的每个字符 $s[i]$,获取它所有前一个合法字符的位置 $j$,那么 $dp[i]=max(dp[i], dp[j]+1)$。\n\n答案为 $dp$ 中的最大值。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2371, "explanations": { "1": "由于可以将每一个数字重新填入并且使最终矩阵的最大值最小化,可考虑贪心。\n\n矩阵中每一个数字不一样,可考虑哈希表或数组记录每个数字对应的位置。\n\n将所有数字排序。然后从小到大填入新的数字,每次填入的数字为当前行和列的较大值再加一,同时用新填入的数字更新当前行和列的最大值。\n\n时间复杂度 $O(mn\\log mn)$,空间复杂度 $O(mn)$。其中 $m$ 和 $n$ 是矩阵的行数和列数。" }, "is_english": false, "time_complexity": "O(mn\\log mn)", "space_complexity": "O(mn)" }, { "problem_id": 2372, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2373, "explanations": { "1": "我们可以枚举每个 $3 \\times 3$ 的矩阵,求出每个 $3 \\times 3$ 的矩阵中的最大值,然后将这些最大值放入答案矩阵中。\n\n时间复杂度 $O(n^2)$,其中 $n$ 是矩阵的边长。忽略答案矩阵的空间消耗,空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(n^2)", "space_complexity": "O(1)" }, { "problem_id": 2374, "explanations": { "1": "We define an array $\\textit{cnt}$ of length $n$, where $\\textit{cnt}[i]$ represents the edge score of node $i$. Initially, all elements are $0$. We also define an answer variable $\\textit{ans}$, initially set to $0$.\n\nNext, we traverse the array $\\textit{edges}$. For each node $i$ and its outgoing edge node $j$, we update $\\textit{cnt}[j]$ to $\\textit{cnt}[j] + i$. If $\\textit{cnt}[\\textit{ans}] < \\textit{cnt}[j]$ or $\\textit{cnt}[\\textit{ans}] = \\textit{cnt}[j]$ and $j < \\textit{ans}$, we update $\\textit{ans}$ to $j$.\n\nFinally, return $\\textit{ans}$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{edges}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2375, "explanations": { "1": "定义 $dfs(u)$,其中 $u$ 表示当前答案字符串的长度。从 $u=0$ 开始搜索,直至找到第一个符合条件的字符串。\n\n时间复杂度 $O(n!)$,空间复杂度 $O(n)$。其中 $n$ 表示字符串 $pattern$ 的长度。" }, "is_english": false, "time_complexity": "O(n!)", "space_complexity": "O(n)" }, { "problem_id": 2376, "explanations": { "1": "This problem essentially asks for the number of numbers in the given range $[l, ..r]$ that satisfy certain conditions. The conditions are related to the composition of the numbers rather than their size, so we can use the concept of Digit DP to solve it. In Digit DP, the size of the number has little impact on the complexity.\n\nFor the range $[l, ..r]$ problem, we generally convert it to the problem of $[1, ..r]$ and then subtract the result of $[1, ..l - 1]$, i.e.:\n\n$$\nans = \\sum_{i=1}^{r} ans_i - \\sum_{i=1}^{l-1} ans_i\n$$\n\nHowever, for this problem, we only need to find the value for the range $[1, ..n]$.\n\nHere, we use memoized search to implement Digit DP. We search from the starting point downwards, and at the lowest level, we get the number of solutions. We then return the answers layer by layer upwards, and finally get the final answer from the starting point of the search.\n\nBased on the problem information, we design a function $\\textit{dfs}(i, \\textit{mask}, \\textit{lead}, \\textit{limit})$, where:\n\n- The digit $i$ represents the current position being searched, starting from the highest digit, i.e., $i = 0$ represents the highest digit.\n- The digit $\\textit{mask}$ represents the current state of the number, i.e., the $j$-th bit of $\\textit{mask}$ being $1$ indicates that the digit $j$ has been used.\n- The boolean $\\textit{lead}$ indicates whether the current number only contains leading $0$s.\n- The boolean $\\textit{limit}$ indicates whether the current number is restricted by the upper bound.\n\nThe function executes as follows:\n\nIf $i$ exceeds the length of the number $n$, it means the search is over. If $\\textit{lead}$ is true, it means the current number only contains leading $0$s, so return $0$. Otherwise, return $1$.\n\nIf $\\textit{limit}$ is false and $\\textit{lead}$ is false and the state of $\\textit{mask}$ has been memoized, directly return the memoized result.\n\nOtherwise, we calculate the current upper bound $up$. If $\\textit{limit}$ is true, $up$ is the $i$-th digit of the current number. Otherwise, $up = 9$.\n\nThen we iterate over $[0, up]$. For each digit $j$, if the $j$-th bit of $\\textit{mask}$ is $1$, it means the digit $j$ has been used, so we skip it. Otherwise, if $\\textit{lead}$ is true and $j = 0$, it means the current number only contains leading $0$s, so we recursively search the next digit. Otherwise, we recursively search the next digit and update the state of $\\textit{mask}$.\n\nFinally, if $\\textit{limit}$ is false and $\\textit{lead}$ is false, memoize the current state.\n\nReturn the final answer.\n\nThe time complexity is $O(m \\times 2^D \\times D)$, and the space complexity is $O(m \\times 2^D)$. Here, $m$ is the length of the number $n$, and $D = 10$.\n\nSimilar Problems:\n\n- [233. Number of Digit One](https://github.com/doocs/leetcode/blob/main/solution/0200-0299/0233.Number%20of%20Digit%20One/README_EN.md)\n- [357. Count Numbers with Unique Digits](https://github.com/doocs/leetcode/blob/main/solution/0300-0399/0357.Count%20Numbers%20with%20Unique%20Digits/README_EN.md)\n- [600. Non-negative Integers without Consecutive Ones](https://github.com/doocs/leetcode/blob/main/solution/0600-0699/0600.Non-negative%20Integers%20without%20Consecutive%20Ones/README_EN.md)\n- [788. Rotated Digits](https://github.com/doocs/leetcode/blob/main/solution/0700-0799/0788.Rotated%20Digits/README_EN.md)\n- [902. Numbers At Most N Given Digit Set](https://github.com/doocs/leetcode/blob/main/solution/0900-0999/0902.Numbers%20At%20Most%20N%20Given%20Digit%20Set/README_EN.md)\n- [1012. Numbers with Repeated Digits](https://github.com/doocs/leetcode/blob/main/solution/1000-1099/1012.Numbers%20With%20Repeated%20Digits/README_EN.md)" }, "is_english": true, "time_complexity": "O(m \\times 2^D \\times D)", "space_complexity": "O(m \\times 2^D)" }, { "problem_id": 2377, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2378, "explanations": { "1": "We design a function $dfs(i)$, which represents the maximum sum of the weights of selected edges in the subtree rooted at node $i$, such that no two selected edges are adjacent. This function returns two values $(a, b)$. The first value $a$ represents the sum of the weights of selected edges when the edge between the current node $i$ and its parent node is selected. The second value $b$ represents the sum of the weights of selected edges when the edge between the current node $i$ and its parent node is not selected.\n\nWe can observe the following for the current node $i$:\n\n- If the edge between $i$ and its parent node is selected, then none of the edges between $i$ and its child nodes can be selected. In this case, the value of $a$ for the current node is the sum of the $b$ values of all its child nodes.\n- If the edge between $i$ and its parent node is not selected, then we can select at most one edge between $i$ and its child nodes. In this case, the value of $b$ for the current node is the sum of the $a$ values of the selected child nodes and the $b$ values of the unselected child nodes, plus the weight of the edge between $i$ and the selected child node.\n\nWe call the function $dfs(0)$, and the second value returned is the answer, which is the sum of the weights of selected edges when the edge between the root node and its parent node is not selected.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2379, "explanations": { "1": "We observe that what the problem actually asks for is the minimum number of white blocks in a sliding window of size $k$.\n\nTherefore, we only need to traverse the string $blocks$, use a variable $cnt$ to count the number of white blocks in the current window, and then use a variable $ans$ to maintain the minimum value.\n\nAfter the traversal ends, we can get the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $blocks$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2380, "explanations": { "1": "由于本题数据范围不大,所以可以暴力模拟,每一轮将字符串中所有 “01” 替换为 “10”,统计轮次作为答案。\n\n时间复杂度 $O(n^2)$。每一轮时间复杂度 $O(n)$,最多进行 $n$ 轮操作。", "2": "题目要把所有“01”串替换为“10”,实际上是将所有的“1”往左移动。操作过后,左侧均为“1”,而右侧均为“0”。\n\n假如我们要把“0100010”重排为“1100000”,会出现两种情况:\n\n1. 如果一个“1”左边有 $cnt$ 个“0”,那么将这个“1”移动到最左边的位置需要 $cnt$ 秒;\n1. 如果有连续的“1”,则将这两个“1”移动到最左边的位置需要额外的 $1$ 秒。\n\n看下面的示例:\n\n| 时刻(秒) | 示例 1 | 示例 2 |\n| ---------- | ------ | ------ |\n| 0 | 0001 | 00011 |\n| 1 | 0010 | 00101 |\n| 2 | 0100 | 01010 |\n| 3 | 1000 | 10100 |\n| 4 | - | 11000 |\n\n我们可以看到,如果在 $cnt$ 个“0”之后只有一个“1”,那么只需要 $cnt$ 秒,如果有连续的“1”,则需要额外的 $1$ 秒。\n\n因此,对于字符串中的每一个“1”,我们计算 $ans=max(ans+1, cnt)$。\n\n时间复杂度 $O(n)$,空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(n^2)", "space_complexity": "O(1)" }, { "problem_id": 2381, "explanations": { "1": "用差分数组 $d$ 记录区间的变化,然后对 $d$ 求前缀和,得到每个下标 $i$ 的变化量 $d[i]$。\n\n然后将原字符串中每个字符加上对应的 $d[i]$,最终得到一个新的字符串。\n\n时间复杂度 $O(n+m)$。其中 $n$ 是原字符串 $s$ 的长度,而 $m$ 是移位操作 $shifts$ 的长度。" }, "is_english": false, "time_complexity": "O(n+m)", "space_complexity": null }, { "problem_id": 2382, "explanations": { "1": "考虑**从后往前遍历**数组 $removeQueries$ 中的每个元素 $i$,用并查集来维护以 $nums[i]$ 所在的连续子数组的和。\n\n遍历过程中:\n\n对于 $removeQueries$ 中的每一个 $i$,若下标 $i-1$ 对应的元素遍历过,可以将 $i-1$ 与 $i$ 进行合并,同理,若下标 $i+1$ 对应的元素也遍历过了,将 $i$ 与 $i+1$ 合并。合并过程中更新连通块的元素和。\n\n时间复杂度 $O(nlogn)$。其中 $n$ 是 $nums$ 中的元素个数。\n\n相似题目:\n\n- [2334. 元素值大于变化阈值的子数组](https://github.com/doocs/leetcode/blob/main/solution/2300-2399/2334.Subarray%20With%20Elements%20Greater%20Than%20Varying%20Threshold/README.md)" }, "is_english": false, "time_complexity": "O(nlogn)", "space_complexity": null }, { "problem_id": 2383, "explanations": { "1": "Let's denote the current energy as $x$ and the current experience as $y$.\n\nNext, we traverse each opponent. For the $i$-th opponent, let their energy be $dx$ and their experience be $dy$.\n\n- If $x \\leq dx$, then we need to train for $dx + 1 - x$ hours to increase our energy to $dx + 1$.\n- If $y \\leq dy$, then we need to train for $dy + 1 - y$ hours to increase our experience to $dy + 1$.\n- Then, we subtract $dx$ from our energy and add $dy$ to our experience.\n\nFinally, return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the number of opponents. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2384, "explanations": { "1": "用 $cnt$ 数组记录每个数字出现的次数。\n\n回文数字需要满足回文串中最多有一个数字出现了奇数次,因此我们先找最大的、出现了奇数次的数字 $v$(也可能不存在),作为回文数字的中间数字,对应的 $cnt$ 减 $1$。\n\n接下来我们从回文数字中间,按数字从小到大的顺序,往左右两边扩散(也可以枚举回文串的右半部分,然后将右半部分反转,得到左半部分)。这样我们可以得到一个“可能”含有前导零的回文串。\n\n我们去除回文串的前导零,若回文串为空,则返回“0”。否则返回该回文串。\n\n时间复杂度 $O(n)$,其中 $n$ 为 $num$ 的长度。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": null }, { "problem_id": 2385, "explanations": { "1": "First, we build a graph through one DFS, and get an adjacency list $g$, where $g[node]$ represents all nodes connected to the node $node$.\n\nThen, we use $start$ as the starting point, and search the entire tree through DFS to find the farthest distance, which is the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2386, "explanations": { "1": "First, we find the maximum subarray sum $mx$, which is the sum of all positive numbers.\n\nIt can be observed that the sum of other subarrays can be considered as the maximum subarray sum minus the sum of other parts of the subarray. Therefore, we can convert the problem into finding the $k$-th smallest subarray sum.\n\nWe only need to sort all numbers in ascending order by their absolute values, then build a min-heap to store the tuple $(s, i)$, where $s$ is the current sum and $i$ is the index of the next number to be selected in the subarray.\n\nEach time, we extract the top of the heap and insert two new situations: one is to select the next number, and the other is to select the next number but not the current number.\n\nSince the array is sorted in ascending order, this method can traverse all subarray sums in order without omission.\n\nThe time complexity is $O(n \\times \\log n + k \\times \\log k)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(n)$." }, "is_english": true, "time_complexity": "O(n \\times \\log n + k \\times \\log k)", "space_complexity": "O(n)" }, { "problem_id": 2387, "explanations": { "1": "The median is actually the $target = \\left \\lceil \\frac{m \\times n}{2} \\right \\rceil$-th number after sorting.\n\nWe perform a binary search on the elements of the matrix $x$, counting the number of elements in the grid that are greater than $x$, denoted as $cnt$. If $cnt \\ge target$, it means the median is on the left side of $x$ (including $x$); otherwise, it is on the right side.\n\nThe time complexity is $O(m \\times \\log n \\times \\log M)$, where $m$ and $n$ are the number of rows and columns of the grid, respectively, and $M$ is the maximum element in the grid. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m \\times \\log n \\times \\log M)", "space_complexity": "O(1)" }, { "problem_id": 2388, "explanations": { "1": "我们可以使用一个临时变量 $cur$ 来记录上一个不为 $null$ 的值,如果当前值为 $null$,则将 $cur$ 的值赋给当前值,否则我们更新 $cur$ 的值为当前值。", "2": "我们先用窗口函数 `row_number()` 为每一行生成一个序号,然后使用 `sum()` 窗口函数来生成一个分组序号,分组序号的生成规则为:如果当前行的值为 $null$,则分组序号与上一行相同,否则分组序号加一。最后我们使用 `max()` 窗口函数来获取每一组唯一一个不为 $null$ 的值。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2389, "explanations": { "1": "According to the problem description, for each $\\textit{queries[i]}$, we need to find a subsequence such that the sum of its elements does not exceed $\\textit{queries[i]}$ and the length of the subsequence is maximized. Obviously, we should choose the smallest possible elements to maximize the length of the subsequence.\n\nTherefore, we can first sort the array $\\textit{nums}$ in ascending order, and then for each $\\textit{queries[i]}$, we can use binary search to find the smallest index $j$ such that $\\textit{nums}[0] + \\textit{nums}[1] + \\cdots + \\textit{nums}[j] > \\textit{queries[i]}$. At this point, $\\textit{nums}[0] + \\textit{nums}[1] + \\cdots + \\textit{nums}[j - 1]$ is the sum of the elements of the subsequence that meets the condition, and the length of this subsequence is $j$. Therefore, we can add $j$ to the answer array.\n\nThe time complexity is $O((n + m) \\times \\log n)$, and the space complexity is $O(n)$ or $O(\\log n)$. Here, $n$ and $m$ are the lengths of the arrays $\\textit{nums}$ and $\\textit{queries}$, respectively.", "2": "Similar to Solution 1, we can first sort the array $nums$ in ascending order.\n\nNext, we define an index array $idx$ of the same length as $queries$, where $idx[i] = i$. Then, we sort the array $idx$ in ascending order based on the values in $queries$. This way, we can process the elements in $queries$ in ascending order.\n\nWe use a variable $s$ to record the sum of the currently selected elements and a variable $j$ to record the number of currently selected elements. Initially, $s = j = 0$.\n\nWe traverse the index array $idx$, and for each index $i$ in it, we iteratively add elements from the array $nums$ to the current subsequence until $s + nums[j] \\gt queries[i]$. At this point, $j$ is the length of the subsequence that meets the condition. We set the value of $ans[i]$ to $j$ and then continue to process the next index.\n\nAfter traversing the index array $idx$, we obtain the answer array $ans$, where $ans[i]$ is the length of the subsequence that satisfies $queries[i]$.\n\nThe time complexity is $O(n \\times \\log n + m)$, and the space complexity is $O(m)$. Here, $n$ and $m$ are the lengths of the arrays $nums$ and $queries$, respectively." }, "is_english": true, "time_complexity": "O((n + m) \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2390, "explanations": { "1": "We can use a stack to simulate the operation process. Traverse the string $s$, and if the current character is not an asterisk, push it onto the stack; if the current character is an asterisk, pop the top element from the stack.\n\nFinally, concatenate the elements in the stack into a string and return it.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. Ignoring the space consumption of the answer string, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2391, "explanations": { "1": "According to the problem description, each garbage truck starts from house $0$, collects one type of garbage, and moves forward in order until it reaches the house index where this type of garbage last appears.\n\nTherefore, we can use a hash table $\\textit{last}$ to record the house index where each type of garbage last appears. We assume that the $i$-th type of garbage last appears in the $j$-th house, then the driving time required for the $i$-th truck is $\\textit{travel}[0] + \\textit{travel}[1] + \\cdots + \\textit{travel}[j-1]$. Note, if $j = 0$, no driving time is needed. We accumulate the driving time of all vehicles, add the total collection time of each type of garbage, and we can get the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(k)$, where $n$ and $k$ are the number and types of garbage, respectively. In this problem, $k = 3$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(k)" }, { "problem_id": 2392, "explanations": { "1": "利用拓扑排序,找到一个合法的 `row` 序列和 `col` 序列,然后根据这两个序列构造出矩阵。\n\n时间复杂度 $O(m+n+k)$。其中 $m$ 和 $n$ 分别为 `rowConditions` 和 `colConditions` 的长度,而 $k$ 为题目中给定的正整数。" }, "is_english": false, "time_complexity": "O(m+n+k)", "space_complexity": null }, { "problem_id": 2393, "explanations": { "1": "We can enumerate the number of strictly increasing subarrays ending at each element and then sum them up.\n\nWe use a variable $\\textit{cnt}$ to record the number of strictly increasing subarrays ending at the current element, initially $\\textit{cnt} = 1$. Then we traverse the array starting from the second element. If the current element is greater than the previous element, then $\\textit{cnt}$ can be incremented by $1$. Otherwise, $\\textit{cnt}$ is reset to $1$. At this point, the number of strictly increasing subarrays ending at the current element is $\\textit{cnt}$, and we add it to the answer.\n\nAfter the traversal, return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2394, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2395, "explanations": { "1": "We can traverse the array $nums$, and use a hash table $vis$ to record the sum of every two adjacent elements in the array. If the sum of the current two elements has already appeared in the hash table, then return `true`. Otherwise, add the sum of the current two elements to the hash table.\n\nIf we finish traversing and haven't found two subarrays that meet the condition, return `false`.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2396, "explanations": { "1": "When $n = 4$, its binary representation is $100$, which is not a palindrome;\n\nWhen $n \\gt 4$, its $(n - 2)$-ary representation is $12$, which is not a palindrome.\n\nTherefore, we can directly return `false`.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 2397, "explanations": { "1": "First, we convert each row of the matrix into a binary number and record it in the array $rows$. Here, $rows[i]$ represents the binary number corresponding to the $i$-th row, and the $j$-th bit of this binary number $rows[i]$ represents the value of the $i$-th row and $j$-th column.\n\nNext, we enumerate all $2^n$ column selection schemes, where $n$ is the number of columns in the matrix. For each column selection scheme, we check whether `numSelect` columns have been selected. If not, we skip it. Otherwise, we count how many rows in the matrix are covered by the selected columns, i.e., how many binary numbers $rows[i]$ are equal to the bitwise AND of $rows[i]$ and the column selection scheme $mask$. We then update the maximum number of rows.\n\nThe time complexity is $O(2^n \\times m)$, and the space complexity is $O(m)$. Where $m$ and $n$ are the number of rows and columns in the matrix, respectively." }, "is_english": true, "time_complexity": "O(2^n \\times m)", "space_complexity": "O(m)" }, { "problem_id": 2398, "explanations": { "1": "The problem is essentially finding the maximum value within a sliding window, which can be solved using a monotonic queue.\n\nWe only need to use binary search to enumerate the size of the window $k$, and find the largest $k$ that satisfies the problem requirements.\n\nIn the implementation process, we don't actually need to perform binary search enumeration. We just need to change the fixed window to a non-fixed window with double pointers.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of robots in the problem." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2399, "explanations": { "1": "We can use a hash table $d$ to record the indices of each letter's occurrences. Then, traverse the hash table and check if the difference between the indices of each letter equals the corresponding value in the `distance` array. If any discrepancy is found, return `false`. If the traversal completes without discrepancies, return `true`.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(|\\Sigma|)$, where $\\Sigma$ is the character set, which in this case is the set of lowercase letters." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 2400, "explanations": { "1": "We design a function $dfs(i, j)$, which represents the number of ways to reach the target position when the current position is $i$ distance from the target position and there are $j$ steps left. The answer is $dfs(abs(startPos - endPos), k)$.\n\nThe calculation method of the function $dfs(i, j)$ is as follows:\n\n- If $i \\gt j$ or $j \\lt 0$, it means that the current distance from the target position is greater than the remaining steps, or the remaining steps are negative. In this case, it is impossible to reach the target position, so return $0$;\n- If $j = 0$, it means that there are no steps left. At this time, only when the current distance from the target position is $0$ can the target position be reached, otherwise it is impossible to reach the target position. Return $1$ or $0$;\n- Otherwise, the current distance from the target position is $i$, and there are $j$ steps left. There are two ways to reach the target position:\n - Move one step to the left, the current distance from the target position is $i + 1$, and there are $j - 1$ steps left. The number of methods is $dfs(i + 1, j - 1)$;\n - Move one step to the right, the current distance from the target position is $abs(i - 1)$, and there are $j - 1$ steps left. The number of methods is $dfs(abs(i - 1), j - 1)$;\n- Finally, return the result of the sum of the two methods modulo $10^9 + 7$.\n\nTo avoid repeated calculations, we use memorization search, that is, we use a two-dimensional array $f$ to record the result of the function $dfs(i, j)$. When the function $dfs(i, j)$ is called, if $f[i][j]$ is not $-1$, return $f[i][j]$ directly, otherwise calculate the value of $f[i][j]$, and return $f[i][j]$.\n\nThe time complexity is $O(k^2)$, and the space complexity is $O(k^2)$. Here, $k$ is the number of steps given in the problem." }, "is_english": true, "time_complexity": "O(k^2)", "space_complexity": "O(k^2)" }, { "problem_id": 2401, "explanations": { "1": "According to the problem description, the position of the binary $1$ in each element of the subarray must be unique to ensure that the bitwise AND result of any two elements is $0$.\n\nTherefore, we can use two pointers, $l$ and $r$, to maintain a sliding window such that the elements within the window satisfy the problem's conditions.\n\nWe use a variable $\\textit{mask}$ to represent the bitwise OR result of the elements within the window. Next, we traverse each element of the array. For the current element $x$, if the bitwise AND result of $\\textit{mask}$ and $x$ is not $0$, it means that the current element $x$ has overlapping binary bits with the elements in the window. At this point, we need to move the left pointer $l$ until the bitwise AND result of $\\textit{mask}$ and $x$ is $0$. Then, we assign the bitwise OR result of $\\textit{mask}$ and $x$ to $\\textit{mask}$ and update the answer $\\textit{ans} = \\max(\\textit{ans}, r - l + 1)$.\n\nAfter the traversal, return the answer $\\textit{ans}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2402, "explanations": { "1": "We define two priority queues to represent idle meeting rooms and busy meeting rooms respectively. The idle meeting rooms $\\textit{idle}$ are sorted by **index**; the busy meeting rooms $\\textit{busy}$ are sorted by **end time and index**.\n\nFirst, sort the meetings by start time, then iterate through the meetings. For each meeting:\n\n- If there are busy meeting rooms with end time less than or equal to the current meeting's start time, add them to the idle meeting rooms queue $\\textit{idle}$;\n- If there are idle meeting rooms available, take the room with the smallest index from the idle queue $\\textit{idle}$ and add it to the busy queue $\\textit{busy}$;\n- If there are no idle meeting rooms, find the room with the earliest end time and smallest index from the busy queue $\\textit{busy}$, and add it back to the busy queue $\\textit{busy}$.\n\nThe time complexity is $O(m (\\log m + \\log n))$, and the space complexity is $O(n + m)$, where $n$ and $m$ are the number of meeting rooms and meetings respectively.\n\nSimilar problems:\n\n- [1882. Process Tasks Using Servers](https://github.com/doocs/leetcode/blob/main/solution/1800-1899/1882.Process%20Tasks%20Using%20Servers/README_EN.md)" }, "is_english": true, "time_complexity": "O(m (\\log m + \\log n))", "space_complexity": "O(n + m)" }, { "problem_id": 2403, "explanations": { "1": "We note that the number of monsters is at most $17$, which means we can use a 17-bit binary number to represent the state of the monsters. The $i$-th bit being $1$ indicates that the $i$-th monster is still alive, and $0$ indicates that the $i$-th monster has been defeated.\n\nWe design a function $\\textit{dfs}(\\textit{mask})$ to represent the minimum number of days needed to defeat all monsters when the current state of the monsters is $\\textit{mask}$. The answer is $\\textit{dfs}(2^n - 1)$, where $n$ is the number of monsters.\n\nThe calculation of the function $\\textit{dfs}(\\textit{mask})$ is as follows:\n\n- If $\\textit{mask} = 0$, it means all monsters have been defeated, return $0$;\n- Otherwise, we enumerate each monster $i$. If the $i$-th monster is still alive, we can choose to defeat the $i$-th monster, then recursively calculate $\\textit{dfs}(\\textit{mask} \\oplus 2^i)$, and update the answer to $\\textit{ans} = \\min(\\textit{ans}, \\textit{dfs}(\\textit{mask} \\oplus 2^i) + \\lceil \\frac{x}{\\textit{gain}} \\rceil)$, where $x$ is the strength of the $i$-th monster, and $\\textit{gain} = 1 + (n - \\textit{mask}.\\textit{bit\\_count}())$ represents the current daily mana gain.\n\nFinally, we return $\\textit{dfs}(2^n - 1)$.\n\nThe time complexity is $O(2^n \\times n)$, and the space complexity is $O(2^n)$. Here, $n$ is the number of monsters.", "2": "We can convert the memoization search in Solution 1 to dynamic programming. Define $f[\\textit{mask}]$ to represent the minimum number of days needed to defeat all monsters when the current state of the monsters is $\\textit{mask}$. Here, $\\textit{mask}$ is an $n$-bit binary number, where the $i$-th bit being $1$ indicates that the $i$-th monster has been defeated, and $0$ indicates that the $i$-th monster is still alive. Initially, $f[0] = 0$, and the rest $f[\\textit{mask}] = +\\infty$. The answer is $f[2^n - 1]$.\n\nWe enumerate $\\textit{mask}$ in the range $[1, 2^n - 1]$. For each $\\textit{mask}$, we enumerate each monster $i$. If the $i$-th monster is defeated, it can be transferred from the previous state $\\textit{mask} \\oplus 2^i$, with a transfer cost of $(\\textit{power}[i] + \\textit{gain} - 1) / \\textit{gain}$, where $\\textit{gain} = \\textit{mask}.\\textit{bitCount}()$.\n\nFinally, return $f[2^n - 1]$.\n\nThe time complexity is $O(2^n \\times n)$, and the space complexity is $O(2^n)$. Here, $n$ is the number of monsters." }, "is_english": true, "time_complexity": "O(2^n \\times n)", "space_complexity": "O(2^n)" }, { "problem_id": 2404, "explanations": { "1": "We use a hash table $cnt$ to count the occurrence of all even elements, and then find the even element with the highest occurrence and the smallest value.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2405, "explanations": { "1": "According to the problem description, each substring should be as long as possible and contain unique characters. Therefore, we can greedily partition the string.\n\nWe define a binary integer $\\textit{mask}$ to record the characters that have appeared in the current substring. The $i$-th bit of $\\textit{mask}$ being $1$ indicates that the $i$-th letter has already appeared, and $0$ indicates that it has not appeared. Additionally, we need a variable $\\textit{ans}$ to record the number of substrings, initially $\\textit{ans} = 1$.\n\nTraverse each character in the string $s$. For each character $c$, convert it to an integer $x$ between $0$ and $25$, then check if the $x$-th bit of $\\textit{mask}$ is $1$. If it is $1$, it means the current character $c$ is a duplicate in the current substring. In this case, increment $\\textit{ans}$ by $1$ and reset $\\textit{mask}$ to $0$. Otherwise, set the $x$-th bit of $\\textit{mask}$ to $1$. Then, update $\\textit{mask}$ to the bitwise OR result of $\\textit{mask}$ and $2^x$.\n\nFinally, return $\\textit{ans}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2406, "explanations": { "1": "First, we sort the intervals by their left endpoints. We use a min heap to maintain the rightmost endpoint of each group (the top of the heap is the minimum of the rightmost endpoints of all groups).\n\nNext, we traverse each interval:\n\n- If the left endpoint of the current interval is greater than the top element of the heap, it means the current interval can be added to the group where the top element of the heap is located. We directly pop the top element of the heap, and then put the right endpoint of the current interval into the heap.\n- Otherwise, it means there is currently no group that can accommodate the current interval, so we create a new group and put the right endpoint of the current interval into the heap.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array `intervals`." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2407, "explanations": { "1": "We assume that $f[v]$ represents the length of the longest increasing subsequence ending with the number $v$.\n\nWe traverse each element $v$ in the array $nums$, with the state transition equation: $f[v] = \\max(f[v], f[x])$, where the range of $x$ is $[v-k, v-1]$.\n\nTherefore, we need a data structure to maintain the maximum value of the interval. It is not difficult to think of using a segment tree.\n\nThe segment tree divides the entire interval into multiple discontinuous subintervals, and the number of subintervals does not exceed $log(width)$. To update the value of an element, only $log(width)$ intervals need to be updated, and these intervals are all contained in a large interval that contains the element.\n\n- Each node of the segment tree represents an interval;\n- The segment tree has a unique root node, which represents the entire statistical range, such as $[1,N]$;\n- Each leaf node of the segment tree represents an elementary interval of length $1$, $[x, x]$;\n- For each internal node $[l,r]$, its left child is $[l,mid]$, and the right child is $[mid+1,r]$, where $mid = \\left \\lfloor \\frac{l+r}{2} \\right \\rfloor$.\n\nFor this problem, the information maintained by the segment tree node is the maximum value within the interval range.\n\nThe time complexity is $O(n \\times \\log n)$, where $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": null }, { "problem_id": 2408, "explanations": { "1": "Create a hash table `tables` to store the mapping of table names to table data rows. Directly simulate the operations in the problem.\n\nThe time complexity of each operation is $O(1)$, and the space complexity is $O(n)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(n)" }, { "problem_id": 2409, "explanations": { "1": "We convert the dates into days, and then calculate the number of days both people are in Rome.\n\nThe time complexity is $O(C)$, and the space complexity is $O(C)$. Here, $C$ is a constant." }, "is_english": true, "time_complexity": "O(C)", "space_complexity": "O(C)" }, { "problem_id": 2410, "explanations": { "1": "According to the problem description, each athlete should be matched with the trainer whose ability value is as close as possible. Therefore, we can sort the ability values of both athletes and trainers, and then use the two-pointer method for matching.\n\nWe use two pointers $i$ and $j$ to point to the arrays of athletes and trainers, respectively, both initially pointing to the start of the arrays. Then we traverse the ability values of the athletes one by one. If the current trainer's ability value is less than the current athlete's ability value, we move the trainer's pointer to the right by one position until we find a trainer whose ability value is greater than or equal to the current athlete's. If no such trainer is found, it means the current athlete cannot be matched with any trainer, and we return the current athlete's index. Otherwise, we can match the current athlete with the trainer, and then move both pointers to the right by one position. Continue this process until all athletes have been traversed.\n\nIf we traverse all athletes, it means all athletes can be matched with trainers, and we return the number of athletes.\n\nThe time complexity is $O(m \\times \\log m + n \\times \\log n)$, and the space complexity is $O(\\max(\\log m, \\log n))$. Here, $m$ and $n$ are the numbers of athletes and trainers, respectively." }, "is_english": true, "time_complexity": "O(m \\times \\log m + n \\times \\log n)", "space_complexity": "O(\\max(\\log m, \\log n))" }, { "problem_id": 2411, "explanations": { "1": "To find the shortest subarray starting at position $i$ that maximizes the bitwise OR operation, we need to maximize the number of $1$s in the result.\n\nWe use an array $f$ of size $32$ to record the earliest position of each bit $1$.\n\nWe traverse the array $nums[i]$ in reverse order. For the $j$-th bit of $nums[i]$, if it is $1$, then $f[j]$ is $i$. Otherwise, if $f[j]$ is not $-1$, it means that a number satisfying the $j$-th bit as $1$ is found on the right, so we update the length.\n\nThe time complexity is $O(n \\times \\log m)$, where $n$ is the length of the array $nums$, and $m$ is the maximum value in the array $nums$." }, "is_english": true, "time_complexity": "O(n \\times \\log m)", "space_complexity": null }, { "problem_id": 2412, "explanations": { "1": "First, we accumulate all negative profits, denoted as $s$. Then, we enumerate each transaction $\\text{transactions}[i] = [a, b]$ as the last transaction. If $a > b$, it means the current transaction is a loss, and this transaction has already been included when we accumulated the negative profits earlier. Therefore, we update the answer with $s + b$. Otherwise, we update the answer with $s + a$.\n\nThe time complexity is $O(n)$, where $n$ is the number of transactions. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2413, "explanations": { "1": "If $n$ is even, then the least common multiple (LCM) of $2$ and $n$ is $n$ itself. Otherwise, the LCM of $2$ and $n$ is $n \\times 2$.\n\nThe time complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": null }, { "problem_id": 2414, "explanations": { "1": "We can traverse the string $s$ and use a variable $\\textit{ans}$ to record the length of the longest lexicographically consecutive substring, and another variable $\\textit{cnt}$ to record the length of the current consecutive substring. Initially, $\\textit{ans} = \\textit{cnt} = 1$.\n\nNext, we start traversing the string $s$ from the character at index $1$. For each character $s[i]$, if $s[i] - s[i - 1] = 1$, it means the current character and the previous character are consecutive. In this case, $\\textit{cnt} = \\textit{cnt} + 1$, and we update $\\textit{ans} = \\max(\\textit{ans}, \\textit{cnt})$. Otherwise, it means the current character and the previous character are not consecutive, so $\\textit{cnt} = 1$.\n\nFinally, we return $\\textit{ans}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2415, "explanations": { "1": "We can use the Breadth-First Search (BFS) method, using a queue $q$ to store the nodes of each level, and a variable $i$ to record the current level. If $i$ is odd, we reverse the values of the nodes at the current level.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2416, "explanations": { "1": "We can use a prefix tree to maintain all prefixes of the strings and count the occurrences of each prefix.\n\nDefine the prefix tree node structure `Trie`, which includes two properties:\n\n- `children`: An array of length 26 used to store the current node's children.\n- `cnt`: The occurrence count of the current node.\n\nDefine two methods for the prefix tree:\n\n- `insert`: Inserts a string, adding its prefixes into the prefix tree.\n- `search`: Searches for a string and returns the occurrence count of its prefixes.\n\nWe traverse all strings, inserting each string into the prefix tree. Then we traverse all strings again, calling the `search` method for each string and summing up the occurrence counts of each prefix.\n\nTime complexity is $O(L)$, and space complexity is $O(L)$, where $L$ is the total length of all strings." }, "is_english": true, "time_complexity": "O(L)", "space_complexity": "O(L)" }, { "problem_id": 2417, "explanations": { "1": "We denote the number of digits of $n$ as $k$, and the number of odd and even digits as $a$ and $b$ respectively.\n\n- If $a = b$, then $n$ itself is `fair`, and we can directly return $n$;\n- Otherwise, if $k$ is odd, we can find the smallest `fair` number with $k+1$ digits, in the form of `10000111`. If $k$ is even, we can directly brute force `closestFair(n+1)`.\n\nThe time complexity is $O(\\sqrt{n} \\times \\log_{10} n)$." }, "is_english": true, "time_complexity": "O(\\sqrt{n} \\times \\log_{10} n)", "space_complexity": null }, { "problem_id": 2418, "explanations": { "1": "According to the problem description, we can create an index array $idx$ of length $n$, where $idx[i]=i$. Then we sort each index in $idx$ in descending order according to the corresponding height in $heights$. Finally, we traverse each index $i$ in the sorted $idx$ and add $names[i]$ to the answer array.\n\nWe can also create an array $arr$ of length $n$, where each element is a tuple $(heights[i], i)$. Then we sort $arr$ in descending order by height. Finally, we traverse each element $(heights[i], i)$ in the sorted $arr$ and add $names[i]$ to the answer array.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the arrays $names$ and $heights$.", "2": "" }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2419, "explanations": { "1": "Since the bitwise AND operation does not increase the number, the maximum value is the maximum value in the array.\n\nThe problem can be converted to finding the maximum number of consecutive occurrences of the maximum value in the array.\n\nFirst, traverse the array $\\textit{nums}$ to find the maximum value $\\textit{mx}$, then traverse the array again to find the maximum number of consecutive occurrences of the maximum value. Finally, return this count.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2420, "explanations": { "1": "We define two arrays `decr` and `incr`, which represent the longest non-increasing and non-decreasing subarray lengths from left to right and from right to left, respectively.\n\nWe traverse the array, updating the `decr` and `incr` arrays.\n\nThen we sequentially traverse the index $i$ (where $k\\le i \\lt n - k$), if $decr[i] \\geq k$ and $incr[i] \\geq k$, then $i$ is a good index.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2421, "explanations": { "1": "To ensure that the starting point (or endpoint) of the path is greater than or equal to all points on the path, we can consider sorting all points from small to large first, then traverse and add them to the connected component, specifically as follows:\n\nWhen traversing to point $a$, for the adjacent point $b$ that is less than or equal to $vals[a]$, if they are not in the same connected component, they can be merged. And we can use all points in the connected component where point $a$ is located with a value of $vals[a]$ as the starting point, and all points in the connected component where point $b$ is located with a value of $vals[a]$ as the endpoint. The product of the number of the two types of points is the contribution to the answer when adding point $a$.\n\nThe time complexity is $O(n \\times \\log n)$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": null }, { "problem_id": 2422, "explanations": { "1": "Define two pointers $i$ and $j$, pointing to the beginning and end of the array respectively, use variables $a$ and $b$ to represent the values of the first and last elements, and variable $ans$ to represent the number of operations.\n\nIf $a < b$, we move the pointer $i$ one step to the right, i.e., $i \\leftarrow i + 1$, then add the value of the element pointed to by $i$ to $a$, i.e., $a \\leftarrow a + nums[i]$, and increment the operation count by one, i.e., $ans \\leftarrow ans + 1$.\n\nIf $a > b$, we move the pointer $j$ one step to the left, i.e., $j \\leftarrow j - 1$, then add the value of the element pointed to by $j$ to $b$, i.e., $b \\leftarrow b + nums[j]$, and increment the operation count by one, i.e., $ans \\leftarrow ans + 1$.\n\nOtherwise, it means $a = b$, at this time we move the pointer $i$ one step to the right, i.e., $i \\leftarrow i + 1$, move the pointer $j$ one step to the left, i.e., $j \\leftarrow j - 1$, and update the values of $a$ and $b$, i.e., $a \\leftarrow nums[i]$ and $b \\leftarrow nums[j]$.\n\nRepeat the above process until $i \\ge j$, return the operation count $ans$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2423, "explanations": { "1": "First, we use a hash table or an array of length $26$ named $cnt$ to count the number of occurrences of each letter in the string.\n\nNext, we enumerate the $26$ letters. If letter $c$ appears in the string, we decrement its count by one, then check whether the counts of the remaining letters are the same. If they are, return `true`. Otherwise, increment the count of $c$ by one and continue to enumerate the next letter.\n\nIf the enumeration ends, it means that it is impossible to make the counts of the remaining letters the same by deleting one letter, so return `false`.\n\nThe time complexity is $O(n + C^2)$, and the space complexity is $O(C)$. Here, $n$ is the length of the string $word$, and $C$ is the size of the character set. In this problem, $C = 26$." }, "is_english": true, "time_complexity": "O(n + C^2)", "space_complexity": "O(C)" }, { "problem_id": 2424, "explanations": { "1": "We use a variable $r$ to record the current longest prefix of uploaded videos, and an array or hash table $s$ to record the videos that have been uploaded.\n\nEach time a video is uploaded, we set `s[video]` to `true`, then loop to check whether `s[r + 1]` is `true`. If it is, we update $r$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the total number of videos." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2425, "explanations": { "1": "Since each element of the array will be XORed with each element of another array, we know that the result remains the same when the same number is XORed twice, i.e., $a \\oplus a = 0$. Therefore, we only need to count the length of the array to know how many times each element is XORed with each element of another array.\n\nIf the length of the `nums2` array is odd, it means that each element in `nums1` has been XORed an odd number of times with each element in `nums2`, so the final XOR result of the `nums1` array is the XOR result of all elements in the `nums1` array. If it is even, it means that each element in `nums1` has been XORed an even number of times with each element in `nums2`, so the final XOR result of the `nums1` array is 0.\n\nSimilarly, we can know the final XOR result of the `nums2` array.\n\nFinally, XOR the two results again to get the final result.\n\nThe time complexity is $O(m+n)$. Where $m$ and $n$ are the lengths of the `nums1` and `nums2` arrays, respectively." }, "is_english": true, "time_complexity": "O(m+n)", "space_complexity": null }, { "problem_id": 2426, "explanations": { "1": "We can transform the inequality in the problem to $nums1[i] - nums2[i] \\leq nums1[j] - nums2[j] + diff$. Therefore, if we calculate the difference between the corresponding elements of the two arrays and get another array $nums$, the problem is transformed into finding the number of pairs in $nums$ that satisfy $nums[i] \\leq nums[j] + diff$.\n\nWe can enumerate $j$ from small to large, find out how many numbers before it satisfy $nums[i] \\leq nums[j] + diff$, and thus calculate the number of pairs. We can use a binary indexed tree to maintain the prefix sum, so we can find out how many numbers before it satisfy $nums[i] \\leq nums[j] + diff$ in $O(\\log n)$ time.\n\nThe time complexity is $O(n \\times \\log n)$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": null }, { "problem_id": 2427, "explanations": { "1": "We can first calculate the greatest common divisor $g$ of $a$ and $b$, then enumerate each number in $[1,..g]$, check whether it is a factor of $g$, if it is, then increment the answer by one.\n\nThe time complexity is $O(\\min(a, b))$, and the space complexity is $O(1)$.", "2": "Similar to Solution 1, we can first calculate the greatest common divisor $g$ of $a$ and $b$, then enumerate all factors of the greatest common divisor $g$, and accumulate the answer.\n\nThe time complexity is $O(\\sqrt{\\min(a, b)})$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\min(a, b))", "space_complexity": "O(1)" }, { "problem_id": 2428, "explanations": { "1": "We observe from the problem statement that each hourglass is a $3 \\times 3$ matrix with the first and last elements of the middle row removed. Therefore, we can start from the top left corner, enumerate the middle coordinate $(i, j)$ of each hourglass, then calculate the sum of the elements in the hourglass, and take the maximum value.\n\nThe time complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns of the matrix, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(1)" }, { "problem_id": 2429, "explanations": { "1": "According to the problem description, we first calculate the number of set bits in $\\textit{num2}$, denoted as $\\textit{cnt}$. Then, we iterate from the highest to the lowest bit of $\\textit{num1}$; if the current bit is $1$, we set the corresponding bit in $x$ to $1$ and decrement $\\textit{cnt}$, until $\\textit{cnt}$ becomes $0$. If $\\textit{cnt}$ is still not $0$, we iterate from the lowest bit upwards, setting positions where $\\textit{num1}$ has $0$ to $1$ in $x$, and decrement $\\textit{cnt}$ until it reaches $0$.\n\nThe time complexity is $O(\\log n)$, where $n$ is the maximum value of $\\textit{num1}$ and $\\textit{num2}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 2430, "explanations": { "1": "We design a function $dfs(i)$, which represents the maximum number of operations needed to delete all characters from $s[i..]$. The answer is $dfs(0)$.\n\nThe calculation process of the function $dfs(i)$ is as follows:\n\n- If $i \\geq n$, then $dfs(i) = 0$, return directly.\n- Otherwise, we enumerate the length of the string $j$, where $1 \\leq j \\leq (n-1)/2$. If $s[i..i+j] = s[i+j..i+j+j]$, we can delete $s[i..i+j]$, then $dfs(i)=max(dfs(i), dfs(i+j)+1)$. We need to enumerate all $j$ to find the maximum value of $dfs(i)$.\n\nHere we need to quickly determine whether $s[i..i+j]$ is equal to $s[i+j..i+j+j]$. We can preprocess all the longest common prefixes of string $s$, that is, $g[i][j]$ represents the length of the longest common prefix of $s[i..]$ and $s[j..]$. In this way, we can quickly determine whether $s[i..i+j]$ is equal to $s[i+j..i+j+j]$, that is, $g[i][i+j] \\geq j$.\n\nTo avoid repeated calculations, we can use memoization search and use an array $f$ to record the value of the function $dfs(i)$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ is the length of the string $s$.", "2": "We can change the memoization search in Solution 1 to dynamic programming. Define $f[i]$ to represent the maximum number of operations needed to delete all characters from $s[i..]$. Initially, $f[i]=1$, and the answer is $f[0]$.\n\nWe can enumerate $i$ from back to front. For each $i$, we enumerate the length of the string $j$, where $1 \\leq j \\leq (n-1)/2$. If $s[i..i+j] = s[i+j..i+j+j]$, we can delete $s[i..i+j]$, then $f[i]=max(f[i], f[i+j]+1)$. We need to enumerate all $j$ to find the maximum value of $f[i]$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 2431, "explanations": { "1": "We design a function $dfs(i, j, k)$ to represent the maximum total tastiness starting from the $i$th fruit, with $j$ money left, and $k$ coupons left.\n\nFor the $i$th fruit, we can choose to buy or not to buy. If we choose to buy, we can decide whether to use a coupon or not.\n\nIf we don't buy, the maximum total tastiness is $dfs(i + 1, j, k)$;\n\nIf we buy, and choose not to use a coupon (requires $j\\ge price[i]$), the maximum total tastiness is $dfs(i + 1, j - price[i], k) + tastiness[i]$; if we use a coupon (requires $k\\gt 0$ and $j\\ge \\lfloor \\frac{price[i]}{2} \\rfloor$), the maximum total tastiness is $dfs(i + 1, j - \\lfloor \\frac{price[i]}{2} \\rfloor, k - 1) + tastiness[i]$.\n\nThe final answer is $dfs(0, maxAmount, maxCoupons)$.\n\nThe time complexity is $O(n \\times maxAmount \\times maxCoupons)$, where $n$ is the number of fruits." }, "is_english": true, "time_complexity": "O(n \\times maxAmount \\times maxCoupons)", "space_complexity": null }, { "problem_id": 2432, "explanations": { "1": "We use a variable $last$ to record the end time of the last task, a variable $mx$ to record the longest working time, and a variable $ans$ to record the employee with the longest working time and the smallest $id$. Initially, all three variables are $0$.\n\nNext, we traverse the array $logs$. For each employee, we subtract the end time of the last task from the time the employee completes the task to get the working time $t$ of this employee. If $mx$ is less than $t$, or $mx$ equals $t$ and the $id$ of this employee is less than $ans$, then we update $mx$ and $ans$. Then we update $last$ to be the end time of the last task plus $t$. Continue to traverse until the entire array is traversed.\n\nFinally, return the answer $ans$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $logs$. The space complexity is $O(1)$.", "2": "" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2433, "explanations": { "1": "According to the problem statement, we have equation one:\n\n$$\npref[i]=arr[0] \\oplus arr[1] \\oplus \\cdots \\oplus arr[i]\n$$\n\nSo, we also have equation two:\n\n$$\npref[i-1]=arr[0] \\oplus arr[1] \\oplus \\cdots \\oplus arr[i-1]\n$$\n\nWe perform a bitwise XOR operation on equations one and two, and get:\n\n$$\npref[i] \\oplus pref[i-1]=arr[i]\n$$\n\nThat is, each item in the answer array is obtained by performing a bitwise XOR operation on the adjacent two items in the prefix XOR array.\n\nThe time complexity is $O(n)$, where $n$ is the length of the prefix XOR array. Ignoring the space consumption of the answer, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2434, "explanations": { "1": "The problem can be transformed into: given a string sequence, use an auxiliary stack to convert it into the lexicographically smallest string sequence.\n\nWe can use an array $\\textit{cnt}$ to maintain the count of each character in string $s$, use a stack $\\textit{stk}$ as the auxiliary stack mentioned in the problem, and use a variable $\\textit{mi}$ to keep track of the smallest character not yet traversed in the string.\n\nTraverse the string $s$. For each character $c$, first decrement its count in the array $\\textit{cnt}$ and update $\\textit{mi}$. Then push $c$ onto the stack. At this point, if the top element of the stack is less than or equal to $\\textit{mi}$, repeatedly pop the top element from the stack and add it to the answer.\n\nAfter the traversal, return the answer.\n\nThe time complexity is $O(n + |\\Sigma|)$, and the space complexity is $O(n)$, where $n$ is the length of the string $s$ and $|\\Sigma|$ is the size of the character set, which is $26$ in this problem." }, "is_english": true, "time_complexity": "O(n + |\\Sigma|)", "space_complexity": "O(n)" }, { "problem_id": 2435, "explanations": { "1": "We denote the $k$ in the problem as $K$, and let $m$ and $n$ be the number of rows and columns of the matrix $\\textit{grid}$, respectively.\n\nDefine $f[i][j][k]$ as the number of paths starting from $(0, 0)$, reaching position $(i, j)$, where the sum of elements along the path modulo $K$ equals $k$. Initially, $f[0][0][\\textit{grid}[0][0] \\bmod K] = 1$. The final answer is $f[m - 1][n - 1][0]$.\n\nWe can derive the state transition equation:\n\n$$\nf[i][j][k] = f[i - 1][j][(k - \\textit{grid}[i][j])\\bmod K] + f[i][j - 1][(k - \\textit{grid}[i][j])\\bmod K]\n$$\n\nTo avoid issues with negative modulo operations, we can replace $(k - \\textit{grid}[i][j])\\bmod K$ in the above equation with $((k - \\textit{grid}[i][j] \\bmod K) + K) \\bmod K$.\n\nThe answer is $f[m - 1][n - 1][0]$.\n\nThe time complexity is $O(m \\times n \\times K)$ and the space complexity is $O(m \\times n \\times K)$, where $m$ and $n$ are the number of rows and columns of the matrix $\\textit{grid}$, respectively, and $K$ is the integer $k$ from the problem." }, "is_english": true, "time_complexity": "O(m \\times n \\times K)", "space_complexity": "O(m \\times n \\times K)" }, { "problem_id": 2436, "explanations": { "1": "For each element in the array, if its greatest common divisor (gcd) with the previous element is $1$, then it needs to be the first element of a new subarray. Otherwise, it can be placed in the same subarray with the previous elements.\n\nTherefore, we first initialize a variable $g$, representing the gcd of the current subarray. Initially, $g=0$ and the answer variable $ans=1$.\n\nNext, we traverse the array from front to back, maintaining the gcd $g$ of the current subarray. If the gcd of the current element $x$ and $g$ is $1$, then we need to make the current element the first element of a new subarray. Therefore, the answer increases by $1$, and $g$ is updated to $x$. Otherwise, the current element can be placed in the same subarray with the previous elements. Continue to traverse the array until the traversal ends.\n\nThe time complexity is $O(n \\times \\log m)$, where $n$ and $m$ are the length of the array and the maximum value in the array, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\log m)", "space_complexity": "O(1)" }, { "problem_id": 2437, "explanations": { "1": "We can directly enumerate all times from $00:00$ to $23:59$, then judge whether each time is valid, if so, increment the answer.\n\nAfter the enumeration ends, return the answer.\n\nThe time complexity is $O(24 \\times 60)$, and the space complexity is $O(1)$.", "2": "We can separately enumerate hours and minutes, count how many hours and minutes meet the condition, and then multiply them together.\n\nThe time complexity is $O(24 + 60)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(24 \\times 60)", "space_complexity": "O(1)" }, { "problem_id": 2438, "explanations": { "1": "We can use bit manipulation (lowbit) to obtain the $\\textit{powers}$ array, and then use simulation to find the answer for each query.\n\nFirst, for a given positive integer $n$, we can quickly obtain the value corresponding to the lowest bit $1$ in the binary representation through $n \\& -n$, which is the minimum power of $2$ factor of the current number. By repeatedly performing this operation on $n$ and subtracting this value, we can sequentially obtain all the powers of $2$ corresponding to the set bits, forming the $\\textit{powers}$ array. This array is in increasing order, and its length equals the number of $1$s in the binary representation of $n$.\n\nNext, we need to process each query. For the current query $(l, r)$, we need to calculate\n\n$$\n\\textit{answers}[i] = \\prod_{j=l}^{r} \\textit{powers}[j]\n$$\n\nwhere $\\textit{answers}[i]$ is the answer to the $i$-th query. Since the query results can be very large, we need to take modulo $10^9 + 7$ for each answer.\n\nThe time complexity is $O(m \\times \\log n)$, where $m$ is the length of the array $\\textit{queries}$. Ignoring the space consumption of the answer, the space complexity is $O(\\log n)$." }, "is_english": true, "time_complexity": "O(m \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 2439, "explanations": { "1": "To minimize the maximum value of the array, it is intuitive to use binary search. We binary search for the maximum value $mx$ of the array, and find the smallest $mx$ that satisfies the problem requirements.\n\nThe time complexity is $O(n \\times \\log M)$, where $n$ is the length of the array, and $M$ is the maximum value in the array." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": null }, { "problem_id": 2440, "explanations": { "1": "Assume the number of connected blocks is $k$, then the number of edges to be deleted is $k-1$, and the value of each connected block is $\\frac{s}{k}$, where $s$ is the sum of the values of all nodes in $nums$.\n\nWe enumerate $k$ from large to small. If there exists a $k$ such that $\\frac{s}{k}$ is an integer, and the value of each connected block obtained is equal, then directly return $k-1$. The initial value of $k$ is $\\min(n, \\frac{s}{mx})$, where $mx$ is the maximum value in $nums$.\n\nThe key point is to judge whether for a given $\\frac{s}{k}$, it is possible to divide several subtrees such that the value of each subtree is $\\frac{s}{k}$.\n\nHere we use the `dfs` function to judge. We recursively traverse from top to bottom to calculate the value of each subtree. If the sum of the subtree values is exactly $\\frac{s}{k}$, it means that the division is successful at this time. We set the value to $0$ and return it to the upper level, indicating that this subtree can be disconnected from the parent node. If the sum of the subtree values is greater than $\\frac{s}{k}$, it means that the division fails at this time. We return $-1$, indicating that it cannot be divided.\n\nThe time complexity is $O(n \\times \\sqrt{s})$, where $n$ and $s$ are the length of $nums$ and the sum of the values of all nodes in $nums$, respectively." }, "is_english": true, "time_complexity": "O(n \\times \\sqrt{s})", "space_complexity": null }, { "problem_id": 2441, "explanations": { "1": "We can use a hash table $s$ to record all elements that appear in the array, and a variable $ans$ to record the maximum positive integer that satisfies the problem requirements, initially $ans = -1$.\n\nNext, we traverse each element $x$ in the hash table $s$. If $-x$ exists in $s$, then we update $ans = \\max(ans, x)$.\n\nAfter the traversal ends, return $ans$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array.", "2": "" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2442, "explanations": { "1": "First, we use a hash table to record all integers in the array. Then, we traverse each integer in the array, reverse it, and add the reversed integer to the hash table. Finally, we return the size of the hash table.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2443, "explanations": { "1": "Enumerate $k$ in the range $[0,.., num]$, and check whether $k + reverse(k)$ equals $num$.\n\nThe time complexity is $O(n \\times \\log n)$, where $n$ is the size of $num$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": null }, { "problem_id": 2444, "explanations": { "1": "According to the problem description, we know that all elements of a bounded subarray are within the range $[\\textit{minK}, \\textit{maxK}]$, and the minimum value must be $\\textit{minK}$, while the maximum value must be $\\textit{maxK}$.\n\nWe iterate through the array $\\textit{nums}$ and count the number of bounded subarrays with $\\textit{nums}[i]$ as the right endpoint. Then, we sum up all the counts.\n\nThe specific implementation logic is as follows:\n\n1. Maintain the index $k$ of the most recent element that is not within the range $[\\textit{minK}, \\textit{maxK}]$, initialized to $-1$. The left endpoint of the current element $\\textit{nums}[i]$ must be greater than $k$.\n2. Maintain the most recent index $j_1$ where the value is $\\textit{minK}$ and the most recent index $j_2$ where the value is $\\textit{maxK}$, both initialized to $-1$. The left endpoint of the current element $\\textit{nums}[i]$ must be less than or equal to $\\min(j_1, j_2)$.\n3. Based on the above, the number of bounded subarrays with the current element as the right endpoint is $\\max\\bigl(0,\\ \\min(j_1, j_2) - k\\bigr)$. Accumulate all these counts to get the result.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2445, "explanations": { "1": "According to the problem description, we can simulate the process of each query, that is, reverse the values of the query node and its subtree nodes. Finally, count the number of nodes with a value of 1.\n\nThere is an optimization point here. If a node and its corresponding subtree have been queried an even number of times, the node value will not change. Therefore, we can record the number of queries for each node, and only reverse the nodes and their subtrees that have been queried an odd number of times.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2446, "explanations": { "1": "If the start time of $event1$ is later than the end time of $event2$, or the end time of $event1$ is earlier than the start time of $event2$, then the two events will not conflict. Otherwise, the two events will conflict.\n\n\"\"\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 2447, "explanations": { "1": "We can enumerate $nums[i]$ as the left endpoint of the subarray, and then enumerate $nums[j]$ as the right endpoint of the subarray, where $i \\le j$. During the enumeration of the right endpoint, we can use a variable $g$ to maintain the greatest common divisor of the current subarray. Each time we enumerate a new right endpoint, we update the greatest common divisor $g = \\gcd(g, nums[j])$. If $g=k$, then the greatest common divisor of the current subarray equals $k$, and we increase the answer by $1$.\n\nAfter the enumeration ends, return the answer.\n\nThe time complexity is $O(n \\times (n + \\log M))$, where $n$ and $M$ are the length of the array $nums$ and the maximum value in the array $nums$, respectively." }, "is_english": true, "time_complexity": "O(n \\times (n + \\log M))", "space_complexity": null }, { "problem_id": 2448, "explanations": { "1": "Let's denote the elements of the array `nums` as $a_1, a_2, \\cdots, a_n$ and the elements of the array `cost` as $b_1, b_2, \\cdots, b_n$. We can assume that $a_1 \\leq a_2 \\leq \\cdots \\leq a_n$, i.e., the array `nums` is sorted in ascending order.\n\nSuppose we change all elements in the array `nums` to $x$, then the total cost we need is:\n\n$$\n\\begin{aligned}\n\\sum_{i=1}^{n} \\left | a_i-x \\right | b_i &= \\sum_{i=1}^{k} (x-a_i)b_i + \\sum_{i=k+1}^{n} (a_i-x)b_i \\\\\n&= x\\sum_{i=1}^{k} b_i - \\sum_{i=1}^{k} a_ib_i + \\sum_{i=k+1}^{n}a_ib_i - x\\sum_{i=k+1}^{n}b_i\n\\end{aligned}\n$$\n\nwhere $k$ is the number of elements in $a_1, a_2, \\cdots, a_n$ that are less than or equal to $x$.\n\nWe can use the prefix sum method to calculate $\\sum_{i=1}^{k} b_i$ and $\\sum_{i=1}^{k} a_ib_i$, as well as $\\sum_{i=k+1}^{n}a_ib_i$ and $\\sum_{i=k+1}^{n}b_i$.\n\nThen we enumerate $x$, calculate the above four prefix sums, get the total cost mentioned above, and take the minimum value.\n\nThe time complexity is $O(n\\times \\log n)$, where $n$ is the length of the array `nums`. The main time complexity comes from sorting.", "2": "We can also consider $b_i$ as the occurrence times of $a_i$, then the index of the median is $\\frac{\\sum_{i=1}^{n} b_i}{2}$. Changing all numbers to the median is definitely optimal.\n\nThe time complexity is $O(n\\times \\log n)$, where $n$ is the length of the array `nums`. The main time complexity comes from sorting.\n\nSimilar problems:\n\n- [296. Best Meeting Point](https://github.com/doocs/leetcode/blob/main/solution/0200-0299/0296.Best%20Meeting%20Point/README_EN.md)\n- [462. Minimum Moves to Equal Array Elements II](https://github.com/doocs/leetcode/blob/main/solution/0400-0499/0462.Minimum%20Moves%20to%20Equal%20Array%20Elements%20II/README_EN.md)" }, "is_english": true, "time_complexity": "O(n\\times \\log n)", "space_complexity": null }, { "problem_id": 2449, "explanations": { "1": "Notice that, because each operation will only increase or decrease the value of an element by $2$, the parity of the element will not change.\n\nTherefore, we can divide the arrays $nums$ and $target$ into two groups according to their parity, denoted as $a_1$ and $a_2$, and $b_1$ and $b_2$ respectively.\n\nThen, we just need to pair the elements in $a_1$ with the elements in $b_1$, and pair the elements in $a_2$ with the elements in $b_2$, and then perform operations. During the pairing process, we can use a greedy strategy, pairing the smaller elements in $a_i$ with the smaller elements in $b_i$ each time, which can ensure the minimum number of operations. This can be directly implemented through sorting.\n\nSince each operation can reduce the difference of the corresponding elements by $4$, we accumulate the difference of each corresponding position, and finally divide by $4$ to get the answer.\n\nThe time complexity is $O(n \\times \\log n)$, where $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": null }, { "problem_id": 2450, "explanations": { "1": "Assume the length of the string $s$ is $n$. Then there are $n - k + 1$ substrings of length $k$, and each substring can be flipped, so there are $2^{n - k + 1}$ ways to flip.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2451, "explanations": { "1": "We use a hash table $d$ to maintain the mapping relationship between the difference array of the string and the string itself, where the difference array is an array composed of the differences of adjacent characters in the string. Since the problem guarantees that except for one string, the difference arrays of other strings are the same, we only need to find the string with a different difference array.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m + n)$. Here, $m$ and $n$ are the length of the string and the number of strings, respectively.", "2": "" }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m + n)" }, { "problem_id": 2452, "explanations": { "1": "We directly traverse each word $s$ in the array $\\textit{queries}$, and then traverse each word $t$ in the array $\\textit{dictionary}$. If there exists a word $t$ whose edit distance from $s$ is less than $3$, we add $s$ to the answer array and then exit the inner loop. If there is no such word $t$, we continue to traverse the next word $s$.\n\nThe time complexity is $O(m \\times n \\times l)$, where $m$ and $n$ are the lengths of the arrays $\\textit{queries}$ and $\\textit{dictionary}$ respectively, and $l$ is the length of the word." }, "is_english": true, "time_complexity": "O(m \\times n \\times l)", "space_complexity": null }, { "problem_id": 2453, "explanations": { "1": "We traverse the array $nums$ and use a hash table $cnt$ to count the frequency of each number modulo $space$. The higher the frequency, the more targets can be destroyed. We find the group with the highest frequency and take the minimum value in the group.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2454, "explanations": { "1": "We can convert the elements in the array into pairs $(x, i)$, where $x$ is the value of the element and $i$ is the index of the element. Then sort by the value of the elements in descending order.\n\nNext, we traverse the sorted array, maintaining an ordered set that stores the indices of the elements. When we traverse to the element $(x, i)$, the indices of all elements greater than $x$ are already in the ordered set. We only need to find the index $j$ of the next element after $i$ in the ordered set, then the element corresponding to $j$ is the second largest element of $x$. Then, we add $i$ to the ordered set. Continue to traverse the next element.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2455, "explanations": { "1": "We notice that an even number divisible by $3$ must be a multiple of $6$. Therefore, we only need to traverse the array, count the sum and the number of all multiples of $6$, and then calculate the average.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$.", "2": "" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2456, "explanations": { "1": "We traverse the three arrays, use a hash table $cnt$ to count the total play count for each creator, and use a hash table $d$ to record the index of the video with the highest play count for each creator.\n\nThen, we traverse the hash table $cnt$ to find the maximum play count $mx$; then we traverse the hash table $cnt$ again to find the creators with a play count of $mx$, and add them to the answer array.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of videos." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2457, "explanations": { "1": "We define a function $f(x)$ to represent the sum of the digits of an integer $x$. The problem is to find the minimum non-negative integer $x$ such that $f(n + x) \\leq target$.\n\nIf the sum of the digits of $y = n+x$ is greater than $target$, we can loop through the following operations to reduce the sum of the digits of $y$ to less than or equal to $target$:\n\n- Find the lowest non-zero digit of $y$, reduce it to $0$, and add $1$ to the digit one place higher;\n- Update $x$ and continue the above operation until the sum of the digits of $n+x$ is less than or equal to $target$.\n\nAfter the loop ends, return $x$.\n\nFor example, if $n=467$ and $target=6$, the change process of $n$ is as follows:\n\n$$\n\\begin{aligned}\n& 467 \\rightarrow 470 \\rightarrow 500 \\\\\n\\end{aligned}\n$$\n\nThe time complexity is $O(\\log^2 n)$, where $n$ is the integer given in the problem. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log^2 n)", "space_complexity": "O(1)" }, { "problem_id": 2458, "explanations": { "1": "First, we perform a DFS traversal to determine the depth of each node, which we store in a hash table $d$, where $d[x]$ represents the depth of node $x$.\n\nThen we design a function $dfs(root, depth, rest)$, where:\n\n- `root` represents the current node;\n- `depth` represents the depth of the current node;\n- `rest` represents the height of the tree after deleting the current node.\n\nThe function's computation logic is as follows:\n\nIf the node is null, return directly. Otherwise, we increment `depth` by $1$, and then store `rest` in `res`.\n\nNext, we recursively traverse the left and right subtrees.\n\nBefore recursing into the left subtree, we calculate the depth from the root node to the deepest node in the current node's right subtree, i.e., $depth+d[root.right]$, and then compare it with `rest`, taking the larger value as the `rest` for the left subtree.\n\nBefore recursing into the right subtree, we calculate the depth from the root node to the deepest node in the current node's left subtree, i.e., $depth+d[root.left]$, and then compare it with `rest`, taking the larger value as the `rest` for the right subtree.\n\nFinally, we return the result values corresponding to each query node.\n\nThe time complexity is $O(n+m)$, and the space complexity is $O(n)$. Here, $n$ and $m$ are the number of nodes in the tree and the number of queries, respectively.", "2": "" }, "is_english": true, "time_complexity": "O(n+m)", "space_complexity": "O(n)" }, { "problem_id": 2459, "explanations": { "1": "For a permutation cycle of length $m$, if $0$ is in the cycle, the number of swaps is $m-1$; otherwise, the number of swaps is $m+1$.\n\nWe find all permutation cycles, first calculate the total number of swaps assuming each cycle requires $m+1$ swaps, then check if $0$ is misplaced. If it is, it means $0$ is in a permutation cycle, so we subtract $2$ from the total number of swaps.\n\nHere, $0$ can be at position $0$ or at position $n-1$. We take the minimum of these two cases.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2460, "explanations": { "1": "We can directly simulate according to the problem description.\n\nFirst, we traverse the array $nums$. For any two adjacent elements $nums[i]$ and $nums[i+1]$, if $nums[i] = nums[i+1]$, then we double the value of $nums[i]$ and change the value of $nums[i+1]$ to $0$.\n\nThen, we create an answer array $ans$ of length $n$, and put all non-zero elements of $nums$ into $ans$ in order.\n\nFinally, we return the answer array $ans$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. Ignoring the space consumption of the answer, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2461, "explanations": { "1": "We maintain a sliding window of length $k$, use a hash table $cnt$ to record the count of each number in the window, and use a variable $s$ to record the sum of all numbers in the window. Each time we slide the window, if all numbers in the window are unique, we update the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2462, "explanations": { "1": "First, we check if $candidates \\times 2$ is greater than or equal to $n$. If it is, we directly return the sum of the costs of the first $k$ smallest workers.\n\nOtherwise, we use a min heap $pq$ to maintain the costs of the first $candidates$ workers and the last $candidates$ workers.\n\nWe first add the costs and corresponding indices of the first $candidates$ workers to the min heap $pq$, and then add the costs and corresponding indices of the last $candidates$ workers to the min heap $pq$. We use two pointers $l$ and $r$ to point to the indices of the front and back candidates, initially $l = candidates$, $r = n - candidates - 1$.\n\nThen we perform $k$ iterations, each time taking the worker with the smallest cost from the min heap $pq$ and adding its cost to the answer. If $l > r$, it means that all the front and back candidates have been selected, and we skip directly. Otherwise, if the index of the current worker is less than $l$, it means it is a worker from the front, we add the cost and index of the $l$-th worker to the min heap $pq$, and then increment $l$; otherwise, we add the cost and index of the $r$-th worker to the min heap $pq$, and then decrement $r$.\n\nAfter the loop ends, we return the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $costs$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2463, "explanations": { "1": "First, we sort the robots and factories in ascending order. Then we define a function $dfs(i, j)$ to represent the minimum total moving distance starting from the $i$-th robot and the $j$-th factory.\n\nFor $dfs(i, j)$, if the $j$-th factory does not repair the robot, then $dfs(i, j) = dfs(i, j+1)$. If the $j$-th factory repairs the robot, we can enumerate the number of robots repaired by the $j$-th factory and find the minimum total moving distance. That is, $dfs(i, j) = min(dfs(i + k + 1, j + 1) + \\sum_{t = 0}^{k} |robot[i + t] - factory[j][0]|)$.\n\nThe time complexity is $O(m^2 \\times n)$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the number of robots and factories, respectively." }, "is_english": true, "time_complexity": "O(m^2 \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 2464, "explanations": { "1": "We design a function $dfs(i)$ to represent the minimum number of partitions starting from index $i$. For index $i$, we can enumerate all partition points $j$, i.e., $i \\leq j < n$, where $n$ is the length of the array. For each partition point $j$, we need to determine whether the greatest common divisor of $nums[i]$ and $nums[j]$ is greater than $1$. If it is greater than $1$, we can partition, and the number of partitions is $1 + dfs(j + 1)$; otherwise, the number of partitions is $+\\infty$. Finally, we take the minimum of all partition numbers.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 2465, "explanations": { "1": "The problem requires us to find the minimum and maximum values in the array $nums$ each time, delete them, and then calculate the average of the two deleted numbers. Therefore, we can first sort the array $nums$, then take the first and last elements of the array each time, calculate their sum, use a hash table or array $cnt$ to record the number of times each sum appears, and finally count the number of different sums.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$.", "2": "", "3": "" }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2466, "explanations": { "1": "We design a function $dfs(i)$ to represent the number of good strings constructed starting from the $i$-th position. The answer is $dfs(0)$.\n\nThe computation process of the function $dfs(i)$ is as follows:\n\n- If $i > high$, return $0$;\n- If $low \\leq i \\leq high$, increment the answer by $1$, then after $i$, we can add either `zero` number of $0$s or `one` number of $1$s. Therefore, the answer is incremented by $dfs(i + zero) + dfs(i + one)$.\n\nDuring the process, we need to take the modulus of the answer, and we can use memoization search to reduce redundant computations.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n = high$.", "2": "" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2467, "explanations": { "1": "According to the problem, we know that Bob's moving path is fixed, that is, starting from node $bob$ and finally reaching node $0$. Therefore, we can first run a DFS to find out the time it takes for Bob to reach each node, which we record in the array $ts$.\n\nThen we run another DFS to find the maximum score for each of Alice's moving paths. We denote the time for Alice to reach node $i$ as $t$, and the current cumulative score as $v$. After Alice passes node $i$, the cumulative score has three cases:\n\n1. The time $t$ for Alice to reach node $i$ is the same as the time $ts[i]$ for Bob to reach node $i$. In this case, Alice and Bob open the door at node $i$ at the same time, and the score Alice gets is $v + \\frac{amount[i]}{2}$.\n2. The time $t$ for Alice to reach node $i$ is less than the time $ts[i]$ for Bob to reach node $i$. In this case, Alice opens the door at node $i$, and the score Alice gets is $v + amount[i]$.\n3. The time $t$ for Alice to reach node $i$ is greater than the time $ts[i]$ for Bob to reach node $i$. In this case, Alice does not open the door at node $i$, and the score Alice gets is $v$, which remains unchanged.\n\nWhen Alice reaches a leaf node, update the maximum score.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2468, "explanations": { "1": "We denote the length of the string `message` as $n$, and the number of segments as $k$.\n\nAccording to the problem, if $k > n$, it means that we can divide the string into more than $n$ segments. Since the length of the string is only $n$, dividing it into more than $n$ segments will inevitably lead to some segments with a length of $0$, which can be deleted. Therefore, we only need to limit the range of $k$ to $[1,.. n]$.\n\nWe enumerate the number of segments $k$ from small to large. Let the length of $a$ segments in all segments be $sa$, the length of $b$ segments in all segments be $sb$, and the length of all symbols (including angle brackets and slashes) in all segments be $sc$.\n\nThen the value of $sa$ is ${\\textstyle \\sum_{j=1}^{k}} len(s_j)$, which can be directly obtained through the prefix sum; the value of $sb$ is $len(str(k)) \\times k$; and the value of $sc$ is $3 \\times k$.\n\nTherefore, the number of characters that can be filled in all segments is $limit\\times k - (sa + sb + sc)$. If this value is greater than or equal to $n$, it means that the string can be divided into $k$ segments, and we can directly construct the answer and return it.\n\nThe time complexity is $O(n\\times \\log n)$, where $n$ is the length of the string `message`. Ignoring the space consumption of the answer, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n\\times \\log n)", "space_complexity": "O(1)" }, { "problem_id": 2469, "explanations": { "1": "We can directly simulate according to the problem description.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 2470, "explanations": { "1": "Enumerate each number as the first number of the subarray, and then enumerate each number as the last number of the subarray. Calculate the least common multiple of this subarray. If the least common multiple equals $k$, then increment the answer by one.\n\nThe time complexity is $O(n^2)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": null }, { "problem_id": 2471, "explanations": { "1": "First, we traverse the binary tree using BFS to find the node values at each level. Then, we sort the node values at each level. If the sorted node values are different from the original node values, it means that we need to swap elements. The number of swaps is the number of operations needed at that level.\n\nThe time complexity is $O(n \\times \\log n)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": null }, { "problem_id": 2472, "explanations": { "1": "First, preprocess the string $s$ to get $dp[i][j]$, which represents whether the substring $s[i,..j]$ is a palindrome.\n\nThen, define a function $dfs(i)$ to represent the maximum number of non-overlapping palindrome substrings that can be selected from the substring $s[i,..]$, i.e.,\n\n$$\n\\begin{aligned}\ndfs(i) &= \\begin{cases}\n0, & i \\geq n \\\\\n\\max\\{dfs(i + 1), \\max_{j \\geq i + k - 1} \\{dfs(j + 1) + 1\\}\\}, & i < n\n\\end{cases}\n\\end{aligned}\n$$\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 2473, "explanations": { "1": "We enumerate the starting point, and for each starting point, we use Dijkstra's algorithm to find the shortest distance to all other points, and update the minimum value accordingly.\n\nThe time complexity is $O(n \\times m \\times \\log m)$, where $n$ and $m$ are the number of cities and roads, respectively." }, "is_english": true, "time_complexity": "O(n \\times m \\times \\log m)", "space_complexity": null }, { "problem_id": 2474, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2475, "explanations": { "1": "We can directly enumerate all triples $(i, j, k)$ and count all the ones that meet the conditions.\n\nThe time complexity is $O(n^3)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$.", "2": "We can also sort the array $nums$ first.\n\nThen traverse $nums$, enumerate the middle element $nums[j]$, and use binary search to find the nearest index $i$ on the left side of $nums[j]$ such that $nums[i] < nums[j]$; find the nearest index $k$ on the right side of $nums[j]$ such that $nums[k] > nums[j]$. Then the number of triples with $nums[j]$ as the middle element and meeting the conditions is $(i + 1) \\times (n - k)$, which is added to the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array $nums$.", "3": "We can also use a hash table $cnt$ to count the number of each element in the array $nums$.\n\nThen traverse the hash table $cnt$, enumerate the number of middle elements $b$, and denote the number of elements on the left as $a$. Then the number of elements on the right is $c = n - a - b$. At this time, the number of triples that meet the conditions is $a \\times b \\times c$, which is added to the answer. Then update $a = a + b$ and continue to enumerate the number of middle elements $b$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$.", "4": "" }, "is_english": true, "time_complexity": "O(n^3)", "space_complexity": "O(1)" }, { "problem_id": 2476, "explanations": { "1": "Since the problem provides a binary search tree, we can obtain a sorted array through in-order traversal. Then for each query, we can find the maximum value less than or equal to the query value and the minimum value greater than or equal to the query value through binary search.\n\nThe time complexity is $O(n + m \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ and $m$ are the number of nodes in the binary search tree and the number of queries, respectively." }, "is_english": true, "time_complexity": "O(n + m \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2477, "explanations": { "1": "According to the problem description, we can find that all cars will only drive towards the capital (node $0$).\n\nSuppose there is a node $a$, its next node is $b$, and node $a$ needs to pass through node $b$ to reach the capital. In order to make the vehicles (fuel consumption) of node $a$ as small as possible, we should greedily let the vehicles of the child nodes of node $a$ converge to node $a$ first, and then distribute the vehicles according to the number of seats $seats$. The minimum number of vehicles (fuel consumption) needed to reach node $b$ is $\\lceil \\frac{sz}{seats} \\rceil$. Where $sz$ represents the number of nodes in the subtree with node $a$ as the root.\n\nWe start a depth-first search from node $0$, using a variable $sz$ to count the number of nodes in the subtree with the current node as the root. Initially, $sz = 1$, representing the current node itself. Then we traverse all the child nodes of the current node. For each child node $b$, we recursively calculate the number of nodes $t$ in the subtree with $b$ as the root, and add $t$ to $sz$, and then we add $\\lceil \\frac{t}{seats} \\rceil$ to the answer. Finally, return $sz$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2478, "explanations": { "1": "We define $f[i][j]$ as the number of schemes for dividing the first $i$ characters into $j$ sections. Initialize $f[0][0] = 1$, and the rest $f[i][j] = 0$.\n\nFirst, we need to determine whether the $i$th character can be the last character of the $j$th section, it needs to meet the following conditions simultaneously:\n\n1. The $i$th character is a non-prime number;\n1. The $i+1$th character is a prime number, or the $i$th character is the last character of the entire string.\n\nIf the $i$th character cannot be the last character of the $j$th section, then $f[i][j]=0$. Otherwise, we have:\n\n$$\nf[i][j]=\\sum_{t=0}^{i-minLength}f[t][j-1]\n$$\n\nThat is to say, we need to enumerate which character is the end of the previous section. Here we use the prefix sum array $g[i][j] = \\sum_{t=0}^{i}f[t][j]$ to optimize the time complexity of enumeration.\n\nThen we have:\n\n$$\nf[i][j]=g[i-minLength][j-1]\n$$\n\nThe time complexity is $O(n \\times k)$, and the space complexity is $O(n \\times k)$. Where $n$ and $k$ are the length of the string $s$ and the number of sections to be divided, respectively." }, "is_english": true, "time_complexity": "O(n \\times k)", "space_complexity": "O(n \\times k)" }, { "problem_id": 2479, "explanations": { "1": "我们先递归预处理出每个节点的子树和,记录在数组 $s$ 中。\n\n然后使用 0-1 前缀树维护遍历过的子树和,可以方便快速查找下一个子树和与之前的子树和的最大异或值。\n\n由于子树不能重叠,因此,我们先查询最大异或值,递归结束后,再将当前子树和插入到前缀树中。\n\n时间复杂度 $O(n \\times log M)$,其中 $n$ 为节点个数,而 $M$ 为子树和的最大值。" }, "is_english": false, "time_complexity": "O(n \\times log M)", "space_complexity": null }, { "problem_id": 2480, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2481, "explanations": { "1": "- When $n=1$, no cutting is needed, so the number of cuts is $0$;\n- When $n$ is odd, there is no collinear situation, and at least $n$ cuts are needed;\n- When $n$ is even, they can be collinear in pairs, and at least $\\frac{n}{2}$ cuts are needed.\n\nIn summary, we can get:\n\n$$\n\\textit{ans} = \\begin{cases}\nn, & n \\gt 1 \\textit{ and } n \\textit{ is odd} \\\\\n\\frac{n}{2}, & n \\textit{ is even} \\\\\n\\end{cases}\n$$\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 2482, "explanations": { "1": "We can solve this problem by simulating the process as described in the problem statement.\n\nThe time complexity is $O(m \\times n)$, and if we ignore the space used by the answer, the space complexity is $O(m + n)$. Here, $m$ and $n$ are the number of rows and columns in the matrix, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m + n)" }, { "problem_id": 2483, "explanations": { "1": "If the shop closes at hour $0$, then the cost is the number of character `'Y'` in $\\textit{customers}$. We initialize the answer variable $\\textit{ans}$ to $0$, and the cost variable $\\textit{cost}$ to the number of character `'Y'` in $\\textit{customers}$.\n\nNext, we enumerate the shop closing at hour $j$ ($1 \\leq j \\leq n$). If $\\textit{customers}[j - 1]$ is `'N'`, it means no customer arrived during the open period, and the cost increases by $1$; otherwise, it means a customer arrived during the closed period, and the cost decreases by $1$. If the current cost $\\textit{cost}$ is less than the minimum cost $\\textit{mn}$, we update the answer variable $\\textit{ans}$ to $j$, and update the minimum cost $\\textit{mn}$ to the current cost $\\textit{cost}$.\n\nAfter the traversal ends, we return the answer variable $\\textit{ans}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $\\textit{customers}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2484, "explanations": { "1": "The time complexity is $O(100 \\times n)$, and the space complexity is $O(100 \\times n)$. Where $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(100 \\times n)", "space_complexity": "O(100 \\times n)" }, { "problem_id": 2485, "explanations": { "1": "We can directly enumerate $x$ in the range of $[1,..n]$, and check whether the following equation holds. If it holds, then $x$ is the pivot integer, and we can directly return $x$.\n\n$$\n(1 + x) \\times x = (x + n) \\times (n - x + 1)\n$$\n\nThe time complexity is $O(n)$, where $n$ is the given positive integer $n$. The space complexity is $O(1)$.", "2": "We can transform the above equation to get:\n\n$$\nn \\times (n + 1) = 2 \\times x^2\n$$\n\nThat is:\n\n$$\nx = \\sqrt{\\frac{n \\times (n + 1)}{2}}\n$$\n\nIf $x$ is an integer, then $x$ is the pivot integer, otherwise there is no pivot integer.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2486, "explanations": { "1": "We define two pointers $i$ and $j$, pointing to the first characters of strings $s$ and $t$ respectively. We iterate through string $s$, if $s[i] = t[j]$, then we move $j$ one step forward. Finally, we return $n - j$, where $n$ is the length of string $t$.\n\nThe time complexity is $O(m + n)$, where $m$ and $n$ are the lengths of strings $s$ and $t$ respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m + n)", "space_complexity": "O(1)" }, { "problem_id": 2487, "explanations": { "1": "We can first store the node values of the linked list into an array $nums$. Then, we traverse the array $nums$, maintaining a stack $stk$ that is monotonically decreasing from the bottom to the top. If the current element is larger than the top element of the stack, we pop the top element of the stack until the current element is less than or equal to the top element, and then we push the current element into the stack.\n\nFinally, we construct the resulting linked list from the bottom to the top of the stack, which is the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the linked list.\n\nWe can also directly traverse the linked list without using the array $nums$, maintaining a stack $stk$ that is monotonically decreasing from the bottom to the top. If the current element is larger than the top element of the stack, we pop the top element of the stack until the current element is less than or equal to the top element. Then, if the stack is not empty, we set the $next$ pointer of the top element of the stack to the current element. Otherwise, we set the $next$ pointer of the dummy head node of the answer linked list to the current element. Finally, we push the current element into the stack and continue to traverse the linked list.\n\nAfter the traversal, we return the $next$ pointer of the dummy head node as the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the linked list.", "2": "" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2488, "explanations": { "1": "First, we find the position $i$ of the median $k$ in the array, and then start traversing from $i$ to both sides, counting the number of subarrays with a median of $k$.\n\nDefine an answer variable $ans$, which represents the number of subarrays with a median of $k$. Initially, $ans = 1$, which means that there is currently a subarray of length $1$ with a median of $k$. In addition, define a counter $cnt$, used to count the number of differences between the \"number of elements larger than $k$\" and the \"number of elements smaller than $k$\" in the currently traversed array.\n\nNext, start traversing to the right from $i + 1$. We maintain a variable $x$, which represents the difference between the \"number of elements larger than $k$\" and the \"number of elements smaller than $k$\" in the current right subarray. If $x \\in [0, 1]$, then the median of the current right subarray is $k$, and the answer variable $ans$ is incremented by $1$. Then, we add the value of $x$ to the counter $cnt$.\n\nSimilarly, start traversing to the left from $i - 1$, also maintaining a variable $x$, which represents the difference between the \"number of elements larger than $k$\" and the \"number of elements smaller than $k$\" in the current left subarray. If $x \\in [0, 1]$, then the median of the current left subarray is $k$, and the answer variable $ans$ is incremented by $1$. If $-x$ or $-x + 1$ is also in the counter, it means that there is currently a subarray that spans both sides of $i$, with a median of $k$, and the answer variable $ans$ increases the corresponding value in the counter, that is, $ans += cnt[-x] + cnt[-x + 1]$.\n\nFinally, return the answer variable $ans$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array.\n\n> In coding, we can directly open an array of length $2 \\times n + 1$, used to count the difference between the \"number of elements larger than $k$\" and the \"number of elements smaller than $k$\" in the current array. Each time we add the difference by $n$, we can convert the range of the difference from $[-n, n]$ to $[0, 2n]$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2489, "explanations": { "1": "We use $one[i]$ to represent the number of $1$s in the substring $s[0,..i]$, and $zero[i]$ to represent the number of $0$s in the substring $s[0,..i]$. A substring meets the condition if\n\n$$\n\\frac{zero[j] - zero[i]}{one[j] - one[i]} = \\frac{num1}{num2}\n$$\n\nwhere $i < j$. We can transform the above equation into\n\n$$\none[j] \\times num1 - zero[j] \\times num2 = one[i] \\times num1 - zero[i] \\times num2\n$$\n\nWhen we iterate to index $j$, we only need to count how many indices $i$ satisfy the above equation. Therefore, we can use a hash table to record the number of occurrences of $one[i] \\times num1 - zero[i] \\times num2$, and when we iterate to index $j$, we only need to count the number of occurrences of $one[j] \\times num1 - zero[j] \\times num2$.\n\nThe hash table initially only has one key-value pair $(0, 1)$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2490, "explanations": { "1": "We split the string into words by spaces, then check whether the last character of each word is equal to the first character of the next word. If they are not equal, return `false`. Otherwise, return `true` after traversing all the words.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string.", "2": "We can first check whether the first and last characters of the string are equal. If they are not equal, return `false`. Otherwise, traverse the string. If the current character is a space, check whether the previous character and the next character are equal. If they are not equal, return `false`. Otherwise, return `true` after traversing all the characters.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2491, "explanations": { "1": "To make all 2-person teams have equal skill points, the minimum value must match the maximum value. Therefore, we sort the `skill` array, and then use two pointers $i$ and $j$ to point to the beginning and end of the array respectively, match them in pairs, and judge whether their sum is the same number.\n\nIf not, it means that the skill points cannot be equal, and we directly return $-1$. Otherwise, we add the chemical reaction to the answer.\n\nAt the end of the traversal, we return the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Where $n$ is the length of the `skill` array.", "2": "The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the `skill` array." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 2492, "explanations": { "1": "According to the problem description, each edge can be passed multiple times, and it is guaranteed that node $1$ and node $n$ are in the same connected component. Therefore, the problem is actually looking for the smallest edge in the connected component where node $1$ is located. We can use DFS, start searching from node $1$, and find the smallest edge.\n\nThe time complexity is $O(n + m)$, where $n$ and $m$ are the number of nodes and edges, respectively.", "2": "We can also use BFS to solve this problem.\n\nThe time complexity is $O(n + m)$, where $n$ and $m$ are the number of nodes and edges, respectively." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": null }, { "problem_id": 2493, "explanations": { "1": "Given that the graph provided by the problem may be disconnected, we need to process each connected component, find the maximum number of groups in each connected component, and accumulate them to get the final result.\n\nWe can enumerate each node as the node of the first group, then use BFS to traverse the entire connected component, and use an array $d$ to record the maximum number of groups in each connected component. In the code implementation, we use the smallest node in the connected component as the root node of this connected component.\n\nDuring the BFS process, we use a queue $q$ to store the nodes currently traversed, use an array $dist$ to record the distance from each node to the starting node, use a variable $mx$ to record the maximum depth of the current connected component, and use a variable $root$ to record the root node of the current connected component.\n\nDuring the traversal, if we find that the $dist[b]$ of a certain node $b$ is $0$, it means that $b$ has not been traversed yet. We set the distance of $b$ to $dist[a] + 1$, update $mx$, and add $b$ to the queue $q$. If the distance of $b$ has been updated, we check whether the distance between $b$ and $a$ is $1$. If not, it means that the problem requirements cannot be met, so we directly return $-1$.\n\nThe time complexity is $O(n \\times (n + m))$, and the space complexity is $O(n + m)$. Where $n$ and $m$ are the number of nodes and edges respectively." }, "is_english": true, "time_complexity": "O(n \\times (n + m))", "space_complexity": "O(n + m)" }, { "problem_id": 2494, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2495, "explanations": { "1": "We know that the product of a subarray is even if and only if there is at least one even number in the subarray.\n\nTherefore, we can traverse the array, record the index `last` of the most recent even number, then the number of subarrays ending with the current element and having an even product is `last + 1`. We can add this to the result.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array `nums`. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2496, "explanations": { "1": "我们定义一个函数 $f(s)$,用于计算字符串 $s$ 的值。如果 $s$ 只包含数字,那么 $f(s)$ 就是 $s$ 在十进制下的值;否则 $f(s)$ 就是 $s$ 的长度。\n\n答案为 $\\max\\limits_{s \\in \\textit{strs}} f(s)$。\n\n时间复杂度 $O(n)$,其中 $n$ 是数组 $strs$ 的长度。空间复杂度 $O(1)$。", "2": "", "3": "" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2497, "explanations": { "1": "我们先将输入的边集合转换成邻接表,其中 $g[i]$ 表示节点 $i$ 的邻居节点的值列表,且按照值的降序排列。\n\n然后我们遍历每个节点 $i$,计算以 $i$ 为中心节点的星图的最大星和,即 $vals[i] + \\sum_{j=0}^{k-1} g[i][j]$,并且更新最大星和。\n\n最后返回最大星和即可。\n\n时间复杂度 $O(n \\times \\log n)$,空间复杂度 $O(n)$,其中 $n$ 为节点数。" }, "is_english": false, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2498, "explanations": { "1": "要使得跳跃过程中的每一步的最大跳跃长度最小,我们应该将跳跃过程切分成尽可能多的连续的步骤。通过观察,间隔跳跃可以获取最优解。\n\n时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 `stones` 的长度。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2499, "explanations": { "1": "我们先同时遍历数组 `nums1` 和 `nums2`,统计相同位置上的值相同的个数 `same`,这些位置上的值必须交换,因此,将这些位置下标累加到答案中。另外,用数组或哈希表 `cnt` 统计这些相同值的出现次数。\n\n如果所有相同值的出现次数均不超过 `same` 的一半,那么意味着,我们可以在其内部,通过两两交换,使得对应位置上的值不同,而这些交换,已经在上面累加下标时计入了答案中了,无需额外的代价。否则,如果某个值的出现次数超过 `same` 的一半,那么对于这个值就是多出的个数,我们需要在数组的其他位置上找到合适的,进行交换。这里我们可以直接遍历一遍数组得出。\n\n如果最终还有剩余位置未能交换,说明无法达成目标,返回 $-1$ 即可,否则返回答案。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 `nums1` 或 `nums2` 的长度。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2500, "explanations": { "1": "Since each operation involves removing the maximum value from each row and then adding the maximum value to the answer, we can first sort each row.\n\nNext, we traverse each column, take the maximum value from each column, and add it to the answer.\n\nThe time complexity is $O(m \\times n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $m$ and $n$ are the number of rows and columns of the matrix, respectively." }, "is_english": true, "time_complexity": "O(m \\times n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 2501, "explanations": { "1": "We first use a hash table to record all elements in the array. Then, we enumerate each element in the array as the first element of the subsequence, square this element continuously, and check whether the squared result is in the hash table. If it is, we use the squared result as the next element and continue checking until the squared result is not in the hash table. At this point, we check whether the length of the subsequence is greater than $1$. If it is, we update the answer.\n\nThe time complexity is $O(n \\times \\log \\log M)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$, and $M$ is the maximum value of the elements in the array $\\textit{nums}$.", "2": "Similar to Solution 1, we first use a hash table to record all elements in the array. Then, we design a function $\\textit{dfs}(x)$, which represents the length of the square wave starting with $x$. The answer is $\\max(\\textit{dfs}(x))$, where $x$ is an element in the array $\\textit{nums}$.\n\nThe calculation process of the function $\\textit{dfs}(x)$ is as follows:\n\n- If $x$ is not in the hash table, return $0$.\n- Otherwise, return $1 + \\textit{dfs}(x^2)$.\n\nDuring the process, we can use memoization, i.e., use a hash table to record the value of the function $\\textit{dfs}(x)$ to avoid redundant calculations.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times \\log \\log M)", "space_complexity": "O(n)" }, { "problem_id": 2502, "explanations": { "1": "The data range of the problem is not large, so we can directly use an array to simulate the memory space.\n\nDuring initialization, set each element in the array to $0$, indicating it's free.\n\nWhen the `allocate` method is called, traverse the array, find `size` consecutive free memory units, set them to `mID`, and return the first index.\n\nWhen the `free` method is called, traverse the array, set all memory units equal to `mID` to $0$, indicating they are free.\n\nThe time complexity is $O(n \\times q)$, and the space complexity is $O(n)$, where $n$ and $q$ are the size of the memory space and the number of method calls, respectively.", "2": "We can use an ordered set to maintain the start and end indices of all allocated memory units, where the start index is the key and the end index is the value. Additionally, we use a hash table to maintain the `mID` and its corresponding start index of the memory unit.\n\nWhen the `allocate` method is called, we traverse the ordered set, find the first free interval with a length greater than or equal to `size`, allocate it to `mID`, and update the ordered set. Then we add the `mID` and its corresponding start index of the memory unit to the hash table.\n\nWhen the `free` method is called, we find the start index of the memory unit corresponding to `mID` from the hash table, then delete it from the ordered set, and then delete `mID` from the hash table.\n\nThe time complexity is $O(q \\log n)$, and the space complexity is $O(n)$, where $n$ and $q$ are the size of the memory space and the number of method calls, respectively." }, "is_english": true, "time_complexity": "O(n \\times q)", "space_complexity": "O(n)" }, { "problem_id": 2503, "explanations": { "1": "According to the problem description, each query is independent, the order of the queries does not affect the result, and we are required to start from the top left corner each time, counting the number of cells that can be accessed and whose value is less than the current query value.\n\nTherefore, we can first sort the `queries` array, and then process each query in ascending order.\n\nWe use a priority queue (min heap) to maintain the smallest cell value that we have currently accessed, and use an array or hash table `vis` to record whether the current cell has been visited. Initially, we add the data $(grid[0][0], 0, 0)$ of the top left cell as a tuple to the priority queue, and set `vis[0][0]` to `True`.\n\nFor each query `queries[i]`, we judge whether the minimum value of the current priority queue is less than `queries[i]`. If it is, we pop the current minimum value, increment the counter `cnt`, and add the four cells above, below, left, and right of the current cell to the priority queue, noting to check whether they have been visited. Repeat the above operation until the minimum value of the current priority queue is greater than or equal to `queries[i]`, at which point `cnt` is the answer to the current query.\n\nThe time complexity is $O(k \\times \\log k + m \\times n \\log(m \\times n))$, and the space complexity is $O(m \\times n)$. Where $m$ and $n$ are the number of rows and columns of the grid, and $k$ is the number of queries. We need to sort the `queries` array, which has a time complexity of $O(k \\times \\log k)$. Each cell in the matrix will be visited at most once, and the time complexity of each enqueue and dequeue operation is $O(\\log(m \\times n))$. Therefore, the total time complexity is $O(k \\times \\log k + m \\times n \\log(m \\times n))$." }, "is_english": true, "time_complexity": "O(k \\times \\log k + m \\times n \\log(m \\times n))", "space_complexity": "O(m \\times n)" }, { "problem_id": 2504, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2505, "explanations": { "1": "We first use an array $cnt$ to count the number of 1s in each bit position. Then, from the lowest bit to the highest bit, if the number of 1s in that bit position is greater than 0, we add the value represented by that bit to the answer. Then, we check if there can be a carry-over, and if so, we add it to the next bit.\n\nThe time complexity is $O(n \\times \\log M)$, where $n$ is the length of the array and $M$ is the maximum value in the array." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": null }, { "problem_id": 2506, "explanations": { "1": "For each string, we can convert it into a binary number of length $26$, where the $i$-th bit being $1$ indicates that the string contains the $i$-th letter.\n\nIf two strings contain the same letters, their binary numbers are the same. Therefore, for each string, we use a hash table to count the occurrences of its binary number. Each time we add the count to the answer, then increment the count of its binary number by $1$.\n\nThe time complexity is $O(L)$, and the space complexity is $O(n)$. Here, $L$ is the total length of all strings, and $n$ is the number of strings." }, "is_english": true, "time_complexity": "O(L)", "space_complexity": "O(n)" }, { "problem_id": 2507, "explanations": { "1": "According to the problem statement, we can perform a process of prime factorization, i.e., continuously decompose a number into its prime factors until it can no longer be decomposed. During the process, add the prime factors each time they are decomposed, and perform this recursively or iteratively.\n\nThe time complexity is $O(\\sqrt{n})$." }, "is_english": true, "time_complexity": "O(\\sqrt{n})", "space_complexity": null }, { "problem_id": 2508, "explanations": { "1": "We first build the graph $g$ using `edges`, and then find all nodes with odd degrees, denoted as $vs$.\n\nIf the length of $vs$ is $0$, it means all nodes in the graph $g$ have even degrees, so we return `true`.\n\nIf the length of $vs$ is $2$, it means there are two nodes with odd degrees in the graph $g$. If we can directly connect these two nodes with an edge, making all nodes in the graph $g$ have even degrees, we return `true`. Otherwise, if we can find a third node $c$ such that we can connect $a$ and $c$, and $b$ and $c$, making all nodes in the graph $g$ have even degrees, we return `true`. Otherwise, we return `false`.\n\nIf the length of $vs$ is $4$, we enumerate all possible pairs and check if any combination meets the conditions. If so, we return `true`; otherwise, we return `false`.\n\nIn other cases, we return `false`.\n\nThe time complexity is $O(n + m)$, and the space complexity is $O(n + m)$. Where $n$ and $m$ are the number of nodes and edges, respectively." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(n + m)" }, { "problem_id": 2509, "explanations": { "1": "For each query, we find the lowest common ancestor of the two nodes $a$ and $b$, and record the number of steps taken upwards. The answer to the query is the number of steps plus one.\n\nTo find the lowest common ancestor, if $a > b$, we move $a$ to its parent node; if $a < b$, we move $b$ to its parent node. We accumulate the number of steps until $a = b$.\n\nThe time complexity is $O(n \\times m)$, where $m$ is the length of the `queries` array." }, "is_english": true, "time_complexity": "O(n \\times m)", "space_complexity": null }, { "problem_id": 2510, "explanations": { "1": "According to the problem description, we know that the number of 0s and 1s on the path from the top-left corner to the bottom-right corner is equal, and the total number is $m + n - 1$, which means the number of 0s and 1s are both $(m + n - 1) / 2$.\n\nTherefore, we can use memoization search, starting from the top-left corner and moving right or down until reaching the bottom-right corner, to check if the number of 0s and 1s on the path is equal.\n\nThe time complexity is $O(m \\times n \\times (m + n))$. Here, $m$ and $n$ are the number of rows and columns of the matrix, respectively." }, "is_english": true, "time_complexity": "O(m \\times n \\times (m + n))", "space_complexity": null }, { "problem_id": 2511, "explanations": { "1": "We use a pointer $i$ to traverse the array $forts$, and a pointer $j$ to start traversing from the next position of $i$ until it encounters the first non-zero position, i.e., $forts[j] \\neq 0$. If $forts[i] + forts[j] = 0$, then we can move the army between $i$ and $j$, destroying $j - i - 1$ enemy forts. We use the variable $ans$ to record the maximum number of enemy forts that can be destroyed.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$. Where $n$ is the length of the array `forts`." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2512, "explanations": { "1": "We can store the positive words in a hash table $ps$ and the negative words in a hash table $ns$.\n\nThen, we traverse the $report$ and for each student, we store their score in an array $arr$, where each element is a tuple $(t, sid)$, where $t$ represents the student's score and $sid$ represents the student's ID.\n\nFinally, we sort the array $arr$ in descending order by score, and if the scores are the same, we sort by ID in ascending order. Then, we take the IDs of the top $k$ students.\n\nThe time complexity is $O(n \\times \\log n + (|ps| + |ns| + n) \\times |s|)$, and the space complexity is $O((|ps|+|ns|) \\times |s| + n)$. Here, $n$ is the number of students, $|ps|$ and $|ns|$ are the number of positive and negative words, respectively, and $|s|$ is the average length of a word." }, "is_english": true, "time_complexity": "O(n \\times \\log n + (|ps| + |ns| + n) \\times |s|)", "space_complexity": "O((|ps|+|ns|) \\times |s| + n)" }, { "problem_id": 2513, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2514, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2515, "explanations": { "1": "遍历数组,找到与 target 相等的单词,计算其与 startIndex 的距离 $t$,则此时的最短距离为 $min(t, n - t)$,我们只需要不断更新最小值即可。\n\n时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组的长度。", "2": "" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2516, "explanations": { "1": "First, we use a hash table or an array of length $3$, denoted as $cnt$, to count the number of each character in string $s$. If any character appears less than $k$ times, it cannot be obtained, so we return $-1$ in advance.\n\nThe problem asks us to remove characters from the left and right sides of the string, so that the number of each remaining character is not less than $k$. We can consider the problem in reverse: remove a substring of certain size in the middle, so that in the remaining string on both sides, the number of each character is not less than $k$.\n\nTherefore, we maintain a sliding window, with pointers $j$ and $i$ representing the left and right boundaries of the window, respectively. The string within the window is what we want to remove. Each time we move the right boundary $i$, we add the corresponding character $s[i]$ to the window (i.e., remove one character $s[i]$). If the count of $cnt[s[i]]$ is less than $k$, then we move the left boundary $j$ in a loop until the count of $cnt[s[i]]$ is not less than $k$. The size of the window at this time is $i - j + 1$, and we update the maximum window size.\n\nThe final answer is the length of string $s$ minus the size of the maximum window.\n\nThe time complexity is $O(n)$, where $n$ is the length of string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2517, "explanations": { "1": "我们注意到,如果一个甜蜜度为 $x$ 的礼盒是可行的,那么甜蜜度小于 $x$ 的礼盒也是可行的,这存在着单调性,因此我们可以使用二分查找的方法,找到最大的可行甜蜜度。\n\n我们首先将数组 $price$ 排序,然后定义二分查找的左边界 $l=0$, $r=price[n-1]-price[0]$。每一次,我们计算出当前的中间值 $mid = \\lfloor \\frac{l+r+1}{2} \\rfloor$,以 $mid$ 作为甜蜜度,判断是否可行。若可行,那么我们将左边界 $l$ 更新为 $mid$,否则将右边界 $r$ 更新为 $mid-1$。最后返回 $l$ 即可。\n\n那么问题的关键转化为:判断一个甜蜜度是否可行,我们通过函数 $check(x)$ 来实现。函数 $check(x)$ 的执行逻辑如下:\n\n定义一个变量 $cnt$ 表示当前已经选取的糖果的数量,初始值为 $0$,定义一个变量 $pre$ 表示上一个选取的糖果的价格,初始值为 $-x$。然后我们遍历排好序的数组 $price$,对于每一个糖果的价格 $cur$,如果 $cur-pre \\geq x$,那么我们就选取这个糖果,将 $pre$ 更新为 $cur$,并将 $cnt$ 加一。最后判断 $cnt$ 是否大于等于 $k$,如果是,那么返回 $true$,否则返回 $false$。\n\n时间复杂度 $O(n \\times (\\log n + \\log M))$,空间复杂度 $O(\\log n)$。其中 $n$ 是数组 $price$ 的长度;而 $M$ 是数组 $price$ 中的最大值,本题中 $M \\leq 10^9$。" }, "is_english": false, "time_complexity": "O(n \\times (\\log n + \\log M))", "space_complexity": "O(\\log n)" }, { "problem_id": 2518, "explanations": { "1": "对于一个长度为 $n$ 的数组 `nums`,每个元素都可以选择放入第一个分区或第二个分区,因此一共有 $2^n$ 种分区方式。每一种分区方式,得到的结果可以是“好分区”或者“坏分区”,题目要我们求“好分区”的个数,我们可以转换为求“坏分区”的个数。那么“好分区”的个数就是 $2^n$ 减去“坏分区”的个数。\n\n“坏分区”实际上就是从数组 `nums` 中选出若干个元素,使得这若干个元素之和不超过 $k$。这可以通过动态规划(0-1 背包问题)来求解。\n\n我们用 $f[i][j]$ 表示从数组 `nums` 的前 $i$ 个元素中选出若干个元素,使得这若干个元素之和为 $j$ 的方案数。那么 $f[i][j]$ 的状态转移方程为:\n\n$$\nf[i][j] = \\left\\{\n\\begin{aligned}\n&f[i - 1][j] & \\textit{如果不选第 } i \\textit{ 个元素} \\\\\n&f[i - 1][j - nums[i - 1]] & \\textit{如果选第 } i \\textit{ 个元素}\n\\end{aligned}\n\\right.\n$$\n\n那么“坏分区”的个数就是 $\\sum_{j=0}^{k-1} f[n][j] \\times 2$,其中 $n$ 为数组 `nums` 的长度。最后,我们用 $2^n$ 减去“坏分区”的个数,即可得到“好分区”的个数。\n\n时间复杂度 $O(n \\times k)$,空间复杂度 $O(n \\times k)$。其中 $n$ 为数组 `nums` 的长度,而 $k$ 为整数 $k$。" }, "is_english": false, "time_complexity": "O(n \\times k)", "space_complexity": "O(n \\times k)" }, { "problem_id": 2519, "explanations": { "1": "We maintain two binary indexed trees, one records the number of elements smaller than the current position on the left, and the other records the number of elements smaller than the current position on the right.\n\nWe traverse the array, and for the current position, if the number of elements smaller than the current position on the left is greater than or equal to $k$, and the number of elements smaller than the current position on the right is greater than or equal to $k$, then the current position is a `k-big`, and we increment the answer by one.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2520, "explanations": { "1": "We directly enumerate each digit $val$ of the integer $num$, and if $val$ can divide $num$, we add one to the answer.\n\nAfter the enumeration, we return the answer.\n\nThe time complexity is $O(\\log num)$, and the space complexity is $O(1)$.", "2": "" }, "is_english": true, "time_complexity": "O(\\log num)", "space_complexity": "O(1)" }, { "problem_id": 2521, "explanations": { "1": "For each element in the array, first perform prime factorization on it, and then add the decomposed prime factors to the hash table. Finally, return the size of the hash table.\n\nThe time complexity is $O(n \\times \\sqrt{m})$, and the space complexity is $O(\\frac{m}{\\log m})$. Where $n$ and $m$ are the length of the array and the maximum value in the array, respectively." }, "is_english": true, "time_complexity": "O(n \\times \\sqrt{m})", "space_complexity": "O(\\frac{m}{\\log m})" }, { "problem_id": 2522, "explanations": { "1": "We design a function $dfs(i)$ to represent the minimum number of partitions starting from index $i$ of string $s$. The answer is $dfs(0)$.\n\nThe calculation process of the function $dfs(i)$ is as follows:\n\n- If $i \\geq n$, it means that it has reached the end of the string, return $0$.\n- Otherwise, we enumerate all substrings starting from $i$. If the value of the substring is less than or equal to $k$, then we can take the substring as a partition. Then we can get $dfs(j + 1)$, where $j$ is the end index of the substring. We take the minimum value among all possible partitions, add $1$, and that is the value of $dfs(i)$.\n\nFinally, if $dfs(0) = \\infty$, it means there is no good partition, return $-1$. Otherwise, return $dfs(0)$.\n\nTo avoid repeated calculations, we can use memoization search.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2523, "explanations": { "1": "For the given range $[\\textit{left}, \\textit{right}]$, we can use the linear sieve method to find all prime numbers. Then, we traverse the prime numbers in ascending order to find the pair of adjacent prime numbers with the smallest difference, which will be the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n = \\textit{right}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2524, "explanations": { "1": "We use a hash table $\\textit{cnt}$ to maintain the elements of the window of size $k$ and their frequencies.\n\nFirst, calculate the score of all elements in the initial window of size $k$. Then, use a sliding window to add one element at a time and remove the leftmost element, while updating the score using fast power.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2525, "explanations": { "1": "We can simulate according to the problem description.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$.", "2": "" }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 2526, "explanations": { "1": "We can maintain a counter $\\textit{cnt}$ to record the current number of consecutive integers equal to $\\textit{value}$.\n\nWhen calling the `consec` method, if $\\textit{num}$ is equal to $\\textit{value}$, we increment $\\textit{cnt}$ by 1; otherwise, we reset $\\textit{cnt}$ to 0. Then we check whether $\\textit{cnt}$ is greater than or equal to $\\textit{k}$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 2527, "explanations": { "1": "We first consider the case where $i$ and $j$ are not equal. In this case, `((nums[i] | nums[j]) & nums[k])` and `((nums[j] | nums[i]) & nums[k])` produce the same result, and their XOR result is $0$.\n\nTherefore, we only need to consider the case where $i$ and $j$ are equal. In this case, `((nums[i] | nums[j]) & nums[k]) = (nums[i] & nums[k])`. If $i \\neq k$, then this is the same as the result of `nums[k] & nums[i]`, and the XOR result of these values is $0$.\n\nTherefore, we ultimately only need to consider the case where $i = j = k$, and the answer is the XOR result of all $nums[i]$.\n\nThe time complexity is $O(n)$ and the space complexity is $O(1)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2528, "explanations": { "1": "According to the problem description, the minimum number of power stations increases as the value of $k$ increases. Therefore, we can use binary search to find the largest minimum number of power stations, ensuring that the additional power stations needed do not exceed $k$.\n\nFirst, we use a difference array and prefix sum to calculate the initial number of power stations in each city, recording it in the array $s$, where $s[i]$ represents the number of power stations in the $i$-th city.\n\nNext, we define the left boundary of the binary search as $0$ and the right boundary as $2^{40}$. Then, we implement a function $check(x, k)$ to determine whether the minimum number of power stations in the cities can be $x$, ensuring that the additional power stations needed do not exceed $k$.\n\nThe implementation logic of the function $check(x, k)$ is as follows:\n\nTraverse each city. If the number of power stations in the current city $i$ is less than $x$, we can greedily build a power station at the rightmost possible position, $j = \\min(i + r, n - 1)$, to cover as many cities as possible. During this process, we can use the difference array to add a certain value to a continuous segment. If the number of additional power stations needed exceeds $k$, then $x$ does not meet the condition, and we return `false`. Otherwise, after the traversal, return `true`.\n\nThe time complexity is $O(n \\times \\log M)$, and the space complexity is $O(n)$. Here, $n$ is the number of cities, and $M$ is fixed at $2^{40}$." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(n)" }, { "problem_id": 2529, "explanations": { "1": "We can directly traverse the array, count the number of positive and negative integers $a$ and $b$, and return the larger of $a$ and $b$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$.", "2": "Since the array is sorted in non-decreasing order, we can use binary search to find the index $i$ of the first element that is greater than or equal to $1$, and the index $j$ of the first element that is greater than or equal to $0$. The number of positive integers is $a = n - i$, and the number of negative integers is $b = j$. We return the larger of $a$ and $b$.\n\nThe time complexity is $O(\\log n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2530, "explanations": { "1": "To maximize the sum of scores, we need to select the element with the maximum value at each step. Therefore, we can use a priority queue (max heap) to maintain the element with the maximum value.\n\nAt each step, we take out the element with the maximum value $v$ from the priority queue, add $v$ to the answer, and replace $v$ with $\\lceil \\frac{v}{3} \\rceil$, and then add it to the priority queue. After repeating this process $k$ times, we return the answer.\n\nThe time complexity is $O(n + k \\times \\log n)$, and the space complexity is $O(n)$ or $O(1)$. Here, $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n + k \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2531, "explanations": { "1": "We first use two arrays $\\textit{cnt1}$ and $\\textit{cnt2}$ of length $26$ to record the frequency of each character in the strings $\\textit{word1}$ and $\\textit{word2}$, respectively.\n\nThen, we count the number of distinct characters in $\\textit{word1}$ and $\\textit{word2}$, denoted as $x$ and $y$ respectively.\n\nNext, we enumerate each character $c1$ in $\\textit{word1}$ and each character $c2$ in $\\textit{word2}$. If $c1 = c2$, we only need to check if $x$ and $y$ are equal; otherwise, we need to check if $x - (\\textit{cnt1}[c1] = 1) + (\\textit{cnt1}[c2] = 0)$ and $y - (\\textit{cnt2}[c2] = 1) + (\\textit{cnt2}[c1] = 0)$ are equal. If they are equal, then we have found a solution and return $\\text{true}$.\n\nIf we have enumerated all characters and have not found a suitable solution, we return $\\text{false}$.\n\nThe time complexity is $O(m + n + |\\Sigma|^2)$, where $m$ and $n$ are the lengths of the strings $\\textit{word1}$ and $\\textit{word2}$, and $\\Sigma$ is the character set. In this problem, the character set consists of lowercase letters, so $|\\Sigma| = 26$." }, "is_english": true, "time_complexity": "O(m + n + |\\Sigma|^2)", "space_complexity": null }, { "problem_id": 2532, "explanations": { "1": "First, we sort the workers by efficiency in descending order, so the worker with the highest index has the lowest efficiency.\n\nNext, we use four priority queues to simulate the state of the workers:\n\n- `wait_in_left`: Max-heap, storing the indices of workers currently waiting on the left bank;\n- `wait_in_right`: Max-heap, storing the indices of workers currently waiting on the right bank;\n- `work_in_left`: Min-heap, storing the time when workers currently working on the left bank finish placing boxes and the indices of the workers;\n- `work_in_right`: Min-heap, storing the time when workers currently working on the right bank finish picking up boxes and the indices of the workers.\n\nInitially, all workers are on the left bank, so `wait_in_left` stores the indices of all workers. We use the variable `cur` to record the current time.\n\nThen, we simulate the entire process. First, we check if any worker in `work_in_left` has finished placing boxes at the current time. If so, we move the worker to `wait_in_left` and remove the worker from `work_in_left`. Similarly, we check if any worker in `work_in_right` has finished picking up boxes. If so, we move the worker to `wait_in_right` and remove the worker from `work_in_right`.\n\nNext, we check if there are any workers waiting on the left bank at the current time, denoted as `left_to_go`. At the same time, we check if there are any workers waiting on the right bank, denoted as `right_to_go`. If there are no workers waiting to cross the river, we directly update `cur` to the next time when a worker finishes placing boxes and continue the simulation.\n\nIf `right_to_go` is `true`, we take a worker from `wait_in_right`, update `cur` to the current time plus the time it takes for the worker to cross from the right bank to the left bank. If all workers have crossed to the right bank at this point, we directly return `cur` as the answer; otherwise, we move the worker to `work_in_left`.\n\nIf `left_to_go` is `true`, we take a worker from `wait_in_left`, update `cur` to the current time plus the time it takes for the worker to cross from the left bank to the right bank, then move the worker to `work_in_right` and decrement the number of boxes.\n\nRepeat the above process until the number of boxes is zero. At this point, `cur` is the answer.\n\nThe time complexity is $O(n \\times \\log k)$, and the space complexity is $O(k)$. Here, $n$ and $k$ are the number of workers and the number of boxes, respectively." }, "is_english": true, "time_complexity": "O(n \\times \\log k)", "space_complexity": "O(k)" }, { "problem_id": 2533, "explanations": { "1": "We define $f[i]$ as the number of strings of length $i$ that meet the condition. The state transition equation is:\n\n$$\nf[i] = \\begin{cases}\n1 & i = 0 \\\\\nf[i - oneGroup] + f[i - zeroGroup] & i \\geq 1\n\\end{cases}\n$$\n\nThe final answer is $f[minLength] + f[minLength + 1] + \\cdots + f[maxLength]$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n=maxLength$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2534, "explanations": { "1": "We define two queues, where $q[0]$ stores the indices of people who want to enter, and $q[1]$ stores the indices of people who want to exit.\n\nWe maintain a variable $t$ to represent the current time, and a variable $st$ to represent the current state of the door. When $st = 1$, it means the door is not in use or someone exited in the previous second. When $st = 0$, it means someone entered in the previous second. Initially, $t = 0$ and $st = 1$.\n\nWe traverse the array $\\textit{arrival}$. For each person, if the current time $t$ is less than or equal to the time the person arrives at the door $\\textit{arrival}[i]$, we add the person's index to the corresponding queue $q[\\text{state}[i]]$.\n\nThen we check if both queues $q[0]$ and $q[1]$ are not empty. If both are not empty, we dequeue the front element from the queue $q[st]$ and assign the current time $t$ to the person's passing time. If only one queue is not empty, we update the value of $st$ based on which queue is not empty, then dequeue the front element from that queue and assign the current time $t$ to the person's passing time. If both queues are empty, we update the value of $st$ to $1$, indicating the door is not in use.\n\nNext, we increment the time $t$ by $1$ and continue traversing the array $\\textit{arrival}$ until all people have passed through the door.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ represents the length of the array $\\textit{arrival}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2535, "explanations": { "1": "We traverse the array $\\textit{nums}$, calculate the sum of the elements $x$ and the sum of the digits $y$, and finally return $|x - y|$. Since $x$ is always greater than or equal to $y$, we can directly return $x - y$.\n\nThe time complexity is $O(n \\times \\log_{10} M)$, where $n$ and $M$ are the length of the array $\\textit{nums}$ and the maximum value of the elements in the array, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\log_{10} M)", "space_complexity": "O(1)" }, { "problem_id": 2536, "explanations": { "1": "A 2D difference array is a technique used to efficiently handle range updates on 2D arrays. We can implement fast updates on submatrices by maintaining a difference matrix of the same size as the original matrix.\n\nSuppose we have a 2D difference matrix $\\textit{diff}$, initially with all elements set to $0$. For each query $[\\textit{row1}, \\textit{col1}, \\textit{row2}, \\textit{col2}]$, we can update the difference matrix through the following steps:\n\n1. Increment position $(\\textit{row1}, \\textit{col1})$ by $1$.\n2. Decrement position $(\\textit{row2} + 1, \\textit{col1})$ by $1$, provided that $\\textit{row2} + 1 < n$.\n3. Decrement position $(\\textit{row1}, \\textit{col2} + 1)$ by $1$, provided that $\\textit{col2} + 1 < n$.\n4. Increment position $(\\textit{row2} + 1, \\textit{col2} + 1)$ by $1$, provided that $\\textit{row2} + 1 < n$ and $\\textit{col2} + 1 < n$.\n\nAfter completing all queries, we need to convert the difference matrix back to the original matrix using prefix sums. That is, for each position $(i, j)$, we calculate:\n\n$$\n\\textit{mat}[i][j] = \\textit{diff}[i][j] + (\\textit{mat}[i-1][j] \\text{ if } i > 0 \\text{ else } 0) + (\\textit{mat}[i][j-1] \\text{ if } j > 0 \\text{ else } 0) - (\\textit{mat}[i-1][j-1] \\text{ if } i > 0 \\text{ and } j > 0 \\text{ else } 0)\n$$\n\nThe time complexity is $O(m + n^2)$, where $m$ and $n$ are the length of $\\textit{queries}$ and the given $n$, respectively. Ignoring the space consumed by the answer, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m + n^2)", "space_complexity": "O(1)" }, { "problem_id": 2537, "explanations": { "1": "If a subarray contains $k$ pairs of identical elements, then this subarray must contain at least $k$ pairs of identical elements.\n\nWe use a hash table $\\textit{cnt}$ to count the occurrences of elements within the sliding window, a variable $\\textit{cur}$ to count the number of identical pairs within the window, and a pointer $i$ to maintain the left boundary of the window.\n\nAs we iterate through the array $\\textit{nums}$, we treat the current element $x$ as the right boundary of the window. The number of identical pairs in the window increases by $\\textit{cnt}[x]$, and we increment the count of $x$ by 1, i.e., $\\textit{cnt}[x] \\leftarrow \\textit{cnt}[x] + 1$. Next, we repeatedly check if the number of identical pairs in the window is greater than or equal to $k$ after removing the leftmost element. If it is, we decrement the count of the leftmost element, i.e., $\\textit{cnt}[\\textit{nums}[i]] \\leftarrow \\textit{cnt}[\\textit{nums}[i]] - 1$, reduce the number of identical pairs in the window by $\\textit{cnt}[\\textit{nums}[i]]$, i.e., $\\textit{cur} \\leftarrow \\textit{cur} - \\textit{cnt}[\\textit{nums}[i]]$, and move the left boundary to the right, i.e., $i \\leftarrow i + 1$. At this point, all elements to the left of and including the left boundary can serve as the left boundary for the current right boundary, so we add $i + 1$ to the answer.\n\nFinally, we return the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2538, "explanations": { "1": "由于每个节点价值均为正整数,因此,以节点 $root$ 作为根节点的最小的一条路径就是 $root$ 节点本身,那么价值和最大的一条路径与最小的一条路径的差值就等价于去掉路径的一个端点。\n\n我们设计一个函数 $dfs(i, fa)$,表示以节点 $i$ 为根节点的子树中,不去掉端点的最大路径和以及去掉端点的最大路径和。其中,$fa$ 表示节点 $i$ 的父节点。\n\n函数 $dfs(i, fa)$ 的实现逻辑如下:\n\n初始化 $a = price[i]$, $b = 0$,表示初始只有一个节点,不去掉端点的最大路径和为 $price[i]$,去掉端点的最大路径和为 $0$。\n\n对于节点 $i$ 的每个子节点 $j$,如果 $j \\ne fa$,则递归调用函数 $dfs(j, i)$,这里返回了以节点 $j$ 为根节点的子树中,不去掉端点的最大路径和以及去掉端点的最大路径和,记为 $c$ 和 $d$。此时答案有两种情况:\n\n- 前面不去掉端点的最大路径和加上当前节点去掉端点的最大路径和,即 $a + d$;\n- 前面去掉端点的最大路径和加上当前节点不去掉端点的最大路径和,即 $b + c$。\n\n我们更新答案的最大值,即 $ans = \\max(ans, a + d, b + c)$。\n\n然后更新 $a$ 和 $b$,即 $a = \\max(a, price[i] + c)$, $b = \\max(b, price[i] + d)$,最后返回。\n\n时间复杂度为 $O(n)$,空间复杂度为 $O(n)$。其中 $n$ 为节点个数。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2539, "explanations": { "1": "由于题目说的是子序列中字母出现的次数,因此,我们可以先用一个数组 $cnt$ 统计字符串 $s$ 中每个字母出现的次数,记最大的次数为 $mx$。\n\n接下来,我们在 $[1,2..mx]$ 范围内枚举子序列中字母出现的次数 $i$,然后枚举所有出现过的字母,如果该字母 $c$ 的出现次数 $cnt[c]$ 大于等于 $i$,那么我们可以从这 $cnt[c]$ 个相同字母中选择其中 $i$ 个,也可以一个都不选,那么当前字母的可选方案数就是 $comb(cnt[c], i) + 1$,将所有可选方案数相乘,可以得到当前次数的所有子序列次数,将次数减去 $1$ 累加到答案中。\n\n那么问题的关键在于如何快速求出 $comb(n, k)$,我们可以用逆元来求解,具体实现见代码。\n\n时间复杂度 $O(n \\times C)$,空间复杂度 $O(n)$。其中 $n$ 为字符串 $s$ 的长度,而 $C$ 是字符集的大小,本题中 $C = 26$。" }, "is_english": false, "time_complexity": "O(n \\times C)", "space_complexity": "O(n)" }, { "problem_id": 2540, "explanations": { "1": "Traverse the two arrays. If the elements pointed to by the two pointers are equal, return that element. If the elements pointed to by the two pointers are not equal, move the pointer pointing to the smaller element to the right by one bit until an equal element is found or the array is traversed.\n\nThe time complexity is $O(m + n)$, where $m$ and $n$ are the lengths of the two arrays respectively. The space complexity is $O(1)$.", "2": "" }, "is_english": true, "time_complexity": "O(m + n)", "space_complexity": "O(1)" }, { "problem_id": 2541, "explanations": { "1": "We use a variable $x$ to record the difference in the number of additions and subtractions, and a variable $ans$ to record the number of operations.\n\nWe traverse the array, and for each position $i$, if $k=0$ and $a_i \\neq b_i$, then it is impossible to make the two arrays equal, so we return $-1$. Otherwise, if $k \\neq 0$, then $a_i - b_i$ must be a multiple of $k$, otherwise it is impossible to make the two arrays equal, so we return $-1$. Next, we update $x$ and $ans$.\n\nFinally, if $x \\neq 0$, then it is impossible to make the two arrays equal, so we return $-1$. Otherwise, we return $\\frac{ans}{2}$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2542, "explanations": { "1": "Sort nums2 and nums1 in descending order according to nums2, then traverse from front to back, maintaining a min heap. The heap stores elements from nums1, and the number of elements in the heap does not exceed $k$. At the same time, maintain a variable $s$ representing the sum of the elements in the heap, and continuously update the answer during the traversal process.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array nums1." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2543, "explanations": { "1": "We notice that the first two types of moves do not change the greatest common divisor (gcd) of the horizontal and vertical coordinates, while the last two types of moves can multiply the gcd of the horizontal and vertical coordinates by a power of $2$. In other words, the final gcd of the horizontal and vertical coordinates must be a power of $2$. If the gcd is not a power of $2$, then it is impossible to reach.\n\nNext, we prove that any $(x, y)$ that satisfies $gcd(x, y)=2^k$ can be reached.\n\nWe reverse the direction of movement, that is, move from the end point back. Then $(x, y)$ can move to $(x, x+y)$, $(x+y, y)$, $(\\frac{x}{2}, y)$, and $(x, \\frac{y}{2})$.\n\nAs long as $x$ or $y$ is even, we divide it by $2$ until both $x$ and $y$ are odd. At this point, if $x \\neq y$, without loss of generality, let $x \\gt y$, then $\\frac{x+y}{2} \\lt x$. Since $x+y$ is even, we can move from $(x, y)$ to $(x+y, y)$, and then to $(\\frac{x+y}{2}, y)$ through operations. That is to say, we can always make $x$ and $y$ continuously decrease. When the loop ends, if $x=y=1$, it means it can be reached.\n\nThe time complexity is $O(\\log(\\min(targetX, targetY)))$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log(\\min(targetX, targetY)))", "space_complexity": "O(1)" }, { "problem_id": 2544, "explanations": { "1": "We can directly simulate the process as described in the problem.\n\nWe define an initial symbol $sign=1$. Starting from the most significant digit, we take out one digit $x$ each time, multiply it by $sign$, add the result to the answer, then negate $sign$, and continue to process the next digit until all digits are processed.\n\nThe time complexity is $O(\\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the given number.", "2": "" }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 2545, "explanations": { "1": "We directly sort $\\textit{score}$ in descending order based on the scores in the $k$-th column, and then return the result.\n\nThe time complexity is $O(m \\times \\log m)$, and the space complexity is $O(\\log m)$. Here, $m$ is the number of rows in $\\textit{score}$." }, "is_english": true, "time_complexity": "O(m \\times \\log m)", "space_complexity": "O(\\log m)" }, { "problem_id": 2546, "explanations": { "1": "We notice that $1$ is actually a \"tool\" for number conversion. Therefore, as long as both strings either have $1$ or neither have $1$, we can make the two strings equal through operations.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2547, "explanations": { "1": "We design a function $dfs(i)$, which represents the minimum cost of splitting from index $i$. So the answer is $dfs(0)$.\n\nThe calculation process of the function $dfs(i)$ is as follows:\n\nIf $i \\ge n$, it means that the splitting has reached the end of the array, and $0$ is returned at this time.\nOtherwise, we enumerate the end $j$ of the subarray. During the process, we use an array or hash table cnt to count the number of times each number appears in the subarray, and use a variable one to count the number of numbers in the subarray that appear once. So the importance of the subarray is $k + j - i + 1 - one$, and the cost of splitting is $k + j - i + 1 - one + dfs(j + 1)$. We enumerate all $j$ and take the minimum value as the return value of $dfs(i)$.\nDuring the process, we can use memoization search, that is, use an array $f$ to memorize the return value of the function $dfs(i)$ to avoid repeated calculations.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 2548, "explanations": { "1": "We sort the items in descending order by unit price, and then take out the items one by one until the backpack is full.\n\nIf the backpack is not full in the end, return $-1$, otherwise return the total price.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$, where $n$ is the number of items." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 2549, "explanations": { "1": "Since every operation on the number $n$ on the desktop will also cause the number $n-1$ to appear on the desktop, the final numbers on the desktop are $[2,...n]$, that is, $n-1$ numbers.\n\nNote that $n$ could be $1$, so it needs to be specially judged.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 2550, "explanations": { "1": "According to the problem description, each monkey has two ways of moving, either clockwise or counterclockwise. Therefore, there are a total of $2^n$ ways to move. The non-collision ways of moving are only two, that is, all monkeys move clockwise or all monkeys move counterclockwise. Therefore, the number of collision ways of moving is $2^n - 2$.\n\nWe can use fast power to calculate the value of $2^n$, then use $2^n - 2$ to calculate the number of collision ways of moving, and finally take the remainder of $10^9 + 7$.\n\nThe time complexity is $O(\\log n)$, where $n$ is the number of monkeys. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 2551, "explanations": { "1": "We can transform the problem into: dividing the array `weights` into $k$ consecutive subarrays, that is, we need to find $k-1$ splitting points, each splitting point's cost is the sum of the elements on the left and right of the splitting point. The difference between the sum of the costs of the largest $k-1$ splitting points and the smallest $k-1$ splitting points is the answer.\n\nTherefore, we can process the array `weights` and transform it into an array `arr` of length $n-1$, where `arr[i] = weights[i] + weights[i+1]`. Then we sort the array `arr`, and finally calculate the difference between the sum of the costs of the largest $k-1$ splitting points and the smallest $k-1$ splitting points.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array `weights`." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2552, "explanations": { "1": "We can enumerate $j$ and $k$ in the quadruplet, then the problem is transformed into, for the current $j$ and $k$:\n\n- Count how many $l$ satisfy $l > k$ and $nums[l] > nums[j]$;\n- Count how many $i$ satisfy $i < j$ and $nums[i] < nums[k]$.\n\nWe can use two two-dimensional arrays $f$ and $g$ to record these two pieces of information. Where $f[j][k]$ represents how many $l$ satisfy $l > k$ and $nums[l] > nums[j]$, and $g[j][k]$ represents how many $i$ satisfy $i < j$ and $nums[i] < nums[k]$.\n\nTherefore, the answer is the sum of all $f[j][k] \\times g[j][k]$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 2553, "explanations": { "1": "Split each number in the array into digits, then put the split numbers into the answer array in order.\n\nThe time complexity is $O(n \\times \\log_{10} M)$, and the space complexity is $O(n \\times \\log_{10} M)$. Where $n$ is the length of the array $nums$, and $M$ is the maximum value in the array $nums$.", "2": "" }, "is_english": true, "time_complexity": "O(n \\times \\log_{10} M)", "space_complexity": "O(n \\times \\log_{10} M)" }, { "problem_id": 2554, "explanations": { "1": "We use the variable $s$ to represent the sum of the currently selected integers, and the variable $ans$ to represent the number of currently selected integers. We convert the array `banned` into a hash table for easy determination of whether a certain integer is not selectable.\n\nNext, we start enumerating the integer $i$ from $1$. If $s + i \\leq maxSum$ and $i$ is not in `banned`, then we can select the integer $i$, and add $i$ and $1$ to $s$ and $ans$ respectively.\n\nFinally, we return $ans$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the given integer.", "2": "If $n$ is very large, the enumeration in Method One will time out.\n\nWe can add $0$ and $n + 1$ to the array `banned`, deduplicate the array `banned`, remove elements greater than $n+1$, and then sort it.\n\nNext, we enumerate every two adjacent elements $i$ and $j$ in the array `banned`. The range of selectable integers is $[i + 1, j - 1]$. We use binary search to enumerate the number of elements we can select in this range, find the maximum number of selectable elements, and then add it to $ans$. At the same time, we subtract the sum of these elements from `maxSum`. If `maxSum` is less than $0$, we break the loop. Return the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array `banned`.\n\nSimilar problems:\n\n- [2557. Maximum Number of Integers to Choose From a Range II](https://github.com/doocs/leetcode/blob/main/solution/2500-2599/2557.Maximum%20Number%20of%20Integers%20to%20Choose%20From%20a%20Range%20II/README.md)" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2555, "explanations": { "1": "We define $f[i]$ as the maximum number of prizes that can be obtained by selecting a segment of length $k$ from the first $i$ prizes. Initially, $f[0] = 0$. We define the answer variable as $ans = 0$.\n\nNext, we enumerate the position $x$ of each prize, and use binary search to find the leftmost prize index $j$ such that $prizePositions[j] \\geq x - k$. At this point, we update the answer $ans = \\max(ans, f[j] + i - j)$, and update $f[i] = \\max(f[i - 1], i - j)$.\n\nFinally, we return $ans$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the number of prizes." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2556, "explanations": { "1": "First, we perform a DFS traversal to determine whether there is a path from $(0, 0)$ to $(m - 1, n - 1)$, and we denote the result as $a$. During the DFS process, we set the value of the visited cells to $0$ to prevent revisiting.\n\nNext, we set the values of $(0, 0)$ and $(m - 1, n - 1)$ to $1$, and perform another DFS traversal to determine whether there is a path from $(0, 0)$ to $(m - 1, n - 1)$, and we denote the result as $b$. During the DFS process, we set the value of the visited cells to $0$ to avoid revisiting.\n\nFinally, if both $a$ and $b$ are `true`, we return `false`, otherwise, we return `true`.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Where $m$ and $n$ are the number of rows and columns of the matrix, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 2557, "explanations": { "1": "We can add $0$ and $n + 1$ to the array `banned`, then deduplicate and sort the array `banned`.\n\nNext, we enumerate every two adjacent elements $i$ and $j$ in the array `banned`. The range of selectable integers is $[i + 1, j - 1]$. We use binary search to enumerate the number of elements we can select in this range, find the maximum number of selectable elements, and then add it to $ans$. At the same time, we subtract the sum of these elements from `maxSum`. If `maxSum` is less than $0$, we break the loop. Return the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array `banned`." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2558, "explanations": { "1": "We can store the array $gifts$ in a max heap, and then loop $k$ times, each time taking out the top element of the heap, taking the square root of it, and putting the result back into the heap.\n\nFinally, we add up all the elements in the heap as the answer.\n\nThe time complexity is $O(n + k \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $gifts$." }, "is_english": true, "time_complexity": "O(n + k \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2559, "explanations": { "1": "We can preprocess all the indices of the strings that start and end with a vowel, and record them in order in the array $nums$.\n\nNext, we iterate through each query $(l, r)$, and use binary search to find the first index $i$ in $nums$ that is greater than or equal to $l$, and the first index $j$ that is greater than $r$. Therefore, the answer to the current query is $j - i$.\n\nThe time complexity is $O(n + m \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ and $m$ are the lengths of the arrays $words$ and $queries$, respectively.", "2": "We can create a prefix sum array $s$ of length $n+1$, where $s[i]$ represents the number of strings that start and end with a vowel in the first $i$ strings of the array $words$. Initially, $s[0] = 0$.\n\nNext, we iterate through the array $words$. If the current string starts and ends with a vowel, then $s[i+1] = s[i] + 1$, otherwise $s[i+1] = s[i]$.\n\nFinally, we iterate through each query $(l, r)$. Therefore, the answer to the current query is $s[r+1] - s[l]$.\n\nThe time complexity is $O(n + m)$, and the space complexity is $O(n)$. Where $n$ and $m$ are the lengths of the arrays $words$ and $queries$, respectively." }, "is_english": true, "time_complexity": "O(n + m \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2560, "explanations": { "1": "The problem is asking for the minimum stealing ability of the thief. We can use binary search to enumerate the stealing ability of the thief. For the enumerated ability $x$, we can use a greedy approach to determine whether the thief can steal at least $k$ houses. Specifically, we traverse the array from left to right. For the current house $i$ we are traversing, if $nums[i] \\leq x$ and the difference between the index of $i$ and the last stolen house is greater than $1$, then the thief can steal house $i$. Otherwise, the thief cannot steal house $i$. We accumulate the number of stolen houses. If the number of stolen houses is greater than or equal to $k$, it means that the thief can steal at least $k$ houses, and at this time, the stealing ability $x$ of the thief might be the minimum. Otherwise, the stealing ability $x$ of the thief is not the minimum.\n\nThe time complexity is $O(n \\times \\log m)$, and the space complexity is $O(1)$. Where $n$ and $m$ are the length of the array $nums$ and the maximum value in the array $nums$, respectively." }, "is_english": true, "time_complexity": "O(n \\times \\log m)", "space_complexity": "O(1)" }, { "problem_id": 2561, "explanations": { "1": "First, we can remove the common elements from both arrays. For the remaining numbers, the occurrence of each number must be even, otherwise, it is impossible to construct identical arrays. Let's denote the arrays after removing common elements as $a$ and $b$.\n\nNext, we consider how to perform the swaps.\n\nIf we want to swap the smallest number in $a$, we need to find the largest number in $b$ to swap with it; similarly, if we want to swap the smallest number in $b$, we need to find the largest number in $a$ to swap with it. This can be achieved by sorting.\n\nHowever, there is another swapping scheme. We can use a smallest number $mi$ as a transition element, first swap the number in $a$ with $mi$, and then swap $mi$ with the number in $b$. In this way, the cost of swapping is $2 \\times mi$.\n\nIn the code implementation, we can directly merge arrays $a$ and $b$ into an array $nums$, and then sort the array $nums$. Next, we enumerate the first half of the numbers, calculate the minimum cost each time, and add it to the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2562, "explanations": { "1": "Starting from both ends of the array, we take out one element at a time, concatenate it with another element, and then add the concatenated result to the answer. We repeat this process until the array is empty.\n\nThe time complexity is $O(n \\times \\log M)$, and the space complexity is $O(\\log M)$. Here, $n$ and $M$ are the length of the array and the maximum value in the array, respectively.", "2": "" }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(\\log M)" }, { "problem_id": 2563, "explanations": { "1": "First, we sort the array `nums` in ascending order. Then, for each `nums[i]`, we use binary search to find the lower bound `j` of `nums[j]`, i.e., the first index that satisfies `nums[j] >= lower - nums[i]`. Then, we use binary search again to find the lower bound `k` of `nums[k]`, i.e., the first index that satisfies `nums[k] >= upper - nums[i] + 1`. Therefore, `[j, k)` is the index range for `nums[j]` that satisfies `lower <= nums[i] + nums[j] <= upper`. The count of these indices corresponding to `nums[j]` is `k - j`, and we can add this to the answer. Note that $j > i$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Where $n$ is the length of the array `nums`." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 2564, "explanations": { "1": "We can first preprocess all substrings of length $1$ to $32$ into their corresponding decimal values, find the minimum index and the corresponding right endpoint index for each value, and store them in the hash table $d$.\n\nThen we enumerate each query. For each query $[first, second]$, we only need to check in the hash table $d$ whether there exists a key-value pair with the key as $first \\oplus second$. If it exists, add the corresponding minimum index and right endpoint index to the answer array. Otherwise, add $[-1, -1]$.\n\nThe time complexity is $O(n \\times \\log M + m)$, and the space complexity is $O(n \\times \\log M)$. Where $n$ and $m$ are the lengths of the string $s$ and the query array $queries$ respectively, and $M$ can take the maximum value of an integer $2^{31} - 1$." }, "is_english": true, "time_complexity": "O(n \\times \\log M + m)", "space_complexity": "O(n \\times \\log M)" }, { "problem_id": 2565, "explanations": { "1": "According to the problem, we know that the range of the index to delete characters is `[left, right]`. The optimal approach is to delete all characters within the range `[left, right]`. In other words, we need to delete a substring from string $t$, so that the remaining prefix of string $t$ can match the prefix of string $s$, and the remaining suffix of string $t$ can match the suffix of string $s$, and the prefix and suffix of string $s$ do not overlap. Note that the match here refers to subsequence matching.\n\nTherefore, we can preprocess to get arrays $f$ and $g$, where $f[i]$ represents the minimum number of characters in the prefix $t[0,..i]$ of string $t$ that match the first $[0,..f[i]]$ characters of string $s$; similarly, $g[i]$ represents the maximum number of characters in the suffix $t[i,..n-1]$ of string $t$ that match the last $[g[i],..n-1]$ characters of string $s$.\n\nThe length of the deleted characters has monotonicity. If the condition is satisfied after deleting a string of length $x$, then the condition is definitely satisfied after deleting a string of length $x+1$. Therefore, we can use the method of binary search to find the smallest length that satisfies the condition.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the length of string $t$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2566, "explanations": { "1": "First, we convert the number to a string $s$.\n\nTo get the minimum value, we just need to find the first digit $s[0]$ in the string $s$, and then replace all $s[0]$ in the string with $0$.\n\nTo get the maximum value, we need to find the first digit $s[i]$ in the string $s$ that is not $9$, and then replace all $s[i]$ in the string with $9$.\n\nFinally, return the difference between the maximum and minimum values.\n\nThe time complexity is $O(\\log n)$, and the space complexity is $O(\\log n)$. Where $n$ is the size of the number $\\textit{num}$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 2567, "explanations": { "1": "From the problem description, we know that the minimum score is actually the minimum difference between two adjacent elements in the sorted array, and the maximum score is the difference between the first and last elements of the sorted array. The score of the array $nums$ is the sum of the minimum score and the maximum score.\n\nTherefore, we can first sort the array. Since the problem allows us to modify the values of at most two elements in the array, we can modify a number to make it the same as another number in the array, making the minimum score $0$. In this case, the score of the array $nums$ is actually the maximum score. We can choose to make one of the following modifications:\n\nModify the smallest two numbers to $nums[2]$, then the maximum score is $nums[n - 1] - nums[2]$;\nModify the smallest number to $nums[1]$ and the largest number to $nums[n - 2]$, then the maximum score is $nums[n - 2] - nums[1]$;\nModify the largest two numbers to $nums[n - 3]$, then the maximum score is $nums[n - 3] - nums[0]$.\nFinally, we return the minimum score of the above three modifications.\n\nThe time complexity is $O(n \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array $nums$.\n\nSimilar problems:\n\n-[1509. Minimum Difference Between Largest and Smallest Value in Three Moves](https://github.com/doocs/leetcode/blob/main/solution/1500-1599/1509.Minimum%20Difference%20Between%20Largest%20and%20Smallest%20Value%20in%20Three%20Moves/README_EN.md)" }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 2568, "explanations": { "1": "We start from the integer $1$. If $1$ is expressible, it must appear in the array `nums`. If $2$ is expressible, it must also appear in the array `nums`. If both $1$ and $2$ are expressible, then their bitwise OR operation $3$ is also expressible, and so on.\n\nTherefore, we can enumerate the powers of $2$. If the currently enumerated $2^i$ is not in the array `nums`, then $2^i$ is the smallest unexpressible integer.\n\nThe time complexity is $O(n + \\log M)$, and the space complexity is $O(n)$. Here, $n$ and $M$ are the length of the array `nums` and the maximum value in the array `nums`, respectively." }, "is_english": true, "time_complexity": "O(n + \\log M)", "space_complexity": "O(n)" }, { "problem_id": 2569, "explanations": { "1": "According to the problem description:\n\n- Operation $1$ is to reverse all numbers in the index range $[l,..r]$ of array `nums1`, that is, change $0$ to $1$ and $1$ to $0$.\n- Operation $3$ is to sum all numbers in array `nums2`.\n- Operation $2$ is to add the sum of all numbers in array `nums2` with $p$ times the sum of all numbers in array `nums1`, that is, $sum(nums2) = sum(nums2) + p * sum(nums1)$.\n\nTherefore, we actually only need to maintain the segment sum of array `nums1`, which can be implemented through a segment tree.\n\nWe define each node of the segment tree as `Node`, each node contains the following attributes:\n\n- `l`: The left endpoint of the node, the index starts from $1$.\n- `r`: The right endpoint of the node, the index starts from $1$.\n- `s`: The segment sum of the node.\n- `lazy`: The lazy tag of the node.\n\nThe segment tree mainly has the following operations:\n\n- `build(u, l, r)`: Build the segment tree.\n- `pushdown(u)`: Propagate the lazy tag.\n- `pushup(u)`: Update the information of the parent node with the information of the child nodes.\n- `modify(u, l, r)`: Modify the segment sum. In this problem, it is to reverse each number in the segment, so the segment sum $s = r - l + 1 - s$.\n- `query(u, l, r)`: Query the segment sum.\n\nFirst, calculate the sum of all numbers in array `nums2`, denoted as $s$.\n\nWhen executing operation $1$, we only need to call `modify(1, l + 1, r + 1)`.\n\nWhen executing operation $2$, we update $s = s + p \\times query(1, 1, n)$.\n\nWhen executing operation $3$, we just need to add $s$ to the answer array.\n\nThe time complexity is $O(n + m \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ and $m$ are the lengths of arrays `nums1` and `queries` respectively." }, "is_english": true, "time_complexity": "O(n + m \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2570, "explanations": { "1": "We can use a hash table or an array `cnt` to count the frequency of each number in the two arrays.\n\nThen we enumerate each number in `cnt` from small to large. If the frequency of a number is greater than $0$, we add it to the answer array.\n\nThe time complexity is $O(n + m)$, and the space complexity is $O(M)$. Where $n$ and $m$ are the lengths of the two arrays respectively; and $M$ is the maximum value in the two arrays, in this problem, $M = 1000$." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(M)" }, { "problem_id": 2571, "explanations": { "1": "We convert the integer $n$ to binary, starting from the lowest bit:\n\n- If the current bit is 1, we accumulate the current number of consecutive 1s;\n- If the current bit is 0, we check whether the current number of consecutive 1s is greater than 0. If it is, we check whether the current number of consecutive 1s is 1. If it is, it means that we can eliminate 1 through one operation; if it is greater than 1, it means that we can reduce the number of consecutive 1s to 1 through one operation.\n\nFinally, we also need to check whether the current number of consecutive 1s is 1. If it is, it means that we can eliminate 1 through one operation; if it is greater than 1, we can eliminate the consecutive 1s through two operations.\n\nThe time complexity is $O(\\log n)$, and the space complexity is $O(1)$. Here, $n$ is the given integer in the problem." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 2572, "explanations": { "1": "Note that in the problem, the range of $nums[i]$ is $[1, 30]$. Therefore, we can preprocess all prime numbers less than or equal to $30$, which are $[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]$.\n\nIn the subset without square numbers, the product of all elements can be represented as the product of one or more distinct prime numbers, that is, each prime factor can appear at most once. Therefore, we can use a binary number to represent the prime factors in a subset, where the $i$-th bit of the binary number indicates whether the prime number $primes[i]$ appears in the subset.\n\nWe can use the method of state compression dynamic programming to solve this problem. Let $f[i]$ represent the number of schemes where the product of prime factors in the subset represented by the binary number $i$ is the product of one or more distinct prime numbers. Initially, $f[0]=1$.\n\nWe enumerate a number $x$ in the range $[2,..30]$. If $x$ is not in $nums$, or $x$ is a multiple of $4, 9, 25$, then we can skip it directly. Otherwise, we can represent the prime factors of $x$ with a binary number $mask$. Then we enumerate the current state $state$ from large to small. If the result of $state$ and $mask$ bitwise AND is $mask$, then we can transition from state $f[state \\oplus mask]$ to state $f[state]$, the transition equation is $f[state] = f[state] + cnt[x] \\times f[state \\oplus mask]$, where $cnt[x]$ represents the number of times $x$ appears in $nums$.\n\nNote that we did not start enumerating from the number $1$, because we can choose any number of number $1$ and add it to the subset without square numbers. Or we can only choose any number of number $1$ and not add it to the subset without square numbers. Both situations are legal. So the answer is $(\\sum_{i=0}^{2^{10}-1} f[i]) - 1$.\n\nThe time complexity is $O(n + C \\times M)$, and the space complexity is $O(M)$. Where $n$ is the length of $nums$; and $C$ and $M$ are the range of $nums[i]$ and the number of states in the problem, in this problem, $C=30$, $M=2^{10}$.\n\nSimilar problems:\n\n- [1994. The Number of Good Subsets](https://github.com/doocs/leetcode/blob/main/solution/1900-1999/1994.The%20Number%20of%20Good%20Subsets/README_EN.md)" }, "is_english": true, "time_complexity": "O(n + C \\times M)", "space_complexity": "O(M)" }, { "problem_id": 2573, "explanations": { "1": "Since the constructed string requires the lexicographically smallest order, we can start by filling the string $s$ with the character `'a'`.\n\nIf the current position $i$ has not been filled with a character, then we can fill the character `'a'` at position $i$. Then we enumerate all positions $j > i$. If $lcp[i][j] > 0$, then position $j$ should also be filled with the character `'a'`. Then we add one to the ASCII code of the character `'a'` and continue to fill the remaining unfilled positions.\n\nAfter filling, if there are unfilled positions in the string, it means that the corresponding string cannot be constructed, so we return an empty string.\n\nNext, we can enumerate each position $i$ and $j$ in the string from large to small, and then judge whether $s[i]$ and $s[j]$ are equal:\n\n- If $s[i] = s[j]$, at this time we need to judge whether $i$ and $j$ are the last positions of the string. If so, then $lcp[i][j]$ should be equal to $1$, otherwise $lcp[i][j]$ should be equal to $0$. If the above conditions are not met, it means that the corresponding string cannot be constructed, so we return an empty string. If $i$ and $j$ are not the last positions of the string, then $lcp[i][j]$ should be equal to $lcp[i + 1][j + 1] + 1$, otherwise it means that the corresponding string cannot be constructed, so we return an empty string.\n- Otherwise, if $lcp[i][j] > 0$, it means that the corresponding string cannot be constructed, so we return an empty string.\n\nIf every position in the string meets the above conditions, then we can construct the corresponding string and return it.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$. Where $n$ is the length of the string." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 2574, "explanations": { "1": "We define a variable $l$ to represent the sum of elements to the left of index $i$ in the array $\\textit{nums}$, and a variable $r$ to represent the sum of elements to the right of index $i$ in the array $\\textit{nums}$. Initially, $l = 0$, $r = \\sum_{i = 0}^{n - 1} \\textit{nums}[i]$.\n\nWe traverse the array $\\textit{nums}$. For the current number $x$, we update $r = r - x$. At this point, $l$ and $r$ represent the sum of elements to the left and right of index $i$ in the array $\\textit{nums}$, respectively. We add the absolute difference of $l$ and $r$ to the answer array $\\textit{ans}$, then update $l = l + x$.\n\nAfter the traversal, we return the answer array $\\textit{ans}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$, not counting the space for the return value.\n\nSimilar problems:\n\n- [0724. Find Pivot Index](https://github.com/doocs/leetcode/blob/main/solution/0700-0799/0724.Find%20Pivot%20Index/README_EN.md)\n- [1991. Find the Middle Index in Array](https://github.com/doocs/leetcode/blob/main/solution/1900-1999/1991.Find%20the%20Middle%20Index%20in%20Array/README_EN.md)" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2575, "explanations": { "1": "We iterate over the string `word`, using a variable $x$ to record the modulo result of the current prefix with $m$. If $x$ is $0$, then the divisible array value at the current position is $1$, otherwise it is $0$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string `word`. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2576, "explanations": { "1": "According to the problem description, the problem can generate at most $n / 2$ pairs of indices, where $n$ is the length of the array $\\textit{nums}$.\n\nTo mark as many indices as possible, we can sort the array $\\textit{nums}$. Next, we traverse each element $\\textit{nums}[j]$ in the right half of the array, using a pointer $\\textit{i}$ to point to the smallest element in the left half. If $\\textit{nums}[i] \\times 2 \\leq \\textit{nums}[j]$, we can mark the indices $\\textit{i}$ and $\\textit{j}$, and move $\\textit{i}$ one position to the right. Continue traversing the elements in the right half until reaching the end of the array. At this point, the number of indices we can mark is $\\textit{i} \\times 2$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 2577, "explanations": { "1": "We observe that if we cannot move at the cell $(0, 0)$, i.e., $grid[0][1] > 1$ and $grid[1][0] > 1$, then we cannot move at the cell $(0, 0)$ anymore, and we should return $-1$. For other cases, we can move.\n\nNext, we define $dist[i][j]$ to represent the earliest arrival time at $(i, j)$. Initially, $dist[0][0] = 0$, and the $dist$ of other positions are all initialized to $\\infty$.\n\nWe use a priority queue (min heap) to maintain the cells that can currently move. The elements in the priority queue are $(dist[i][j], i, j)$, i.e., $(dist[i][j], i, j)$ represents the earliest arrival time at $(i, j)$.\n\nEach time we take out the cell $(t, i, j)$ that can arrive the earliest from the priority queue. If $(i, j)$ is $(m - 1, n - 1)$, then we directly return $t$. Otherwise, we traverse the four adjacent cells $(x, y)$ of $(i, j)$, which are up, down, left, and right. If $t + 1 < grid[x][y]$, then the time $nt = grid[x][y] + (grid[x][y] - (t + 1)) \\bmod 2$ to move to $(x, y)$. At this time, we can repeatedly move to extend the time to no less than $grid[x][y]$, depending on the parity of the distance between $t + 1$ and $grid[x][y]$. Otherwise, the time $nt = t + 1$ to move to $(x, y)$. If $nt < dist[x][y]$, then we update $dist[x][y] = nt$, and add $(nt, x, y)$ to the priority queue.\n\nThe time complexity is $O(m \\times n \\times \\log (m \\times n))$, and the space complexity is $O(m \\times n)$. Where $m$ and $n$ are the number of rows and columns of the grid, respectively." }, "is_english": true, "time_complexity": "O(m \\times n \\times \\log (m \\times n))", "space_complexity": "O(m \\times n)" }, { "problem_id": 2578, "explanations": { "1": "First, we use a hash table or array $cnt$ to count the occurrences of each digit in $num$, and use a variable $n$ to record the number of digits in $num$.\n\nNext, we enumerate all the digits $i$ in $nums$, and alternately allocate the digits in $cnt$ to $num1$ and $num2$ in ascending order, recording them in an array $ans$ of length $2$. Finally, we return the sum of the two numbers in $ans$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(C)$. Where $n$ is the number of digits in $num$; and $C$ is the number of different digits in $num$, in this problem, $C \\leq 10$.", "2": "We can convert $num$ to a string or character array, then sort it, and then alternately allocate the digits in the sorted array to $num1$ and $num2$ in ascending order. Finally, we return the sum of $num1$ and $num2$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the number of digits in $num$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(C)" }, { "problem_id": 2579, "explanations": { "1": "We find that after the $n$th minute, there are a total of $2 \\times n - 1$ columns in the grid, and the numbers on each column are respectively $1, 3, 5, \\cdots, 2 \\times n - 1, 2 \\times n - 3, \\cdots, 3, 1$. The left and right parts are both arithmetic progressions, and the sum can be obtained by $2 \\times n \\times (n - 1) + 1$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 2580, "explanations": { "1": "We can first sort the intervals in the range, merge the overlapping intervals, and count the number of non-overlapping intervals, denoted as $cnt$.\n\nEach non-overlapping interval can be chosen to be put in the first group or the second group, so the number of plans is $2^{cnt}$. Note that $2^{cnt}$ may be very large, so we need to take modulo $10^9 + 7$. Here, we can use fast power to solve this problem.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the number of intervals.\n\nAlternatively, we can also avoid using fast power. Once a new non-overlapping interval is found, we multiply the number of plans by 2 and take modulo $10^9 + 7$.", "2": "" }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 2581, "explanations": { "1": "First, we traverse the given edge set $edges$ and convert it to an adjacency list $g$ where $g[i]$ represents the adjacent nodes of node $i$. Use a hash map $gs$ to record the given guess set $guesses$.\n\nThen, we start from node $0$ and perform a DFS to count the number of edges in $guesses$ among all the nodes that can be reached from node $0$. We use the variable $cnt$ to record this number.\n\nNext, we start from node $0$ and perform a DFS to count the number of edges in $guesses$ in each tree with $0$ as the root. If the number is greater than or equal to $k$, it means that this node is a possible root node, and we add $1$ to the answer.\n\nTherefore, the problem becomes to count the number of edges in $guesses$ in each tree with each node as the root. We already know that there are $cnt$ edges in $guesses$ among all the nodes that can be reached from node $0$. We can maintain this value by adding or subtracting the current edge in $guesses$ in DFS.\n\nAssume that we are currently traversing node $i$ and $cnt$ represents the number of edges in $guesses$ with $i$ as the root node. Then, for each adjacent node $j$ of $i$, we need to calculate the number of edges in $guesses$ with $j$ as the root node. If $(i, j)$ is in $guesses$, then there is no edge $(i, j)$ in the tree with $j$ as the root node, so $cnt$ should decrease by $1$. If $(j, i)$ is in $guesses$, then there is an extra edge $(i, j)$ in the tree with $j$ as the root node, so $cnt$ should increase by $1$. That is, $f[j] = f[i] + (j, i) \\in guesses - (i, j) \\in guesses$. Where $f[i]$ represents the number of edges in $guesses$ with $i$ as the root node.\n\nThe time complexity is $O(n + m)$ and the space complexity is $O(n + m)$, where $n$ and $m$ are the lengths of $edges$ and $guesses$ respectively." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(n + m)" }, { "problem_id": 2582, "explanations": { "1": "We can simulate the process of passing the pillow, and each time the pillow is passed, if the pillow reaches the front or the end of the queue, the direction of the pillow will change, and the queue will continue to pass the pillow along the opposite direction.\n\nThe time complexity is $O(time)$ and the space complexity is $O(1)$, where $time$ is the given time.", "2": "We notice that there are $n - 1$ passes in each round. Therefore, we can divide $time$ by $n - 1$ to get the number of rounds $k$ that the pillow is passed, and then take the remainder of $time$ modulo $n - 1$ to get the remaining passes $mod$ in the current round.\n\nThen we judge the current round $k$:\n\n- If $k$ is odd, then the current direction of the pillow is from the end of the queue to the front, so the pillow will be passed to the person with the number $n - mod$.\n- If $k$ is even, then the current direction of the pillow is from the front of the queue to the back, so the pillow will be passed to the person with the number $mod + 1$.\n\nThe time complexity is $O(1)$ and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(time)", "space_complexity": "O(1)" }, { "problem_id": 2583, "explanations": { "1": "We can use BFS to traverse the binary tree, while recording the sum of nodes at each level, then sort the array of node sums, and finally return the $k$th largest node sum. Note that if the number of levels in the binary tree is less than $k$, then return $-1$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in the binary tree.", "2": "We can also use DFS to traverse the binary tree, while recording the sum of nodes at each level, then sort the array of node sums, and finally return the $k$th largest node sum. Note that if the number of levels in the binary tree is less than $k$, then return $-1$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2584, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2585, "explanations": { "1": "We define $f[i][j]$ to represent the number of methods to get $j$ points exactly from the first $i$ types of questions. Initially, $f[0][0] = 1$, and the rest $f[i][j] = 0$. The answer is $f[n][target]$.\n\nWe can enumerate the $i$th type of questions, suppose the number of questions of this type is $count$, and the score is $marks$. Then we can get the following state transition equation:\n\n$$\nf[i][j] = \\sum_{k=0}^{count} f[i-1][j-k \\times marks]\n$$\n\nwhere $k$ represents the number of questions of the $i$th type.\n\nThe final answer is $f[n][target]$. Note that the answer may be very large and needs to be modulo $10^9 + 7$.\n\nThe time complexity is $O(n \\times target \\times count)$ and the space complexity is $O(n \\times target)$. $n$ is the number of types of questions, and $target$ and $count$ are the target score and the number of questions of each type, respectively." }, "is_english": true, "time_complexity": "O(n \\times target \\times count)", "space_complexity": "O(n \\times target)" }, { "problem_id": 2586, "explanations": { "1": "We just need to traverse the string in the interval $[left,.. right]$, and check if it starts and ends with a vowel. If so, the answer plus one.\n\nAfter the traversal, return the answer.\n\nThe time complexity is $O(m)$, and the space complexity is $O(1)$. Where $m = right - left + 1$." }, "is_english": true, "time_complexity": "O(m)", "space_complexity": "O(1)" }, { "problem_id": 2587, "explanations": { "1": "To maximize the number of positive integers in the prefix sum array, we need to make the elements in the prefix sum array as large as possible, that is, to add as many positive integers as possible. Therefore, we can sort the array $nums$ in descending order, then traverse the array, maintaining the prefix sum $s$. If $s \\leq 0$, it means that there can be no more positive integers in the current position and the positions after it, so we can directly return the current position.\n\nOtherwise, after the traversal, we return the length of the array.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 2588, "explanations": { "1": "We observe that a subarray can become an array of all $0$s if and only if the number of $1$s on each binary bit of all elements in the subarray is even.\n\nIf there exist indices $i$ and $j$ such that $i \\lt j$ and the subarrays $nums[0,..,i]$ and $nums[0,..,j]$ have the same parity of the number of $1$s on each binary bit, then we can turn the subarray $nums[i + 1,..,j]$ into an array of all $0$s.\n\nTherefore, we can use the prefix XOR method and a hash table $cnt$ to count the occurrences of each prefix XOR value. We traverse the array, for each element $x$, we calculate its prefix XOR value $mask$, then add the number of occurrences of $mask$ to the answer. Then, we increase the number of occurrences of $mask$ by $1$.\n\nFinally, we return the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2589, "explanations": { "1": "We observe that the problem is equivalent to selecting $duration$ integer time points in each interval $[start,..,end]$, so that the total number of selected integer time points is minimized.\n\nTherefore, we can first sort $tasks$ in ascending order of end time $end$. Then we greedily make selections. For each task, we start from the end time $end$ and choose the points as late as possible from back to front. This way, these points are more likely to be reused by later tasks.\n\nIn our implementation, we can use an array $vis$ of length $2010$ to record whether each time point has been selected. Then for each task, we first count the number of points $cnt$ that have been selected in the interval $[start,..,end]$, and then select $duration - cnt$ points from back to front, while recording the number of selected points $ans$ and updating the $vis$ array.\n\nFinally, we return $ans$.\n\nThe time complexity is $O(n \\times \\log n + n \\times m)$, and the space complexity is $O(m)$. Here, $n$ and $m$ are the lengths of $tasks$ and $vis$ array, respectively. In this problem, $m = 2010$." }, "is_english": true, "time_complexity": "O(n \\times \\log n + n \\times m)", "space_complexity": "O(m)" }, { "problem_id": 2590, "explanations": { "1": "We use a hash table $tasks$ to record the set of tasks for each user, where the key is the user ID and the value is a sorted set sorted by the deadline of the task. In addition, we use a variable $i$ to record the current task ID.\n\nWhen calling the `addTask` method, we add the task to the task set of the corresponding user and return the task ID. The time complexity of this operation is $O(\\log n)$.\n\nWhen calling the `getAllTasks` method, we traverse the task set of the corresponding user and add the description of the unfinished task to the result list, and then return the result list. The time complexity of this operation is $O(n)$.\n\nWhen calling the `getTasksForTag` method, we traverse the task set of the corresponding user and add the description of the unfinished task to the result list, and then return the result list. The time complexity of this operation is $O(n)$.\n\nWhen calling the `completeTask` method, we traverse the task set of the corresponding user and mark the task whose task ID is $taskId$ as completed. The time complexity of this operation is $(n)$.\n\nThe space complexity is $O(n)$. Where $n$ is the number of all tasks." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(n)" }, { "problem_id": 2591, "explanations": { "1": "If $money \\lt children$, then there must be a child who did not receive money, return $-1$.\n\nIf $money \\gt 8 \\times children$, then there are $children-1$ children who received $8$ dollars, and the remaining child received $money - 8 \\times (children-1)$ dollars, return $children-1$.\n\nIf $money = 8 \\times children - 4$, then there are $children-2$ children who received $8$ dollars, and the remaining two children shared the remaining $12$ dollars (as long as it is not $4$, $8$ dollars is fine), return $children-2$.\n\nIf we assume that there are $x$ children who received $8$ dollars, then the remaining money is $money- 8 \\times x$, as long as it is greater than or equal to the number of remaining children $children-x$, it can meet the requirements. Therefore, we only need to find the maximum value of $x$, which is the answer.\n\nTime complexity $O(1)$, space complexity $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 2592, "explanations": { "1": "We can sort the array $nums$ first.\n\nThen we define a pointer $i$ pointing to the first element of the array $nums$. We traverse the array $nums$, and for each element $x$ we encounter, if $x$ is greater than $nums[i]$, then we move the pointer $i$ to the right.\n\nFinally, we return the value of the pointer $i$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$, where $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 2593, "explanations": { "1": "We use a priority queue to maintain the unmarked elements in the array, and each item in the queue is a tuple $(x, i)$, where $x$ and $i$ represent the element value and index of the array respectively. An array $vis$ is used to record whether the element in the array is marked.\n\nEach time we take out the smallest element $(x, i)$ from the queue, we add $x$ to the answer, and then mark the element at the $i$ position, and the left and right adjacent elements at the $i$ position, that is, the elements at the $i-1$ and $i+1$ positions. Then we determine whether the top element of the heap is marked. If it is marked, pop the top element of the heap until the top element is unmarked or the heap is empty.\n\nFinally, return the answer.\n\nThe time complexity is $O(n \\times \\log n)$ and the space complexity is $O(n)$, where $n$ is the length of the array.", "2": "We can create an index array $idx$ where $idx[i]=i$, and then we sort the index array $idx$ according to the element values in the array $nums$. If the element values are the same, then sort them according to the index values.\n\nNext, create an array $vis$ of length $n+2$ where $vis[i]=false$, which means whether the element in the array is marked.\n\nWe traverse the index array $idx$, and for each index $i$ in the array, if $vis[i+1]$ is $false$, that is, the element at position $i$ is not marked, we add $nums[i]$ to the answer, and then mark the element at position $i$, and the left and right adjacent elements at position $i$, that is, the elements at positions $i-1$ and $i+1$. Continue to traverse the index array $idx$ until the end.\n\nFinally, return the answer.\n\nThe time complexity is $O(n \\times \\log n)$ and the space complexity is $O(n)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2594, "explanations": { "1": "We notice that the longer the repair time, the more cars are repaired. Therefore, we can use the repair time as the target of binary search, and binary search for the minimum repair time.\n\nWe define the left and right boundaries of the binary search as $left=0$, $right=ranks[0] \\times cars \\times cars$. Next, we binary search for the repair time $mid$, and the number of cars each mechanic can repair is $\\lfloor \\sqrt{\\frac{mid}{r}} \\rfloor$, where $\\lfloor x \\rfloor$ represents rounding down. If the number of cars repaired is greater than or equal to $cars$, it means that the repair time $mid$ is feasible, we reduce the right boundary to $mid$, otherwise we increase the left boundary to $mid+1$.\n\nFinally, we return the left boundary.\n\nThe time complexity is $O(n \\times \\log M)$, and the space complexity is $O(1)$. Here, $n$ is the number of mechanics, and $M$ is the upper bound of the binary search." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(1)" }, { "problem_id": 2595, "explanations": { "1": "According to the problem description, enumerate the binary representation of $n$ from the low bit to the high bit. If the bit is $1$, add $1$ to the corresponding counter according to whether the index of the bit is odd or even.\n\nThe time complexity is $O(\\log n)$ and the space complexity is $O(1)$. Where $n$ is the given integer.", "2": "We can define a mask $\\textit{mask} = \\text{0x5555}$, which is represented in binary as $\\text{0101 0101 0101 0101}_2$. Then, performing a bitwise AND operation between $n$ and $\\textit{mask}$ will give us the bits at even indices in the binary representation of $n$. Performing a bitwise AND operation between $n$ and the complement of $\\textit{mask}$ will give us the bits at odd indices in the binary representation of $n$. We can count the number of 1s in these two results.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$. Here, $n$ is the given integer." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 2596, "explanations": { "1": "We first use an array $\\textit{pos}$ to record the coordinates of each cell visited by the knight, then traverse the $\\textit{pos}$ array and check if the coordinate difference between two adjacent cells is $(1, 2)$ or $(2, 1)$. If not, return $\\textit{false}$.\n\nOtherwise, after the traversal, return $\\textit{true}$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ is the side length of the chessboard." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 2597, "explanations": { "1": "We use a hash table or array $\\textit{cnt}$ to record the currently selected numbers and their counts, and use $\\textit{ans}$ to record the number of beautiful subsets. Initially, $\\textit{ans} = -1$ to exclude the empty set.\n\nFor each number $x$ in the array $\\textit{nums}$, we have two choices:\n\n- Do not select $x$, and directly recurse to the next number;\n- Select $x$, and check if $x + k$ and $x - k$ have already appeared in $\\textit{cnt}$. If neither has appeared, we can select $x$. In this case, we increment the count of $x$ by one, recurse to the next number, and then decrement the count of $x$ by one.\n\nFinally, we return $\\textit{ans}$.\n\nThe time complexity is $O(2^n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(2^n)", "space_complexity": "O(n)" }, { "problem_id": 2598, "explanations": { "1": "We use a hash table $\\textit{cnt}$ to count the number of remainders when each number in the array is modulo $\\textit{value}$.\n\nThen we traverse starting from $0$. For the current number $i$ being traversed, if $\\textit{cnt}[i \\bmod \\textit{value}]$ is $0$, it means there is no number in the array whose remainder when modulo $\\textit{value}$ is $i$, so $i$ is the MEX of the array, and we can return it directly. Otherwise, we decrement $\\textit{cnt}[i \\bmod \\textit{value}]$ by $1$ and continue traversing.\n\nThe time complexity is $O(n)$ and the space complexity is $O(\\textit{value})$, where $n$ is the length of array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(\\textit{value})" }, { "problem_id": 2599, "explanations": { "1": "We use a variable $s$ to record the prefix sum of the current array.\n\nTraverse the array $nums$, add the current element $x$ to the prefix sum $s$. If $x$ is a negative number, add $x$ to the min heap. If $s$ is negative at this time, greedily take out the smallest negative number and subtract it from $s$, and add one to the answer. Finally, return the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2600, "explanations": { "1": "According to the problem description, we should take as many items marked as $1$ as possible, then take items marked as $0$, and finally take items marked as $-1$.\n\nThus:\n\n- If the number of items marked as $1$ in the bag is greater than or equal to $k$, we take $k$ items, and the sum of the numbers is $k$.\n- If the number of items marked as $1$ is less than $k$, we take $\\textit{numOnes}$ items, resulting in a sum of $\\textit{numOnes}$. If the number of items marked as $0$ is greater than or equal to $k - \\textit{numOnes}$, we take $k - \\textit{numOnes}$ more items, keeping the sum at $\\textit{numOnes}$.\n- Otherwise, we take $k - \\textit{numOnes} - \\textit{numZeros}$ items from those marked as $-1$, resulting in a sum of $\\textit{numOnes} - (k - \\textit{numOnes} - \\textit{numZeros})$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 2601, "explanations": { "1": "We first preprocess all the primes within $1000$ and record them in the array $p$.\n\nFor each element $nums[i]$ in the array $nums$, we need to find a prime $p[j]$ such that $p[j] \\gt nums[i] - nums[i + 1]$ and $p[j]$ is as small as possible. If there is no such prime, it means that it cannot be strictly increased by subtraction operations, return `false`. If there is such a prime, we will subtract $p[j]$ from $nums[i]$ and continue to process the next element.\n\nIf all the elements in $nums$ are processed, it means that it can be strictly increased by subtraction operations, return `true`.\n\nThe time complexity is $O(n \\log n)$ and the space complexity is $O(n)$. where $n$ is the length of the array $nums$.", "2": "" }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2602, "explanations": { "1": "First, we sort the array $nums$ and calculate the prefix sum array $s$ with a length of $n+1$, where $s[i]$ represents the sum of the first $i$ elements in the array $nums$.\n\nThen, we traverse each query $queries[i]$, we need to reduce all elements greater than $queries[i]$ to $queries[i]$, and increase all elements less than $queries[i]$ to $queries[i]$.\n\nWe can use binary search to find the index $i$ of the first element in the array $nums$ that is greater than $queries[i]$. There are $n-i$ elements that need to be reduced to $queries[i]$, and the sum of these elements is $s[n]-s[i]$. These elements need to be reduced by $n-i$ $queries[i]$, so the total number of operations to reduce these elements to $queries[i]$ is $s[n]-s[i]-(n-i)\\times queries[i]$.\n\nSimilarly, we can find the index $i$ of the first element in the array $nums$ that is greater than or equal to $queries[i]$. There are $i$ elements that need to be increased to $queries[i]$, and the sum of these elements is $s[i]$. Therefore, the total number of operations to increase these elements to $queries[i]$ is $queries[i]\\times i-s[i]$.\n\nFinally, add these two total operation counts together to get the minimum number of operations to change all elements in the array $nums$ to $queries[i]$, that is, $ans[i]=s[n]-s[i]-(n-i)\\times queries[i]+queries[i]\\times i-s[i]$.\n\nTime complexity $O(n \\times \\log n)$, space complexity $O(n)$, where $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2603, "explanations": { "1": "We first convert the edges in $edges$ to the adjacency list $g$, where $g[i]$ represents all the adjacent nodes of node $i$, represented by a set.\n\nThen we traverse all nodes and find the nodes where $coins[i]=0$ and $g[i]$ only has one node (that is, the leaf node where the coin is $0$), and add them to the queue $q$.\n\nThen we continuously remove nodes from the queue and delete them from the adjacent list. Then we check whether the adjacent nodes meet the condition where $coins[j]=0$ and $g[j]$ only has one node. If it meets, we add it to the queue $q$. Loop until the queue is empty.\n\nAfter the above operation, we get a new tree, and the leaf nodes of the tree are all nodes where the coin is $1$.\n\nThen, we delete the remaining two layers of leaf nodes, and finally get a tree where all nodes need to be visited. We only need to count the number of edges and multiply it by $2$ to get the answer.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the number of nodes.\n\nSimilar problems:\n\n- [2204. Distance to a Cycle in Undirected Graph](https://github.com/doocs/leetcode/blob/main/solution/2200-2299/2204.Distance%20to%20a%20Cycle%20in%20Undirected%20Graph/README_EN.md)" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2604, "explanations": { "1": "First, sort the chickens and grains by their position from left to right. Then enumerate the time $t$ using binary search to find the smallest $t$ such that all the grains can be eaten up in $t$ seconds.\n\nFor each chicken, we use the pointer $j$ to point to the leftmost grain that has not been eaten, and the current position of the chicken is $x$ and the position of the grain is $y$. There are the following cases:\n\n- If $y \\leq x$, we note that $d = x - y$. If $d \\gt t$, the current grain cannot be eaten, so directly return `false`. Otherwise, move the pointer $j$ to the right until $j=m$ or $grains[j] \\gt x$. At this point, we need to check whether the chicken can eat the grain pointed to by $j$. If it can, continue to move the pointer $j$ to the right until $j=m$ or $min(d, grains[j] - x) + grains[j] - y \\gt t$.\n- If $y \\lt x$, move the pointer $j$ to the right until $j=m$ or $grains[j] - x \\gt t$.\n\nIf $j=m$, it means that all the grains have been eaten, return `true`, otherwise return `false`.\n\nTime complexity $O(n \\times \\log n + m \\times \\log m + (m + n) \\times \\log U)$, space complexity $O(\\log m + \\log n)$. $n$ and $m$ are the number of chickens and grains respectively, and $U$ is the maximum value of all the chicken and grain positions." }, "is_english": true, "time_complexity": "O(n \\times \\log n + m \\times \\log m + (m + n) \\times \\log U)", "space_complexity": "O(\\log m + \\log n)" }, { "problem_id": 2605, "explanations": { "1": "We observe that if there are the same numbers in the arrays $nums1$ and $nums2$, then the minimum of the same numbers is the smallest number. Otherwise, we take the number $a$ in the array $nums1$ and the number $b$ in the array $nums2$, and concatenate the two numbers $a$ and $b$ into two numbers, and take the smaller number.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(1)$, where $m$ and $n$ are the lengths of the arrays $nums1$ and $nums2$.", "2": "We can use a hash table or array to record the numbers in the arrays $nums1$ and $nums2$, and then enumerate $1 \\sim 9$. If $i$ appears in both arrays, then $i$ is the smallest number. Otherwise, we take the number $a$ in the array $nums1$ and the number $b$ in the array $nums2$, and concatenate the two numbers $a$ and $b$ into two numbers, and take the smaller number.\n\nThe time complexity is $(m + n)$, and the space complexity is $O(C)$. Where $m$ and $n$ are the lengths of the arrays $nums1$ and $nums2$ respectively; and $C$ is the range of the numbers in the arrays $nums1$ and $nums2$, and the range in this problem is $C = 10$.", "3": "Since the range of the numbers is $1 \\sim 9$, we can use a binary number with a length of $10$ to represent the numbers in the arrays $nums1$ and $nums2$. We use $mask1$ to represent the numbers in the array $nums1$, and use $mask2$ to represent the numbers in the array $nums2$.\n\nIf the number $mask$ obtained by performing a bitwise AND operation on $mask1$ and $mask2$ is not equal to $0$, then we extract the position of the last $1$ in the number $mask$, which is the smallest number.\n\nOtherwise, we extract the position of the last $1$ in $mask1$ and $mask2$ respectively, and denote them as $a$ and $b$, respectively. Then the smallest number is $min(a \\times 10 + b, b \\times 10 + a)$.\n\nThe time complexity is $O(m + n)$, and the space complexity is $O(1)$. Where $m$ and $n$ are the lengths of the arrays $nums1$ and $nums2$ respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(1)" }, { "problem_id": 2606, "explanations": { "1": "According to the description of the problem, we traverse each character $c$ in the string $s$, obtain its corresponding value $v$, and then update the current prefix sum $tot=tot+v$. Then, the cost of the maximum cost substring ending with $c$ is $tot$ minus the minimum prefix sum $mi$, that is, $tot-mi$. We update the answer $ans=max(ans,tot-mi)$ and maintain the minimum prefix sum $mi=min(mi,tot)$.\n\nAfter the traversal is over, return the answer $ans$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(C)$. Where $n$ is the length of the string $s$; and $C$ is the size of the character set, which is $26$ in this problem.", "2": "We can consider the value $v$ of each character $c$ as an integer, so the actual problem is to solve the maximum subarray sum problem.\n\nWe use the variable $f$ to maintain the cost of the maximum cost substring ending with the current character $c$. Each time we traverse to a character $c$, we update $f=max(f, 0) + v$. Then we update the answer $ans=max(ans,f)$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(C)$. Where $n$ is the length of the string $s$; and $C$ is the size of the character set, which is $26$ in this problem." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(C)" }, { "problem_id": 2607, "explanations": { "1": "题目要求每个长度为 $k$ 的子数组的元素总和相等,那么有以下等式成立:\n\n$$\narr_i + arr_{i + 1} + \\cdots + arr_{i + k - 1} = arr_{i + 1} + arr_{i + 2} + \\cdots + arr_{i + k}\n$$\n\n化简得:\n\n$$\narr_i = arr_{i + k}\n$$\n\n也即是说,数组 $arr$ 有一个大小为 $k$ 的循环节,而由于数组 $arr$ 是一个循环数组,那么数组 $arr$ 也有一个长度为 $n$ 的循环节。换句话说,数组 $arr$ 上间隔为 $k$,以及间隔为 $n$ 的元素均相等。即有:\n\n$$\narr_i = arr_{i + k \\times x + n \\times y}\n$$\n\n根据裴蜀定理,有 $a \\times x + b \\times y = gcd(a, b)$,因此,有:\n\n$$\narr_i = arr_{i + k \\times x + n \\times y} = arr_{i + gcd(k, n)}\n$$\n\n因此,数组 $arr$ 上的元素可以分为 $gcd(k, n)$ 组,每组的元素间隔为 $gcd(k, n)$,且每一组中的所有元素均相等。对于每一组,我们可以将其元素按照大小排序,然后取中位数,即可将该组中的所有元素变为中位数。对于所有组,我们将其中位数之差的绝对值求和,即为答案。\n\n时间复杂度 $O(n \\times \\log n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $arr$ 的长度。" }, "is_english": false, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2608, "explanations": { "1": "We first construct the adjacency list $g$ of the graph according to the array $edges$, where $g[u]$ represents all the adjacent vertices of vertex $u$.\n\nThen we enumerate the two-directional edge $(u, v)$, if the path from vertex $u$ to vertex $v$ still exists after deleting this edge, then the length of the shortest cycle containing this edge is $dist[v] + 1$, where $dist[v]$ represents the shortest path length from vertex $u$ to vertex $v$. We take the minimum of all these cycles.\n\nThe time complexity is $O(m^2)$ and the space complexity is $O(m + n)$, where $m$ and $n$ are the length of the array $edges$ and the number of vertices.", "2": "Similar to Solution 1, we first construct the adjacency list $g$ of the graph according to the array $edges$, where $g[u]$ represents all the adjacent vertices of vertex $u$.\n\nThen we enumerate the vertex $u$, if there are two paths from vertex $u$ to vertex $v$, then we currently find a cycle, the length is the sum of the length of the two paths. We take the minimum of all these cycles.\n\nThe time complexity is $O(m \\times n)$ and the space complexity is $O(m + n)$, where $m$ and $n$ are the length of the array $edges$ and the number of vertices." }, "is_english": true, "time_complexity": "O(m^2)", "space_complexity": "O(m + n)" }, { "problem_id": 2609, "explanations": { "1": "Since the range of $n$ is small, we can enumerate all substrings $s[i..j]$ to check if it is a balanced string. If so, update the answer.\n\nThe time complexity is $O(n^3)$, and the space complexity is $O(1)$. Where $n$ is the length of string $s$.", "2": "We use variables $zero$ and $one$ to record the number of continuous $0$ and $1$.\n\nTraverse the string $s$, for the current character $c$:\n\n- If the current character is `'0'`, we check if $one$ is greater than $0$, if so, we reset $zero$ and $one$ to $0$, and then add $1$ to $zero$.\n- If the current character is `'1'`, we add $1$ to $one$, and update the answer to $ans = max(ans, 2 \\times min(one, zero))$.\n\nAfter the traversal is complete, we can get the length of the longest balanced substring.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$. Where $n$ is the length of string $s$." }, "is_english": true, "time_complexity": "O(n^3)", "space_complexity": "O(1)" }, { "problem_id": 2610, "explanations": { "1": "We first use an array or hash table $\\textit{cnt}$ to count the frequency of each element in the array $\\textit{nums}$.\n\nThen we iterate through $\\textit{cnt}$. For each element $x$, we add it to the 0th row, 1st row, 2nd row, ..., and $(cnt[x]-1)$th row of the answer list.\n\nFinally, we return the answer list.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2611, "explanations": { "1": "We can first give all the cheese to the second mouse. Next, consider giving $k$ pieces of cheese to the first mouse. How should we choose these $k$ pieces of cheese? Obviously, if we give the $i$-th piece of cheese from the second mouse to the first mouse, the change in the score is $reward1[i] - reward2[i]$. We hope that this change is as large as possible, so that the total score is maximized.\n\nTherefore, we sort the cheese in decreasing order of `reward1[i] - reward2[i]`. The first $k$ pieces of cheese are eaten by the first mouse, and the remaining cheese is eaten by the second mouse to obtain the maximum score.\n\nTime complexity $O(n \\times \\log n)$, space complexity $O(n)$. Where $n$ is the number of cheeses.", "2": "" }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2612, "explanations": { "1": "We notice that for any index $i$ in the subarray interval $[l,..r]$, the flipped index $j = l + r - i$.\n\nIf the subarray moves one position to the right, then $j = l + 1 + r + 1 - i = l + r - i + 2$, that is, $j$ will increase by $2$.\n\nSimilarly, if the subarray moves one position to the left, then $j = l - 1 + r - 1 - i = l + r - i - 2$, that is, $j$ will decrease by $2$.\n\nTherefore, for a specific index $i$, all its flipped indices form an arithmetic progression with common difference $2$, that is, all the flipped indices have the same parity.\n\nNext, we consider the range of values ​​of the index $i$ after flipping $j$.\n\n- If the boundary is not considered, the range of values ​​of $j$ is $[i - k + 1, i + k - 1]$.\n- If the subarray is on the left, then $[l, r] = [0, k - 1]$, so the flipped index $j$ of $i$ is $0 + k - 1 - i$, that is, $j = k - i - 1$, so the left boundary $mi = max(i - k + 1, k - i - 1)$.\n- If the subarray is on the right, then $[l, r] = [n - k, n - 1]$, so the flipped index $j= n - k + n - 1 - i$ is $j = n \\times 2 - k - i - 1$, so the right boundary of $j$ is $mx = min(i + k - 1, n \\times 2 - k - i - 1)$.\n\nWe use two ordered sets to store all the odd indices and even indices to be searched, here we need to exclude the indices in the array $banned$ and the index $p$.\n\nThen we use BFS to search, each time searching all the flipped indices $j$ of the current index $i$, that is, $j = mi, mi + 2, mi + 4, \\dots, mx$, updating the answer of index $j$ and adding index $j$ to the search queue, and removing index $j$ from the corresponding ordered set.\n\nWhen the search is over, the answer to all indices can be obtained.\n\nThe time complexity is $O(n \\times \\log n)$ and the space complexity is $O(n)$. Where $n$ is the given array length in the problem." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2613, "explanations": { "1": "This problem is equivalent to finding two points in the plane, such that the Manhattan distance between them is the smallest. If there are multiple points satisfying the condition, return the one with the smallest index.\n\nFirst, we handle the case where there are duplicate points. For each point, we record the corresponding indices in a list. If the length of the index list is greater than $1$, then the first two indices in the index list can be used as candidates, and we find the smallest index pair.\n\nIf there are no duplicate points, we sort all the points by $x$ coordinates, and then use the divide and conquer to solve the problem.\n\nFor each interval $[l, r]$, we first calculate the median of the $x$ coordinates $m$, and then recursively solve the left and right intervals, and get $d_1, (pi_1, pj_1)$ and $d_2, (pi_2, pj_2)$ respectively, where $d_1$ and $d_2$ are the minimum Manhattan distances of the left and right intervals respectively, and $(pi_1, pj_1)$ and $(pi_2, pj_2)$ are the index pairs of the two points of the minimum Manhattan distance of the left and right intervals respectively. We take the smaller one of $d_1$ and $d_2$ as the minimum Manhattan distance of the current interval, and if $d_1 = d_2$, we take the one with the smaller index as the answer. The corresponding two points of the index are taken as the answer.\n\nThe above considers the case where the two points are on the same side. If the two points are on different sides, we take the middle point, i.e. the point with the index of $m = \\lfloor (l + r) / 2 \\rfloor$ as the standard, and divide a new region. The range of this region is to expand the range of $d_1$ from the middle point to the left and right sides respectively. Then we sort these points in the range by $y$ coordinates, and then traverse each point pair in the sorted order. If the difference of the $y$ coordinates of the two points is greater than the current minimum Manhattan distance, then the following point pairs do not need to be considered, because their $y$ coordinate differences are larger, so the Manhattan distance is larger, and it will not be smaller than the current minimum Manhattan distance. Otherwise, we update the minimum Manhattan distance, and update the answer.\n\nFinally, we return the answer.\n\nTime complexity: $O(n \\times \\log n)$, where $n$ is the length of the array.\n\nSpace complexity: $O(n)$." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 2614, "explanations": { "1": "We implement a function `is_prime` to check whether a number is prime.\n\nThen we iterate the array and check whether the numbers on the diagonals are prime. If so, we update the answer.\n\nThe time complexity is $O(n \\times \\sqrt{M})$, where $n$ and $M$ are the number of rows of the array and the maximum value in the array, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\sqrt{M})", "space_complexity": "O(1)" }, { "problem_id": 2615, "explanations": { "1": "我们先用哈希表 $d$ 记录数组 $nums$ 中每个元素对应的下标列表,即 $d[x]$ 表示数组 $nums$ 中所有值为 $x$ 的下标列表。\n\n对于哈希表 $d$ 中的每个值列表 $idx$,我们可以计算出 $idx$ 中每个下标 $i$ 对应的 $arr[i]$ 的值。对于第一个下标 $idx[0]$,右边所有下标距离 $idx[0]$ 的和 $right=\\sum_{i=0}^{m-1} - idx[0] \\times m$。接下来我们遍历 $idx$,每一次计算得到 $ans[idx[i]] = left + right$,然后更新 $left$ 和 $right$,即 $left = left + (idx[i+1] - idx[i]) \\times (i+1)$,而 $right = right - (idx[i+1] - idx[i]) \\times (m-i-1)$。\n\n遍历结束后,我们得到了数组 $nums$ 中每个元素对应的 $arr$ 的值,即 $ans$。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $nums$ 的长度。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2616, "explanations": { "1": "We notice that the maximum difference has monotonicity: if a maximum difference $x$ is feasible, then $x-1$ is also feasible. Therefore, we can use binary search to find the minimal feasible maximum difference.\n\nFirst, sort the array $\\textit{nums}$. Then, for a given maximum difference $x$, check whether it is possible to form $p$ pairs of indices such that the maximum difference in each pair does not exceed $x$. If possible, we can try a smaller $x$; otherwise, we need to increase $x$.\n\nTo check whether $p$ such pairs exist with maximum difference at most $x$, we can use a greedy approach. Traverse the sorted array $\\textit{nums}$ from left to right. For the current index $i$, if the difference between $\\textit{nums}[i+1]$ and $\\textit{nums}[i]$ does not exceed $x$, we can form a pair with $i$ and $i+1$, increment the pair count $cnt$, and increase $i$ by $2$. Otherwise, increase $i$ by $1$. After traversing, if $cnt \\geq p$, then such $p$ pairs exist; otherwise, they do not.\n\nThe time complexity is $O(n \\times (\\log n + \\log m))$, where $n$ is the length of $\\textit{nums}$ and $m$ is the difference between the maximum and minimum values in $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times (\\log n + \\log m))", "space_complexity": "O(1)" }, { "problem_id": 2617, "explanations": { "1": "Let's denote the number of rows of the grid as $m$ and the number of columns as $n$. Define $dist[i][j]$ to be the shortest distance from the coordinate $(0, 0)$ to the coordinate $(i, j)$. Initially, $dist[0][0]=1$ and $dist[i][j]=-1$ for all other $i$ and $j$.\n\nFor each grid $(i, j)$, it can come from the grid above or the grid on the left. If it comes from the grid above $(i', j)$, where $0 \\leq i' \\lt i$, then $(i', j)$ must satisfy $grid[i'][j] + i' \\geq i$. We need to select from these grids the one that is closest.\n\nTherefore, we maintain a priority queue (min-heap) for each column $j$. Each element of the priority queue is a pair $(dist[i][j], i)$, which represents that the shortest distance from the coordinate $(0, 0)$ to the coordinate $(i, j)$ is $dist[i][j]$. When we consider the coordinate $(i, j)$, we only need to take out the head element $(dist[i'][j], i')$ of the priority queue. If $grid[i'][j] + i' \\geq i$, we can move from the coordinate $(i', j)$ to the coordinate $(i, j)$. At this time, we can update the value of $dist[i][j]$, that is, $dist[i][j] = dist[i'][j] + 1$, and add $(dist[i][j], i)$ to the priority queue.\n\nSimilarly, we can maintain a priority queue for each row $i$ and perform a similar operation.\n\nFinally, we can obtain the shortest distance from the coordinate $(0, 0)$ to the coordinate $(m - 1, n - 1)$, that is, $dist[m - 1][n - 1]$, which is the answer.\n\nThe time complexity is $O(m \\times n \\times \\log (m \\times n))$ and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the number of rows and columns of the grid, respectively." }, "is_english": true, "time_complexity": "O(m \\times n \\times \\log (m \\times n))", "space_complexity": "O(m \\times n)" }, { "problem_id": 2618, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2619, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2620, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2621, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2622, "explanations": { "1": "我们用哈希表 $cache$ 记录键值对,其中键为整型键 $key$,值为一个数组,数组的第一个元素为整型值 $value$,第二个元素为元素的过期时间 $expire$。\n\n我们实现一个 `removeExpire` 方法,用于删除过期的键值对。在 `set`、`get` 和 `count` 方法中,我们先调用 `removeExpire` 方法,然后再进行相应的操作。\n\n时间复杂度为 $O(1)$,空间复杂度为 $O(n)$。其中 $n$ 为哈希表 $cache$ 的大小。" }, "is_english": false, "time_complexity": "O(1)", "space_complexity": "O(n)" }, { "problem_id": 2623, "explanations": { "1": "我们可以使用哈希表来存储函数的参数和返回值,当再次调用函数时,如果参数已经存在于哈希表中,则直接返回哈希表中的值,否则调用函数并将返回值存入哈希表中。\n\n时间复杂度 $O(1)$,空间复杂度 $O(n)$。其中 $n$ 为函数的参数个数。" }, "is_english": false, "time_complexity": "O(1)", "space_complexity": "O(n)" }, { "problem_id": 2624, "explanations": { "1": "我们首先判断数组的长度是否等于行数与列数的乘积,如果不等,说明输入是无效的,返回空数组。\n\n接下来,我们可以模拟蜗牛排序的过程,从左上角开始,遍历数组,按照蜗牛排序的顺序,将遍历到的元素依次放入结果数组中。\n\n时间复杂度 $(n)$,其中 $n$ 为数组的长度。忽略答案数组的空间消耗,空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 2625, "explanations": { "1": "我们可以使用递归的方法,将多维数组扁平化。\n\n在函数中,我们首先判断 $n$ 是否小于等于 $0$,如果是,直接返回原数组。否则,我们遍历数组的每个元素 $x$,如果 $x$ 是数组,我们递归调用函数,参数为 $(x, n - 1)$,将返回值添加到结果数组中;否则,将 $x$ 添加到结果数组中。最后返回结果数组。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是数组的元素个数。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2626, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2627, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2628, "explanations": { "1": "我们先判断 `o1` 是否为空,或者 `o1` 是否非对象类型。如果是,则直接返回 `o1` 和 `o2` 是否相等。\n\n否则,我们判断 `o1` 和 `o2` 的类型是否相同。如果不同,则返回 `false`。\n\n接下来,我们判断 `o1` 和 `o2` 是否都是数组。如果不是,则返回 `false`。\n\n如果是数组,则判断两个数组的长度是否相同。如果不同,则返回 `false`。否则,我们遍历两个数组对应位置的元素,递归调用 `areDeeplyEqual` 函数,判断两个元素是否相等。如果有一个元素不相等,则返回 `false`。否则,返回 `true`。\n\n如果 `o1` 和 `o2` 都不是数组,则判断两个对象的键的个数是否相同。如果不同,则返回 `false`。否则,我们遍历 `o1` 的所有键,递归调用 `areDeeplyEqual` 函数,判断两个键对应的值是否相等。如果有一个键对应的值不相等,则返回 `false`。否则,返回 `true`。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为 `o1` 和 `o2` 的长度。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2629, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2630, "explanations": { "1": "我们用两个哈希表,其中:\n\n- `idxMap` 用于记录每个参数对应的索引,索引从 $0$ 开始逐渐递增;\n- `cache` 用于记录每个函数参数调用的结果。\n\n对于每个函数参数,我们将其转换为索引序列,然后将其转换为字符串作为 `cache` 的键,将函数调用的结果作为 `cache` 的值。每一次函数调用,我们都先判断 `cache` 中是否存在该键,如果存在,则直接返回对应的值,否则调用函数并将结果存入 `cache` 中。\n\n时间复杂度 $O(1)$,空间复杂度 $O(n)$。其中 $n$ 为函数参数的个数。" }, "is_english": false, "time_complexity": "O(1)", "space_complexity": "O(n)" }, { "problem_id": 2631, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2632, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2633, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2634, "explanations": { "1": "We traverse the array $arr$ and for each element $arr[i]$, if $fn(arr[i], i)$ is true, we add it to the answer array. Finally, we return the answer array.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $arr$. Ignoring the space consumption of the answer, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2635, "explanations": { "1": "We traverse the array $arr$, for each element $arr[i]$, replace it with $fn(arr[i], i)$. Finally, return the array $arr$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $arr$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2636, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2637, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2638, "explanations": { "1": "First, sort the array $nums$ in ascending order, and then group the elements in the array according to the remainder modulo $k$, that is, the elements $nums[i] \\bmod k$ with the same remainder are in the same group. Then for any two elements in different groups, their absolute difference is not equal to $k$. Therefore, we can obtain the number of subsets in each group, and then multiply the number of subsets in each group to obtain the answer.\n\nFor each group $arr$, we can use dynamic programming to obtain the number of subsets. Let $f[i]$ denote the number of subsets of the first $i$ elements, and initially $f[0] = 1$, and $f[1]=2$. When $i \\geq 2$, if $arr[i-1]-arr[i-2]=k$, if we choose $arr[i-1]$, then $f[i]=f[i-2]$; If we do not choose $arr[i-1]$, then $f[i]=f[i-1]$. Therefore, when $arr[i-1]-arr[i-2]=k$, we have $f[i]=f[i-1]+f[i-2]$; otherwise $f[i] = f[i - 1] \\times 2$. The number of subsets of this group is $f[m]$, where $m$ is the length of the array $arr$.\n\nFinally, we multiply the number of subsets of each group to obtain the answer.\n\nThe time complexity is $O(n \\times \\log n)$ and the space complexity is $O(n)$, where $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2639, "explanations": { "1": "We denote the number of columns in the matrix as $n$, and create an array $ans$ of length $n$, where $ans[i]$ represents the width of the $i$-th column. Initially, $ans[i] = 0$.\n\nWe traverse each row in the matrix. For each element in each row, we calculate its string length $w$, and update the value of $ans[j]$ to be $\\max(ans[j], w)$.\n\nAfter traversing all rows, each element in the array $ans$ is the width of the corresponding column.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(\\log M)$. Where $m$ and $n$ are the number of rows and columns in the matrix respectively, and $M$ is the absolute value of the maximum element in the matrix." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(\\log M)" }, { "problem_id": 2640, "explanations": { "1": "We use a variable $mx$ to record the maximum value of the first $i$ elements in the array $nums$, and use an array $ans[i]$ to record the score of the first $i$ elements in the array $nums$.\n\nNext, we traverse the array $nums$. For each element $nums[i]$, we update $mx$, i.e., $mx = \\max(mx, nums[i])$, and then update $ans[i]$. If $i = 0$, then $ans[i] = nums[i] + mx$, otherwise $ans[i] = nums[i] + mx + ans[i - 1]$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. Ignoring the space consumption of the answer array, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2641, "explanations": { "1": "We create a list $s$ to record the sum of the node values at each level of the binary tree, where $s[depth]$ represents the sum of the node values at the $depth$-th level (the root node is at level $0$).\n\nNext, we perform a DFS traversal to calculate the values in the array $s$. Then, we perform another DFS traversal to update the values of each node's children. The value of a child node is equal to the sum of the node values at its level minus the value of the child node and its sibling nodes.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree.", "2": "First, we update the root node's value to $0$, and use a queue $q$ to store all nodes at each level, initially enqueueing the root node.\n\nThen, we traverse the queue, calculate the sum $s$ of all child nodes' values at each level, then calculate the sum $sub$ of each child node and its sibling nodes' values, and then update each child node's value to $s - sub$.\n\nAfter the traversal ends, we return the root node.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2642, "explanations": { "1": "In the initialization function, we first use the adjacency matrix $g$ to store the edge weights of the graph, where $g_{ij}$ represents the edge weight from node $i$ to node $j$. If there is no edge between $i$ and $j$, the value of $g_{ij}$ is $\\infty$.\n\nIn the `addEdge` function, we update the value of $g_{ij}$ to $edge[2]$.\n\nIn the `shortestPath` function, we use Dijsktra's algorithm to find the shortest path from node $node1$ to node $node2$. Here, $dist[i]$ represents the shortest path from node $node1$ to node $i$, and $vis[i]$ indicates whether node $i$ has been visited. We initialize $dist[node1]$ to $0$, and the rest of $dist[i]$ are all $\\infty$. Then we iterate $n$ times, each time finding the current unvisited node $t$ such that $dist[t]$ is the smallest. Then we mark node $t$ as visited, and then update the value of $dist[i]$ to $min(dist[i], dist[t] + g_{ti})$. Finally, we return $dist[node2]$. If $dist[node2]$ is $\\infty$, it means that there is no path from node $node1$ to node $node2$, so we return $-1$.\n\nThe time complexity is $O(n^2 \\times q)$, and the space complexity is $O(n^2)$. Where $n$ is the number of nodes, and $q$ is the number of calls to the `shortestPath` function." }, "is_english": true, "time_complexity": "O(n^2 \\times q)", "space_complexity": "O(n^2)" }, { "problem_id": 2643, "explanations": { "1": "We initialize an array $\\textit{ans} = [0, 0]$ to store the index of the row with the most $1$s and the count of $1$s.\n\nThen, we iterate through each row of the matrix:\n\n- Compute the number of $1$s in the current row, denoted as $\\textit{cnt}$ (since the matrix contains only $0$s and $1$s, we can directly sum up the row).\n- If $\\textit{ans}[1] < \\textit{cnt}$, update $\\textit{ans} = [i, \\textit{cnt}]$.\n\nAfter finishing the iteration, we return $\\textit{ans}$.\n\nThe time complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns in the matrix, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(1)" }, { "problem_id": 2644, "explanations": { "1": "We can enumerate each element $div$ in $divisors$, and calculate how many elements in $nums$ can be divided by $div$, denoted as $cnt$.\n\n- If $cnt$ is greater than the current maximum divisibility score $mx$, then update $mx = cnt$, and update $ans = div$.\n- If $cnt$ equals $mx$ and $div$ is less than $ans$, then update $ans = div$.\n\nFinally, return $ans$.\n\nThe time complexity is $O(m \\times n)$, where $m$ and $n$ are the lengths of $nums$ and $divisors$ respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(1)" }, { "problem_id": 2645, "explanations": { "1": "We define the string $s$ as `\"abc\"`, and use pointers $i$ and $j$ to point to $s$ and $word$ respectively.\n\nIf $word[j] \\neq s[i]$, we need to insert $s[i]$, and we add $1$ to the answer; otherwise, it means that $word[j]$ can match with $s[i]$, and we move $j$ one step to the right.\n\nThen, we move $i$ one step to the right, i.e., $i = (i + 1) \\bmod 3$. We continue the above operations until $j$ reaches the end of the string $word$.\n\nFinally, we check whether the last character of $word$ is `'b'` or `'a'`. If it is, we need to insert `'c'` or `'bc'`, and we add $1$ or $2$ to the answer and return it.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $word$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2646, "explanations": { "1": "We can enumerate each element $div$ in $divisors$, and calculate how many elements in $nums$ can be divided by $div$, denoted as $cnt$.\n\n- If $cnt$ is greater than the current maximum divisibility score $mx$, then update $mx = cnt$, and update $ans = div$.\n- If $cnt$ equals $mx$ and $div$ is less than $ans$, then update $ans = div$.\n\nFinally, return $ans$.\n\nThe time complexity is $O(m \\times n)$, where $m$ and $n$ are the lengths of $nums$ and $divisors$ respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(1)" }, { "problem_id": 2647, "explanations": { "1": "We draw a graph to observe, and we can find that the first row only has one triangle and must be colored, and from the last row to the second row, the coloring scheme of every four rows is the same:\n\n1. The last row is colored at $(n, 1)$, $(n, 3)$, ..., $(n, 2n - 1)$.\n1. The $n - 1$ row is colored at $(n - 1, 2)$.\n1. The $n - 2$ row is colored at $(n - 2, 3)$, $(n - 2, 5)$, ..., $(n - 2, 2n - 5)$.\n1. The $n - 3$ row is colored at $(n - 3, 1)$.\n\n\"\"\n\nTherefore, we can color the first row according to the above rules, and then start from the last row, and color every four rows once until the second row ends.\n\n\"\"\n\nThe time complexity is $(n^2)$, where $n$ is the parameter given in the problem. Ignoring the space consumption of the answer array, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 2648, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2649, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2650, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2651, "explanations": { "1": "我们直接计算列车实际到站的时间,即为 $arrivalTime + delayedTime$,但是由于时间采用 24 小时制,所以我们需要对结果取模,即 $(arrivalTime + delayedTime) \\bmod 24$。\n\n时间复杂度 $O(1)$,空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 2652, "explanations": { "1": "We directly enumerate every number $x$ in $[1,..n]$, and if $x$ is divisible by $3$, $5$, and $7$, we add $x$ to the answer.\n\nAfter the enumeration, we return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the given integer. The space complexity is $O(1)$.", "2": "We define a function $f(x)$ to represent the sum of numbers in $[1,..n]$ that are divisible by $x$. There are $m = \\left\\lfloor \\frac{n}{x} \\right\\rfloor$ numbers that are divisible by $x$, which are $x$, $2x$, $3x$, $\\cdots$, $mx$, forming an arithmetic sequence with the first term $x$, the last term $mx$, and the number of terms $m$. Therefore, $f(x) = \\frac{(x + mx) \\times m}{2}$.\n\nAccording to the inclusion-exclusion principle, we can obtain the answer as:\n\n$$\nf(3) + f(5) + f(7) - f(3 \\times 5) - f(3 \\times 7) - f(5 \\times 7) + f(3 \\times 5 \\times 7)\n$$\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$.", "3": "" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2653, "explanations": { "1": "We notice that the range of elements in the array $nums$ is $[-50,50]$. Therefore, we can use an array of length $101$, denoted as $cnt$, to count the occurrences of each number in $[-50,50]$. Due to the presence of negative numbers, we can add $50$ to each number to make them all non-negative, so we can use the array $cnt$ to count the occurrences of each number.\n\nNext, we traverse the array $nums$, maintaining a sliding window of length $k$. The occurrence times of all elements in the window are recorded in the array $cnt$. Then we traverse the array $cnt$ to find the $x$-th smallest number, which is the beauty value of the current sliding window. If there is no $x$-th smallest number, then the beauty value is $0$.\n\nThe time complexity is $O(n \\times 50)$, and the space complexity is $O(100)$. Where $n$ is the length of the array $nums$.", "2": "We can use two priority queues (min-max heap) to maintain the elements in the current window, one priority queue stores the smaller $x$ elements in the current window, and the other priority queue stores the larger $k - x$ elements in the current window. We also need a delayed deletion dictionary `delayed` to record whether the elements in the current window need to be deleted.\n\nWe design a class `MedianFinder` to maintain the elements in the current window. This class includes the following methods:\n\n- `add_num(num)`: Add `num` to the current window.\n- `find()`: Return the beauty value of the current window.\n- `remove_num(num)`: Remove `num` from the current window.\n- `prune(pq)`: If the top element of the heap is in the delayed deletion dictionary `delayed`, pop it from the top of the heap and subtract one from its delayed deletion count. If the delayed deletion count of the element is zero, delete it from the delayed deletion dictionary.\n- `rebalance()`: Balance the size of the two priority queues.\n\nIn the `add_num(num)` method, we first consider adding `num` to the smaller queue. If the count is greater than $x$ or `num` is less than or equal to the top element of the smaller queue, add `num` to the smaller queue; otherwise, add `num` to the larger queue. Then we call the `rebalance()` method to ensure that the number of elements in the smaller queue does not exceed $x$.\n\nIn the `remove_num(num)` method, we increase the delayed deletion count of `num` by one. Then we compare `num` with the top element of the smaller queue. If `num` is less than or equal to the top element of the smaller queue, update the size of the smaller queue and call the `prune()` method to ensure that the top element of the smaller queue is not in the delayed deletion dictionary. Otherwise, we update the size of the larger queue and call the `prune()` method to ensure that the top element of the larger queue is not in the delayed deletion dictionary.\n\nIn the `find()` method, if the size of the smaller queue is equal to $x$, return the top element of the smaller queue, otherwise return $0$.\n\nIn the `prune(pq)` method, if the top element of the heap is in the delayed deletion dictionary, pop it from the top of the heap and subtract one from its delayed deletion count. If the delayed deletion count of the element is zero, delete it from the delayed deletion dictionary.\n\nIn the `rebalance()` method, if the size of the smaller queue is greater than $x$, add the top element of the smaller queue to the larger queue and call the `prune()` method to ensure that the top element of the smaller queue is not in the delayed deletion dictionary. If the size of the smaller queue is less than $x$ and the size of the larger queue is greater than $0$, add the top element of the larger queue to the smaller queue and call the `prune()` method to ensure that the top element of the larger queue is not in the delayed deletion dictionary.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array `nums`.\n\nSimilar problems:\n\n- [480. Sliding Window Median](https://github.com/doocs/leetcode/blob/main/solution/0400-0499/0480.Sliding%20Window%20Median/README.md)" }, "is_english": true, "time_complexity": "O(n \\times 50)", "space_complexity": "O(100)" }, { "problem_id": 2654, "explanations": { "1": "We first count the number of $1$s in the array $nums$ as $cnt$. If $cnt \\gt 0$, then we only need $n - cnt$ operations to turn the entire array into $1$s.\n\nOtherwise, we need to first turn one element in the array into $1$, and then the minimum number of remaining operations is $n - 1$.\n\nConsider how to turn one element in the array into $1$ while minimizing the number of operations. In fact, we only need to find a minimum contiguous subarray interval $nums[i,..j]$ such that the greatest common divisor of all elements in the subarray is $1$, with the subarray length being $mi = \\min(mi, j - i + 1)$. Finally, our total number of operations is $n - 1 + mi - 1$.\n\nThe time complexity is $O(n \\times (n + \\log M))$ and the space complexity is $O(\\log M)$, where $n$ and $M$ are the length of the array $nums$ and the maximum value in the array $nums$, respectively." }, "is_english": true, "time_complexity": "O(n \\times (n + \\log M))", "space_complexity": "O(\\log M)" }, { "problem_id": 2655, "explanations": { "1": "We sort all intervals by their left endpoints in ascending order, then traverse all intervals from left to right, maintaining a variable $\\textit{last}$ to represent the rightmost endpoint that has been covered so far, initially $\\textit{last}=-1$.\n\nIf the left endpoint of the current interval is greater than $\\textit{last}+1$, it means $[\\textit{last}+1, l-1]$ is an uncovered interval, and we add it to the answer array. Then we update $\\textit{last}$ to the right endpoint of the current interval and continue traversing the next interval. After traversing all intervals, if $\\textit{last}+1 < n$, it means $[\\textit{last}+1, n-1]$ is an uncovered interval, and we add it to the answer array.\n\nFinally, we return the answer array.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$, where $n$ is the length of the array $\\textit{ranges}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 2656, "explanations": { "1": "We notice that to make the final score maximum, we should make each choice as large as possible. Therefore, we select the largest element $x$ in the array for the first time, $x+1$ for the second time, $x+2$ for the third time, and so on, until the $k$th time we select $x+k-1$. This way of selection ensures that the element selected each time is the largest in the current array, so the final score is also the largest. The answer is $k$ $x$ sum plus $0+1+2+\\cdots+(k-1)$, that is, $k \\times x + (k - 1) \\times k / 2$.\n\nTime complexity is $O(n)$, where $n$ is the length of the array. Space complexity is $O(1)$.", "2": "" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2657, "explanations": { "1": "We can use two arrays $cnt1$ and $cnt2$ to record the occurrence times of each element in arrays $A$ and $B$ respectively, and use an array $ans$ to record the answer.\n\nTraverse arrays $A$ and $B$, increment the occurrence times of $A[i]$ in $cnt1$, and increment the occurrence times of $B[i]$ in $cnt2$. Then enumerate $j \\in [1,n]$, calculate the minimum occurrence times of each element $j$ in $cnt1$ and $cnt2$, and accumulate them into $ans[i]$.\n\nAfter the traversal, return the answer array $ans$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ is the length of arrays $A$ and $B$.", "2": "We can use an array $vis$ of length $n+1$ to record the occurrence situation of each element in arrays $A$ and $B$, the initial value of array $vis$ is $1$. In addition, we use a variable $s$ to record the current number of common elements.\n\nNext, we traverse arrays $A$ and $B$, update $vis[A[i]] = vis[A[i]] \\oplus 1$, and update $vis[B[i]] = vis[B[i]] \\oplus 1$, where $\\oplus$ represents XOR operation.\n\nIf at the current position, the element $A[i]$ has appeared twice (i.e., it has appeared in both arrays $A$ and $B$), then the value of $vis[A[i]]$ will be $1$, and we increment $s$. Similarly, if the element $B[i]$ has appeared twice, then the value of $vis[B[i]]$ will be $1$, and we increment $s$. Then add the value of $s$ to the answer array $ans$.\n\nAfter the traversal, return the answer array $ans$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of arrays $A$ and $B$.", "3": "Since the elements of arrays $A$ and $B$ are in the range $[1, n]$ and do not exceed $50$, we can use an integer $x$ and an integer $y$ to represent the occurrence of each element in arrays $A$ and $B$, respectively. Specifically, we use the $i$-th bit of integer $x$ to indicate whether element $i$ has appeared in array $A$, and the $i$-th bit of integer $y$ to indicate whether element $i$ has appeared in array $B$.\n\nThe time complexity of this solution is $O(n)$, where $n$ is the length of arrays $A$ and $B$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 2658, "explanations": { "1": "According to the problem description, we only need to find the number of fish in each connected water area and then take the maximum value. Therefore, we can use the depth-first search method to solve this problem.\n\nWe define a function $dfs(i, j)$, which indicates the maximum number of fish that can be caught starting from the cell in the $i$-th row and the $j$-th column. The execution logic of the function $dfs(i, j)$ is as follows:\n\nWe use a variable $cnt$ to record the number of fish in the current cell, and then set the number of fish in the current cell to $0$, indicating that it has been fished. Then we traverse the four directions of the current cell, if the cell $(x, y)$ in a certain direction is in the grid and is a water cell, then we recursively call the $dfs(x, y)$ function and add the return value to $cnt$. Finally, return $cnt$.\n\nIn the main function, we traverse all the cells $(i, j)$. If the current cell is a water cell, we call the $dfs(i, j)$ function, take the maximum value of the return value as the answer, and return it.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. where $m$ and $n$ are the number of rows and columns of the grid graph respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 2659, "explanations": { "1": "First, we use a hash table $pos$ to record the position of each element in array $nums$. Then, we sort array $nums$. The initial answer is the position of the minimum element in array $nums$ plus 1, which is $ans = pos[nums[0]] + 1$.\n\nNext, we traverse the sorted array $nums$, the indexes of the two adjacent elements $a$ and $b$ are $i = pos[a]$, $j = pos[b]$. The number of operations needed to move the second element $b$ to the first position of the array and delete it is equal to the interval between the two indexes, minus the number of indexes deleted between the two indexes, and add the number of operations to the answer. We can use a Fenwick tree or an ordered list to maintain the deleted indexes between two indexes, so that we can find the number of deleted indexes between two indexes in $O(\\log n)$ time. Note that if $i \\gt j$, then we need to increase $n - k$ operations, where $k$ is the current position.\n\nAfter the traversal is over, return the number of operations $ans$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the length of array $nums$.", "2": "" }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2660, "explanations": { "1": "We can define a function $f(arr)$ to calculate the scores of the two players, denoted as $a$ and $b$, respectively, and then return the answer based on the relationship between $a$ and $b$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2661, "explanations": { "1": "We use a hash table $idx$ to record the position of each element in the matrix $mat$, that is $idx[mat[i][j]] = (i, j)$, and define two arrays $row$ and $col$ to record the number of colored elements in each row and each column respectively.\n\nTraverse the array $arr$. For each element $arr[k]$, we find its position $(i, j)$ in the matrix $mat$, and then add $row[i]$ and $col[j]$ by one. If $row[i] = n$ or $col[j] = m$, it means that the $i$-th row or the $j$-th column has been colored, so $arr[k]$ is the element we are looking for, and we return $k$.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Here $m$ and $n$ are the number of rows and columns of the matrix $mat$ respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 2662, "explanations": { "1": "We can find that for each coordinate $(x, y)$ we visit, suppose the minimum cost from the start point to $(x, y)$ is $d$. If we choose to move directly to $(targetX, targetY)$, then the total cost is $d + |x - targetX| + |y - targetY|$. If we choose to go through a special path $(x_1, y_1) \\rightarrow (x_2, y_2)$, then we need to spend $|x - x_1| + |y - y_1| + cost$ to move from $(x, y)$ to $(x_2, y_2)$.\n\nTherefore, we can use Dijkstra algorithm to find the minimum cost from the start point to all points, and then choose the smallest one from them.\n\nWe define a priority queue $q$, each element in the queue is a triple $(d, x, y)$, which means that the minimum cost from the start point to $(x, y)$ is $d$. Initially, we add $(0, startX, startY)$ to the queue.\n\nIn each step, we take out the first element $(d, x, y)$ in the queue, at this time we can update the answer, that is $ans = \\min(ans, d + dist(x, y, targetX, targetY))$. Then we enumerate all special paths $(x_1, y_1) \\rightarrow (x_2, y_2)$ and add $(d + dist(x, y, x_1, y_1) + cost, x_2, y_2)$ to the queue.\n\nFinally, when the queue is empty, we can get the answer.\n\nThe time complexity is $O(n^2 \\times \\log n)$, and the space complexity is $O(n^2)$. Where $n$ is the number of special paths." }, "is_english": true, "time_complexity": "O(n^2 \\times \\log n)", "space_complexity": "O(n^2)" }, { "problem_id": 2663, "explanations": { "1": "We can find that a palindrome string of length $2$ must have two adjacent characters equal; and a palindrome string of length $3$ must have two characters at the beginning and end equal. Therefore, a beautiful string does not contain any palindrome substring of length $2$ or longer, which means that each character in the string is different from its previous two adjacent characters.\n\nWe can greedily search backwards from the last index of the string, find an index $i$ such that the character at index $i$ can be replaced by a slightly larger character, while ensuring that it is different from its two previous adjacent characters.\n\n- If such an index $i$ is found, then we replace $s[i]$ with $c$, and replace the characters from $s[i+1]$ to $s[n-1]$ with the characters in the first $k$ characters of the alphabet in the order of the minimum dictionary that are not the same as the previous two adjacent characters. After the replacement is completed, we obtain a beautiful string that is the smallest in the dictionary and greater than $s$.\n- If such an index $i$ cannot be found, then we cannot construct a beautiful string greater than $s$ in dictionary order, so return an empty string.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2664, "explanations": { "1": "We create a two-dimensional array $g$, used to record the knight's movement order, initially $g[r][c] = -1$, and all other positions are set to $-1$ as well. Additionally, we need a variable $ok$ to record whether a solution has been found.\n\nNext, we start depth-first search from $(r, c)$. Each time we search position $(i, j)$, we first check if $g[i][j]$ equals $m \\times n - 1$. If so, it means we have found a solution, then we set $ok$ to `true` and return. Otherwise, we enumerate the knight's eight possible movement directions to position $(x, y)$. If $0 \\leq x < m$, $0 \\leq y < n$, and $g[x][y]=-1$, then we update $g[x][y]$ to $g[i][j]+1$, and recursively search position $(x, y)$. If after the search, the variable $ok$ is `true`, we return directly. Otherwise, we reset $g[x][y]$ to $-1$ and continue searching in other directions.\n\nFinally, return the two-dimensional array $g$.\n\nThe time complexity is $O(8^{m \\times n})$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the integers given in the problem." }, "is_english": true, "time_complexity": "O(8^{m \\times n})", "space_complexity": "O(m \\times n)" }, { "problem_id": 2665, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2666, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2667, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2668, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2669, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2670, "explanations": { "1": "We can preprocess a suffix array $suf$, where $suf[i]$ represents the number of distinct elements in the suffix $nums[i, ..., n - 1]$. During the preprocessing, we use a hash table $s$ to maintain the elements that have appeared in the suffix, so we can query the number of distinct elements in the suffix in $O(1)$ time.\n\nAfter preprocessing the suffix array $suf$, we clear the hash table $s$, and then traverse the array $nums$ again, using the hash table $s$ to maintain the elements that have appeared in the prefix. The answer at position $i$ is the number of distinct elements in $s$ minus $suf[i + 1]$, that is, $s.size() - suf[i + 1]$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2671, "explanations": { "1": "We define two hash tables, where $cnt$ is used to record the occurrence count of each number, and $freq$ is used to record the count of numbers with each frequency.\n\nFor the `add` operation, we directly decrement the value corresponding to $cnt[number]$ in the hash table $freq$, then increment $cnt[number]$, and finally increment the value corresponding to $cnt[number]$ in $freq$.\n\nFor the `deleteOne` operation, we first check if $cnt[number]$ is greater than zero. If it is, we decrement the value corresponding to $cnt[number]$ in the hash table $freq$, then decrement $cnt[number]$, and finally increment the value corresponding to $cnt[number]$ in $freq$.\n\nFor the `hasFrequency` operation, we directly return whether $freq[frequency]$ is greater than zero.\n\nIn terms of time complexity, since we use hash tables, the time complexity of each operation is $O(1)$. The space complexity is $O(n)$, where $n$ is the number of distinct numbers." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(n)" }, { "problem_id": 2672, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2673, "explanations": { "1": "According to the problem description, we need to calculate the minimum number of increments to make the path values from the root node to each leaf node equal.\n\nThe path values from the root node to each leaf node being equal is actually equivalent to the path values from any node as the root of a subtree to each leaf node of that subtree being equal.\n\nWhy is that? We can prove it by contradiction. Suppose there is a node $x$, and the path values from it as the root of a subtree to some leaf nodes are not equal. Then there exists a situation where the path values from the root node to the leaf nodes are not equal, which contradicts the condition \"the path values from the root node to each leaf node are equal\". Therefore, the assumption is not valid, and the path values from any node as the root of a subtree to each leaf node of that subtree are equal.\n\nWe can start from the bottom of the tree and calculate the number of increments layer by layer. For each non-leaf node, we can calculate the path values of its left and right child nodes. The number of increments is the difference between the two path values, and then update the path values of the left and right child nodes to the larger one of the two.\n\nFinally, return the total number of increments.\n\nThe time complexity is $O(n)$, where $n$ is the number of nodes. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2674, "explanations": { "1": "We define two pointers $a$ and $b$, both initially pointing to the head of the linked list. Each iteration, pointer $a$ moves forward one step, and pointer $b$ moves forward two steps, until pointer $b$ reaches the end of the linked list. At this point, pointer $a$ points to half of the linked list nodes, and we break the linked list from pointer $a$, thus obtaining the head nodes of the two linked lists.\n\nThe time complexity is $O(n)$, where $n$ is the length of the linked list. It requires one traversal of the linked list. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2675, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2676, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2677, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2678, "explanations": { "1": "We can traverse each string $x$ in `details` and convert the $12$th and $13$th characters (indexed at $11$ and $12$) of $x$ to integers, and check if they are greater than $60$. If so, we add one to the answer.\n\nAfter the traversal, we return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of `details`. The space complexity is $O(1)`." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2679, "explanations": { "1": "我们可以先遍历矩阵的每一行,将每一行排序。\n\n接下来,遍历矩阵的每一列,找到每一列的最大值,将这些最大值相加即可。\n\n时间复杂度 $O(m \\times n \\times \\log n)$,空间复杂度 $(\\log n)$。其中 $m$ 和 $n$ 分别是矩阵的行数和列数。" }, "is_english": false, "time_complexity": "O(m \\times n \\times \\log n)", "space_complexity": null }, { "problem_id": 2680, "explanations": { "1": "We notice that in order to maximize the answer, we should apply $k$ times of bitwise OR to the same number.\n\nFirst, we preprocess the suffix OR value array $suf$ of the array $nums$, where $suf[i]$ represents the bitwise OR value of $nums[i], nums[i + 1], \\cdots, nums[n - 1]$.\n\nNext, we traverse the array $nums$ from left to right, and maintain the current prefix OR value $pre$. For the current position $i$, we perform $k$ times of bitwise left shift on $nums[i]$, i.e., $nums[i] \\times 2^k$, and perform bitwise OR operation with $pre$ to obtain the intermediate result. Then, we perform bitwise OR operation with $suf[i + 1]$ to obtain the maximum OR value with $nums[i]$ as the last number. By enumerating all possible positions $i$, we can obtain the final answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2681, "explanations": { "1": "We notice that the problem involves the maximum and minimum values of a subsequence, and the order of elements in the array does not affect the final result. Therefore, we can sort the array first.\n\nNext, we enumerate each element as the minimum value of the subsequence. Let's denote each element of the array as $a_1, a_2, \\cdots, a_n$. The contribution of the subsequence with $a_i$ as the minimum value is:\n\n$$\na_i \\times (a_{i}^{2} + a_{i+1}^2 + 2 \\times a_{i+2}^2 + 4 \\times a_{i+3}^2 + \\cdots + 2^{n-i-1} \\times a_n^2)\n$$\n\nWe notice that each $a_i$ will be multiplied by $a_i^2$, which we can directly add to the answer. For the remaining part, we can maintain it with a variable $p$, initially set to $0$.\n\nThen, we enumerate $a_i$ from right to left. Each time, we add $a_i \\times p$ to the answer, and then set $p = p \\times 2 + a_i^2$.\n\nAfter enumerating all $a_i$, return the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 2682, "explanations": { "1": "We use an array `vis` to record whether each friend has received the ball, initially, all friends have not received the ball. Then, we simulate the game process according to the rules described in the problem statement until a friend receives the ball for the second time.\n\nIn the simulation process, we use two variables $i$ and $p$ to represent the current friend holding the ball and the current passing step length, respectively. Initially, $i=0, p=1$, indicating the first friend receives the ball. Each time the ball is passed, we update $i$ to $(i+p \\times k) \\bmod n$, representing the next friend's number to receive the ball, and then update $p$ to $p+1$, representing the step length for the next pass. The game ends when a friend receives the ball for the second time.\n\nFinally, we iterate through the array `vis` and add the numbers of friends who have not received the ball to the answer array.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of friends." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2683, "explanations": { "1": "Let's assume the original binary array is $a$, and the derived array is $b$. Then, we have:\n\n$$\nb_0 = a_0 \\oplus a_1 \\\\\nb_1 = a_1 \\oplus a_2 \\\\\n\\cdots \\\\\nb_{n-1} = a_{n-1} \\oplus a_0\n$$\n\nSince the XOR operation is commutative and associative, we get:\n\n$$\nb_0 \\oplus b_1 \\oplus \\cdots \\oplus b_{n-1} = (a_0 \\oplus a_1) \\oplus (a_1 \\oplus a_2) \\oplus \\cdots \\oplus (a_{n-1} \\oplus a_0) = 0\n$$\n\nTherefore, as long as the XOR sum of all elements in the derived array is $0$, there must exist an original binary array that meets the requirements.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2684, "explanations": { "1": "We define a queue $q$, and initially add all the row coordinates of the first column to the queue.\n\nNext, we start from the first column and traverse column by column. For each column, we take out all the row coordinates in the queue one by one. For each row coordinate $i$, we get all possible row coordinates $k$ of the next column, and satisfy $grid[i][j] < grid[k][j + 1]$, and add these row coordinates to a new set $t$. If $t$ is empty, it means that we cannot continue to move, so we return the current column number. Otherwise, we assign $t$ to $q$ and continue to traverse the next column.\n\nFinally, if we have traversed all the columns, it means that we can move to the last column, so we return $n - 1$.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m)$. Where $m$ and $n$ are the number of rows and columns in the matrix, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m)" }, { "problem_id": 2685, "explanations": { "1": "我们先根据题目给定的边建立一个邻接表 $g$,其中 $g[i]$ 表示顶点 $i$ 的邻接点集合。\n\n然后我们从 $0$ 开始遍历所有顶点,如果当前顶点没有被访问过,我们就从当前顶点开始进行深度优先搜索,统计当前连通分量的顶点数 $x$ 和边数 $y$。如果 $\\frac{x(x-1)}{2} = y$,那么当前连通分量就是完全连通分量,我们将答案加一。\n\n最后我们返回答案即可。\n\n时间复杂度 $O(n + m)$,空间复杂度 $O(n + m)$。其中 $n$ 和 $m$ 分别是顶点数和边数。", "2": "Problems needed to solve:\n\n1. How do we maintain the link state between each node and the others? 如\n2. How can one determine whether multiple points form a connected graph?\n\nFor the first one: we can maintain each node's connection set(including itself).\n\nFor the second one: After solving the first one, we can see:\n\n- the node itself includes every node in the connected graph(including itself).\n- and only connected to the nodes in the connected graph.\n\nTake example 1 to explain:\n\n- Node 5's connected node is itself, so it is a connected graph.\n- Node 0's connected 0, 1, 2. Same as nodes 1, 2.\n- Nodes 3 and 4 also include themselves and each other." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(n + m)" }, { "problem_id": 2686, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2687, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2688, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2689, "explanations": { "1": "我们可以使用深度优先搜索的方法,定义一个函数 $dfs(root)$,表示从根节点开始搜索,返回以 $root$ 为根节点的子树的字符串。那么答案就是 $dfs(root)[k-1]$。\n\n函数 $dfs(root)$ 的执行逻辑如下:\n\n- 如果 $root$ 为空,返回空字符串;\n- 如果 $root$ 是叶子节点,返回 $root.val$;\n- 否则,返回 $dfs(root.left) + dfs(root.right)$。\n\n时间复杂度 $O(n^2)$,空间复杂度 $O(n)$。其中 $n$ 是树中节点的个数。" }, "is_english": false, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 2690, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2691, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2692, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2693, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2694, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2695, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2696, "explanations": { "1": "We traverse the string $s$. For the current character $c$ we are traversing, if the stack is not empty and the top element of the stack $top$ can form $AB$ or $CD$ with $c$, then we pop the top element of the stack, otherwise we push $c$ into the stack.\n\nThe number of remaining elements in the stack is the length of the final string.\n\n> In implementation, we can pre-place an empty character in the stack, so there is no need to judge whether the stack is empty when traversing the string. Finally, we can return the size of the stack minus one.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the string $s$.", "2": "" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2697, "explanations": { "1": "We use two pointers $i$ and $j$ to point to the beginning and end of the string, initially $i = 0$, $j = n - 1$.\n\nNext, each time we greedily modify $s[i]$ and $s[j]$ to their smaller value to make them equal. Then we move $i$ one step forward and $j$ one step backward, and continue this process until $i \\ge j$. At this point, we have obtained the smallest palindrome string.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2698, "explanations": { "1": "We enumerate $i$, where $1 \\leq i \\leq n$. For each $i$, we split the decimal representation string of $x = i^2$, and then check whether it meets the requirements of the problem. If it does, we add $x$ to the answer.\n\nAfter the enumeration ends, we return the answer.\n\nThe time complexity is $O(n^{1 + 2 \\log_{10}^2})$, and the space complexity is $O(\\log n)$, where $n$ is the given positive integer." }, "is_english": true, "time_complexity": "O(n^{1 + 2 \\log_{10}^2})", "space_complexity": "O(\\log n)" }, { "problem_id": 2699, "explanations": { "1": "First, we ignore the edges with a weight of $-1$ and use Dijkstra's algorithm to find the shortest distance $d$ from $source$ to $destination$.\n\n- If $d < target$, it means there is a shortest path composed entirely of positive weight edges. No matter how we modify the edges with a weight of $-1$, we cannot make the shortest distance from $source$ to $destination$ equal to $target$. Therefore, there is no modification scheme that satisfies the problem, and we can return an empty array.\n\n- If $d = target$, it means there is a shortest path composed entirely of positive weight edges, and its length is $target$. In this case, we can modify all edges with a weight of $-1$ to the maximum value $2 \\times 10^9$.\n\n- If $d > target$, we can try to add an edge with a weight of $-1$ to the graph, set the weight of the edge to $1$, and then use Dijkstra's algorithm again to find the shortest distance $d$ from $source$ to $destination$.\n - If the shortest distance $d \\leq target$, it means that after adding this edge, the shortest path can be shortened, and the shortest path must pass through this edge. Then we only need to change the weight of this edge to $target-d+1$ to make the shortest path equal to $target$. Then we can modify the remaining edges with a weight of $-1$ to the maximum value $2 \\times 10^9$.\n - If the shortest distance $d > target$, it means that after adding this edge, the shortest path will not be shortened. Then we greedily keep the weight of this edge as $-1$ and continue to try to add the remaining edges with a weight of $-1$.\n\nThe time complexity is $O(n^3)$, and the space complexity is $O(n^2)$, where $n$ is the number of points in the graph." }, "is_english": true, "time_complexity": "O(n^3)", "space_complexity": "O(n^2)" }, { "problem_id": 2700, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2701, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2702, "explanations": { "1": "We notice that if an operation count $t$ can make all numbers less than or equal to $0$, then for any $t' > t$, the operation count $t'$ can also make all numbers less than or equal to $0$. Therefore, we can use binary search to find the minimum operation count.\n\nWe define the left boundary of the binary search as $l=0$, and the right boundary as $r=\\max(nums)$. Each time we perform a binary search, we find the middle value $mid=\\lfloor\\frac{l+r}{2}\\rfloor$, and then determine whether there exists an operation method that does not exceed $mid$ and makes all numbers less than or equal to $0$. If it exists, we update the right boundary $r = mid$, otherwise, we update the left boundary" }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 2703, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2704, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2705, "explanations": { "1": "If `obj` is not an object or is null, the function will return it as is, because there's no need to check for keys in non-object values.\n\nIf `obj` is an array, it will use `obj.filter(Boolean)` to filter out falsy values (like `null`, `undefined`, `false`, 0, \"\"), then use `map(compactObject)` to recursively call `compactObject` on each element. This ensures that nested arrays are also compacted.\n\nIf `obj` is an object, it will create a new empty object `compactedObj`. It will iterate over all keys of `obj`, and for each key, it will recursively call `compactObject` on the corresponding value, then store the result in the value variable. If the value is truthy (i.e., not falsy), it will assign it to the compacted object with the corresponding key.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2706, "explanations": { "1": "We can sort the prices of the chocolates in ascending order, and then add the first two prices to get the minimum cost $cost$ of buying two chocolates. If this cost is greater than the money we have, then we return `money`. Otherwise, we return `money - cost`.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Where $n$ is the length of the array `prices`.", "2": "We can find the two smallest prices in one pass, and then calculate the cost.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array `prices`. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 2707, "explanations": { "1": "We can use a hash table $ss$ to record all words in the dictionary, which allows us to quickly determine whether a string is in the dictionary.\n\nNext, we define $f[i]$ to represent the minimum number of extra characters in the first $i$ characters of string $s$, initially $f[0] = 0$.\n\nWhen $i \\ge 1$, the $i$th character $s[i - 1]$ can be an extra character, in which case $f[i] = f[i - 1] + 1$. If there exists an index $j \\in [0, i - 1]$ such that $s[j..i)$ is in the hash table $ss$, then we can take $s[j..i)$ as a word, in which case $f[i] = f[j]$.\n\nIn summary, we can get the state transition equation:\n\n$$\nf[i] = \\min \\{ f[i - 1] + 1, \\min_{j \\in [0, i - 1]} f[j] \\}\n$$\n\nwhere $i \\ge 1$, and $j \\in [0, i - 1]$ and $s[j..i)$ is in the hash table $ss$.\n\nThe final answer is $f[n]$.\n\nThe time complexity is $O(n^3 + L)$, and the space complexity is $O(n + L)$. Here, $n$ is the length of string $s$, and $L$ is the sum of the lengths of all words in the dictionary.", "2": "We can use a trie to optimize the time complexity of Solution 1.\n\nSpecifically, we first insert each word in the dictionary into the trie $root$ in reverse order, then we define $f[i]$ to represent the minimum number of extra characters in the first $i$ characters of string $s$, initially $f[0] = 0$.\n\nWhen $i \\ge 1$, the $i$th character $s[i - 1]$ can be an extra character, in which case $f[i] = f[i - 1] + 1$. We can also enumerate the index $j$ in reverse order in the range $[0..i-1]$, and determine whether $s[j..i)$ is in the trie $root$. If it exists, then we can take $s[j..i)$ as a word, in which case $f[i] = f[j]$.\n\nThe time complexity is $O(n^2 + L)$, and the space complexity is $O(n + L \\times |\\Sigma|)$. Here, $n$ is the length of string $s$, and $L$ is the sum of the lengths of all words in the dictionary. Additionally, $|\\Sigma|$ is the size of the character set. In this problem, the character set is lowercase English letters, so $|\\Sigma| = 26$." }, "is_english": true, "time_complexity": "O(n^3 + L)", "space_complexity": "O(n + L)" }, { "problem_id": 2708, "explanations": { "1": "The problem is actually to find the maximum product of all subsets. Since the length of the array does not exceed $13$, we can consider using the method of binary enumeration.\n\nWe enumerate all subsets in the range of $[1, 2^n)$, and for each subset, we calculate its product, and finally return the maximum value.\n\nThe time complexity is $O(2^n \\times n)$, where $n$ is the length of the array. The space complexity is $O(1)$.", "2": "First, we can sort the array. Based on the characteristics of the array, we can draw the following conclusions:\n\n- If there is only one element in the array, then the maximum strength value is this element.\n- If there are two or more elements in the array, and $nums[1] = nums[n - 1] = 0$, then the maximum strength value is $0$.\n- Otherwise, we traverse the array from small to large. If the current element is less than $0$ and the next element is also less than $0$, then we multiply these two elements and accumulate the product into the answer. Otherwise, if the current element is less than or equal to $0$, we skip it directly. If the current element is greater than $0$, we multiply this element into the answer. Finally, we return the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(2^n \\times n)", "space_complexity": "O(1)" }, { "problem_id": 2709, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2710, "explanations": { "1": "We can traverse the string from the end to the beginning, stopping when we encounter the first character that is not `0`. Then, we return the substring from the beginning to this character.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string. Ignoring the space consumed by the answer string, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2711, "explanations": { "1": "We can simulate the process described in the problem statement, calculating the number of distinct values on the top-left diagonal $tl$ and the bottom-right diagonal $br$ for each cell, then compute their difference $|tl - br|$.\n\nThe time complexity is $O(m \\times n \\times \\min(m, n))$, and the space complexity is $O(m \\times n)$." }, "is_english": true, "time_complexity": "O(m \\times n \\times \\min(m, n))", "space_complexity": "O(m \\times n)" }, { "problem_id": 2712, "explanations": { "1": "According to the problem description, if $s[i] \\neq s[i - 1]$, an operation must be performed; otherwise, it's impossible to make all characters equal.\n\nWe can either choose to reverse all characters from $s[0..i-1]$, with a cost of $i$, or reverse all characters from $s[i..n-1]$, with a cost of $n - i$. We take the minimum of the two.\n\nBy iterating through the string $s$ and summing up the costs of all characters that need to be reversed, we can obtain the minimum cost.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2713, "explanations": { "1": "Based on the problem description, the value of the cells we move through in sequence must strictly increase. Therefore, we can use a hash table $g$ to record the positions of all cells corresponding to each value, and then traverse from the smallest to the largest value.\n\nDuring this process, we can maintain two arrays `rowMax` and `colMax`, which record the maximum increasing length of each row and column, respectively. Initially, all elements of these two arrays are $0$.\n\nFor all cell positions corresponding to each value, we traverse them in order of position. For each position $(i, j)$, we can calculate the maximum increasing length ending at that position as $1 + \\max(\\textit{rowMax}[i], \\textit{colMax}[j])$, update the answer, and then update `rowMax[i]` and `colMax[j]`.\n\nFinally, return the answer.\n\nThe time complexity is $O(m \\times n \\times \\log(m \\times n))$, and the space complexity is $O(m \\times n)$." }, "is_english": true, "time_complexity": "O(m \\times n \\times \\log(m \\times n))", "space_complexity": "O(m \\times n)" }, { "problem_id": 2714, "explanations": { "1": "First, we construct a graph $g$ based on the given edges, where $g[u]$ represents all neighboring nodes of node $u$ and their corresponding edge weights.\n\nThen, we use Dijkstra's algorithm to find the shortest path from node $s$ to node $d$. However, we need to make some modifications to Dijkstra's algorithm:\n\n- We need to record the shortest path length from each node $u$ to node $d$, but since we can cross at most $k$ edges, we need to record the shortest path length from each node $u$ to node $d$ and the number of edges crossed $t$, i.e., $dist[u][t]$ represents the shortest path length from node $u$ to node $d$ and the number of edges crossed is $t$.\n- We need to use a priority queue to maintain the current shortest path, but since we need to record the number of edges crossed, we need to use a triple $(dis, u, t)$ to represent the current shortest path, where $dis$ represents the current shortest path length, and $u$ and $t$ represent the current node and the number of edges crossed, respectively.\n\nFinally, we only need to return the minimum value in $dist[d][0..k]$.\n\nThe time complexity is $O(n^2 \\times \\log n)$, and the space complexity is $O(n \\times k)$, where $n$ represents the number of nodes and $k$ represents the maximum number of edges crossed." }, "is_english": true, "time_complexity": "O(n^2 \\times \\log n)", "space_complexity": "O(n \\times k)" }, { "problem_id": 2715, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2716, "explanations": { "1": "The problem can actually be transformed into finding the number of distinct characters in the string. Therefore, we only need to count the number of distinct characters in the string.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $\\textit{s}$. The space complexity is $O(|\\Sigma|)$, where $\\Sigma$ is the character set. In this case, it's lowercase English letters, so $|\\Sigma|=26$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 2717, "explanations": { "1": "We can first find the indices $i$ and $j$ of $1$ and $n$, respectively. Then, based on the relative positions of $i$ and $j$, we can determine the number of swaps required.\n\nIf $i < j$, the number of swaps required is $i + n - j - 1$. If $i > j$, the number of swaps required is $i + n - j - 2$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2718, "explanations": { "1": "Since the value of each row and column depends on the last modification, we can traverse all queries in reverse order and use hash tables $row$ and $col$ to record which rows and columns have been modified.\n\nFor each query $(t, i, v)$:\n\n- If $t = 0$, we check whether the $i$th row has been modified. If not, we add $v \\times (n - |col|)$ to the answer, where $|col|$ represents the size of $col$, and then add $i$ to $row$.\n- If $t = 1$, we check whether the $i$th column has been modified. If not, we add $v \\times (n - |row|)$ to the answer, where $|row|$ represents the size of $row$, and then add $i$ to $col$.\n\nFinally, return the answer.\n\nThe time complexity is $O(m)$, and the space complexity is $O(n)$. Here, $m$ represents the number of queries." }, "is_english": true, "time_complexity": "O(m)", "space_complexity": "O(n)" }, { "problem_id": 2719, "explanations": { "1": "The problem is actually asking for the number of integers in the range $[num1,..num2]$ whose digit sum is in the range $[min\\_sum,..max\\_sum]$. For this kind of range $[l,..r]$ problem, we can consider transforming it into finding the answers for $[1,..r]$ and $[1,..l-1]$, and then subtracting the latter from the former.\n\nFor the answer to $[1,..r]$, we can use digit DP to solve it. We design a function $dfs(pos, s, limit)$, which represents the number of schemes when we are currently processing the $pos$th digit, the digit sum is $s$, and whether the current number has an upper limit $limit$. Here, $pos$ is enumerated from high to low.\n\nFor $dfs(pos, s, limit)$, we can enumerate the value of the current digit $i$, and then recursively calculate $dfs(pos+1, s+i, limit \\bigcap i==up)$, where $up$ represents the upper limit of the current digit. If $limit$ is true, then $up$ is the upper limit of the current digit, otherwise $up$ is $9$. If $pos$ is greater than or equal to the length of $num$, then we can judge whether $s$ is in the range $[min\\_sum,..max\\_sum]$. If it is, return $1$, otherwise return $0$.\n\nThe time complexity is $O(10 \\times n \\times max\\_sum)$, and the space complexity is $O(n \\times max\\_sum)$. Here, $n$ represents the length of $num$.\n\nSimilar problems:\n\n- [2801. Count Stepping Numbers in Range](https://github.com/doocs/leetcode/blob/main/solution/2800-2899/2801.Count%20Stepping%20Numbers%20in%20Range/README_EN.md)" }, "is_english": true, "time_complexity": "O(10 \\times n \\times max\\_sum)", "space_complexity": "O(n \\times max\\_sum)" }, { "problem_id": 2720, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2721, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2722, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2723, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2724, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2725, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2726, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2727, "explanations": { "1": "我们可以遍历对象或数组,如果遍历到了第一个元素,就返回 `false`,否则返回 `true`。\n\n时间复杂度 $O(1)$,空间复杂度 $O(1)$。", "2": "" }, "is_english": false, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 2728, "explanations": { "1": "我们先循环 $k$ 次,每次打开当前房子的门,然后向左移动一格,循环结束后,所有房子的门都是打开的。\n\n然后,我们再循环左移,如果当前房子的门是打开的,就关闭它,房子数加一,继续左移,直到当前房子的门是关闭的,循环结束,返回房子数。\n\n时间复杂度 $O(k)$,其中 $k$ 为题目给定的整数。空间复杂度 $O(1)$。\n\n相似题目:\n\n- [2753. 计算一个环形街道上的房屋数量 🔒 II](https://github.com/doocs/leetcode/blob/main/solution/2700-2799/2753.Count%20Houses%20in%20a%20Circular%20Street%20II/README.md)" }, "is_english": false, "time_complexity": "O(k)", "space_complexity": "O(1)" }, { "problem_id": 2729, "explanations": { "1": "我们根据题目描述,将数字 $n$ 与 $2 \\times n$ 和 $3 \\times n$ 连接,得到字符串 $s$,然后判断 $s$ 是否包含数字 $1$ 到 $9$ 各一次且不包含任何 $0$ 即可。\n\n时间复杂度 $O(\\log n)$,空间复杂度 $O(\\log n)$。其中 $n$ 为题目给定的整数。", "2": "" }, "is_english": false, "time_complexity": "O(\\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 2730, "explanations": { "1": "We use two pointers to maintain a range $s[j..i]$ such that there is at most one pair of adjacent characters that are equal, initially $j = 0$, $i = 1$. Initialize the answer $ans = 1$.\n\nWe use $cnt$ to record the number of pairs of adjacent characters that are equal in the range. If $cnt > 1$, then we need to move the left pointer $j$ until $cnt \\le 1$. Each time, we update the answer as $ans = \\max(ans, i - j + 1)$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(1)$.", "2": "Since the problem only requires us to find the length of the longest semi-repetitive substring, each time the number of adjacent identical characters in the interval exceeds $1$, we can move the left pointer $l$ once, while the right pointer $r$ continues to move to the right. This ensures that the length of the substring does not decrease.\n\nFinally, the answer is $n - l$, where $n$ is the length of the string.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2731, "explanations": { "1": "After two robots collide, they will immediately change direction, which is equivalent to the two robots continuing to move in their original direction. Therefore, we traverse the array $nums$, and according to the instructions in the string $s$, we add or subtract $d$ from the position of each robot, and then sort the array $nums$.\n\nNext, we enumerate the position of each robot from small to large, and calculate the sum of the distances between the current robot and all robots in front, which is the answer.\n\nThe time complexity is $O(n \\times \\log n)$ and the space complexity is $O(n)$, where $n$ is the number of robots." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2732, "explanations": { "1": "We can consider the number of rows $k$ chosen for the answer from smallest to largest.\n\n- If $k = 1$, the maximum sum of each column is $0$. Therefore, there must be a row where all elements are $0$, otherwise, the condition cannot be met.\n- If $k = 2$, the maximum sum of each column is $1$. There must exist two rows, and the bitwise AND result of these two rows' elements is $0$, otherwise, the condition cannot be met.\n- If $k = 3$, the maximum sum of each column is also $1$. If the condition for $k = 2$ is not met, then the condition for $k = 3$ will definitely not be met either. Therefore, we do not need to consider any case where $k > 2$ and $k$ is odd.\n- If $k = 4$, the maximum sum of each column is $2$. This situation definitely occurs when the condition for $k = 2$ is not met, meaning that for any two selected rows, there exists at least one column with a sum of $2$. When choosing any 2 rows out of 4, there are a total of $C_4^2 = 6$ ways to choose, so there are at least $6$ columns with a sum of $2$. Since the number of columns $n \\le 5$, there must be at least one column with a sum greater than $2$, so the condition for $k = 4$ is also not met.\n- For $k > 4$ and $k$ being even, we can draw the same conclusion, that $k$ definitely does not meet the condition.\n\nIn summary, we only need to consider the cases of $k = 1$ and $k = 2$. That is, to check whether there is a row entirely composed of $0$s, or whether there exist two rows whose bitwise AND result is $0$.\n\nThe time complexity is $O(m \\times n + 4^n)$, and the space complexity is $O(2^n)$. Here, $m$ and $n$ are the number of rows and columns of the matrix, respectively." }, "is_english": true, "time_complexity": "O(m \\times n + 4^n)", "space_complexity": "O(2^n)" }, { "problem_id": 2733, "explanations": { "1": "First, we find the minimum and maximum values in the array, denoted as $mi$ and $mx$ respectively. Then, we traverse the array and find the first number that is not equal to $mi$ and not equal to $mx$, and return it.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$.", "2": "" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2734, "explanations": { "1": "We can traverse the string $s$ from left to right, find the position $i$ of the first character that is not 'a', and then find the position $j$ of the first 'a' character starting from $i$. We decrement each character in $s[i:j]$, and finally return the processed string.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2735, "explanations": { "1": "We consider enumerating the number of operations, and define $f[i][j]$ as the minimum cost after the $i$-th chocolate has undergone $j$ operations.\n\nFor the $i$-th chocolate:\n\n- If $j = 0$, i.e., no operation is performed, then $f[i][j] = nums[i]$.\n- If $0 < j \\leq n-1$, its minimum cost is the minimum cost within the index range $[i,.. (i - j + n) \\bmod n]$, i.e., $f[i][j] = \\min\\{nums[i], nums[i - 1], \\cdots, nums[(i - j + n) \\bmod n]\\}$, or it can be written as $f[i][j] = \\min\\{f[i][j - 1], nums[(i - j + n) \\bmod n]\\}$.\n- If $j \\ge n$, since when $j = n - 1$, all minimum costs have been covered, if $j$ continues to increase, the minimum cost will not change, but the increase in the number of operations will lead to an increase in the final cost, so we do not need to consider the case where $j \\ge n$.\n\nIn summary, we can get the state transition equation:\n\n$$\nf[i][j] =\n\\begin{cases}\nnums[i] ,& j = 0 \\\\\n\\min(f[i][j - 1], nums[(i - j + n) \\bmod n]) ,& 0 \\lt j \\leq n - 1\n\\end{cases}\n$$\n\nFinally, we only need to enumerate the number of operations $j$, calculate the minimum cost under each number of operations, and take the minimum value. That is, the answer is $\\min\\limits_{0 \\leq j \\leq n - 1} \\sum\\limits_{i = 0}^{n - 1} f[i][j] + x \\times j$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Where $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 2736, "explanations": { "1": "This problem belongs to the category of two-dimensional partial order problems.\n\nA two-dimensional partial order problem is defined as follows: given several pairs of points $(a_1, b_1)$, $(a_2, b_2)$, ..., $(a_n, b_n)$, and a defined partial order relation, now given a point $(a_i, b_i)$, we need to find the number/maximum value of point pairs $(a_j, b_j)$ that satisfy the partial order relation. That is:\n\n$$\n\\left(a_{j}, b_{j}\\right) \\prec\\left(a_{i}, b_{i}\\right) \\stackrel{\\text { def }}{=} a_{j} \\lesseqgtr a_{i} \\text { and } b_{j} \\lesseqgtr b_{i}\n$$\n\nThe general solution to two-dimensional partial order problems is to sort one dimension and use a data structure to handle the second dimension (this data structure is generally a binary indexed tree).\n\nFor this problem, we can create an array $nums$, where $nums[i]=(nums_1[i], nums_2[i])$, and then sort $nums$ in descending order according to $nums_1$. We also sort the queries $queries$ in descending order according to $x$.\n\nNext, we iterate through each query $queries[i] = (x, y)$. For the current query, we loop to insert the value of $nums_2$ for all elements in $nums$ that are greater than or equal to $x$ into the binary indexed tree. The binary indexed tree maintains the maximum value of $nums_1 + nums_2$ in the discretized $nums_2$ interval. Therefore, we only need to query the maximum value corresponding to the interval greater than or equal to the discretized $y$ in the binary indexed tree. Note that since the binary indexed tree maintains the prefix maximum value, we can insert $nums_2$ in reverse order into the binary indexed tree in the implementation.\n\nThe time complexity is $O((n + m) \\times \\log n + m \\times \\log m)$, and the space complexity is $O(n + m)$. Here, $n$ is the length of the array $nums$, and $m$ is the length of the array $queries$.\n\nSimilar problems:\n\n- [2940. Find Building Where Alice and Bob Can Meet](https://github.com/doocs/leetcode/blob/main/solution/2900-2999/2940.Find%20Building%20Where%20Alice%20and%20Bob%20Can%20Meet/README_EN.md)" }, "is_english": true, "time_complexity": "O((n + m) \\times \\log n + m \\times \\log m)", "space_complexity": "O(n + m)" }, { "problem_id": 2737, "explanations": { "1": "First, we construct an adjacency matrix $g$ based on the edge information provided in the problem, where $g[i][j]$ represents the distance from node $i$ to node $j$. If such an edge does not exist, then $g[i][j]$ is positive infinity.\n\nThen, we can use Dijkstra's algorithm to find the shortest distance from the starting point $s$ to all nodes, denoted as $dist$.\n\nFinally, we traverse all the marked nodes and find the marked node with the smallest distance. If the distance is positive infinity, we return $-1$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ is the number of nodes." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 2738, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2739, "explanations": { "1": "We can simulate the process of the truck's movement. Each time, it consumes 1 liter of fuel from the main fuel tank and travels 10 kilometers. Whenever the fuel in the main fuel tank is consumed by 5 liters, if there is fuel in the auxiliary fuel tank, 1 liter of fuel is transferred from the auxiliary fuel tank to the main fuel tank. The simulation continues until the fuel in the main fuel tank is exhausted.\n\nThe time complexity is $O(n + m)$, where $n$ and $m$ are the amounts of fuel in the main and auxiliary fuel tanks, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(1)" }, { "problem_id": 2740, "explanations": { "1": "The problem requires us to minimize the partition value. Therefore, we can sort the array and then take the minimum difference between two adjacent numbers.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 2741, "explanations": { "1": "We notice that the maximum length of the array in the problem does not exceed $14$. Therefore, we can use an integer to represent the current state, where the $i$-th bit is $1$ if the $i$-th number in the array has been selected, and $0$ if it has not been selected.\n\nWe define $f[i][j]$ as the number of schemes where the current selected integer state is $i$, and the index of the last selected integer is $j$. Initially, $f[0][0]=0$, and the answer is $\\sum_{j=0}^{n-1}f[2^n-1][j]$.\n\nConsidering $f[i][j]$, if only one number is currently selected, then $f[i][j]=1$. Otherwise, we can enumerate the index $k$ of the last selected number. If the numbers corresponding to $k$ and $j$ meet the requirements of the problem, then $f[i][j]$ can be transferred from $f[i \\oplus 2^j][k]$. That is:\n\n$$\nf[i][j]=\n\\begin{cases}\n1, & i=2^j\\\\\n\\sum_{k=0}^{n-1}f[i \\oplus 2^j][k], & i \\neq 2^j \\textit{ and nums}[j] \\textit{ and nums}[k] \\textit{ meet the requirements of the problem}\\\\\n\\end{cases}\n$$\n\nThe final answer is $\\sum_{j=0}^{n-1}f[2^n-1][j]$. Note that the answer may be very large, so we need to take the modulus of $10^9+7$.\n\nThe time complexity is $O(n^2 \\times 2^n)$, and the space complexity is $O(n \\times 2^n)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n^2 \\times 2^n)", "space_complexity": "O(n \\times 2^n)" }, { "problem_id": 2742, "explanations": { "1": "We can consider whether each wall is painted by a paid painter or a free painter. Design a function $dfs(i, j)$, which means that from the $i$th wall, and the current remaining free painter working time is $j$, the minimum cost of painting all the remaining walls. Then the answer is $dfs(0, 0)$.\n\nThe calculation process of function $dfs(i, j)$ is as follows:\n\n- If $n - i \\le j$, it means that there are no more walls than the free painter's working time, so the remaining walls are painted by the free painter, and the cost is $0$;\n- If $i \\ge n$, return $+\\infty$;\n- Otherwise, if the $i$th wall is painted by a paid painter, the cost is $cost[i]$, then $dfs(i, j) = dfs(i + 1, j + time[i]) + cost[i]$; if the $i$th wall is painted by a free painter, the cost is $0$, then $dfs(i, j) = dfs(i + 1, j - 1)$.\n\nNote that the parameter $j$ may be less than $0$. Therefore, in the actual coding process, except for the $Python$ language, we add an offset $n$ to $j$ so that the range of $j$ is $[0, 2n]$.\n\nTime complexity $O(n^2)$, space complexity $O(n^2)$. Where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 2743, "explanations": { "1": "We use two pointers $j$ and $i$ to represent the left and right boundaries of the current substring, and an array $cnt$ of length $26$ to count the occurrence of each character in the current substring. We traverse the string from left to right. Each time we traverse to position $i$, we increase the occurrence of $s[i]$, and then check whether $s[i]$ appears at least twice. If so, we need to decrease the occurrence of $s[j]$ and move $j$ one step to the right, until the occurrence of $s[i]$ does not exceed once. In this way, we get the length of the longest special substring ending with $s[i]$, which is $i - j + 1$, so the number of special substrings ending with $s[i]$ is $i - j + 1$. Finally, we add up the number of special substrings ending at each position to get the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(C)$. Here, $n$ is the length of the string $s$, and $C$ is the size of the character set. In this problem, the character set consists of lowercase English letters, so $C = 26$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(C)" }, { "problem_id": 2744, "explanations": { "1": "We can use a hash table $cnt$ to store the number of occurrences of each reversed string in the array $words$.\n\nWe iterate through the array $words$. For each string $w$, we add the number of occurrences of its reversed string to the answer, then increment the count of $w$ by $1$.\n\nFinally, we return the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $words$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2745, "explanations": { "1": "We observe that the string 'AA' can only be followed by 'BB', and the string 'AB' can be placed at the beginning or end of the string. Therefore:\n\n- If $x < y$, we can first alternately place 'BBAABBAA..BB', placing a total of $x$ 'AA' and $x+1$ 'BB', then place the remaining $z$ 'AB', with a total length of $(x \\times 2 + z + 1) \\times 2$;\n- If $x > y$, we can first alternately place 'AABBAABB..AA', placing a total of $y$ 'BB' and $y+1$ 'AA', then place the remaining $z$ 'AB', with a total length of $(y \\times 2 + z + 1) \\times 2$;\n- If $x = y$, we only need to alternately place 'AABB', placing a total of $x$ 'AA' and $y$ 'BB', then place the remaining $z$ 'AB', with a total length of $(x + y + z) \\times 2$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 2746, "explanations": { "1": "We notice that when concatenating strings, the first and last characters of the string will affect the length of the concatenated string. Therefore, we design a function $dfs(i, a, b)$, which represents the minimum length of the concatenated string starting from the $i$-th string, and the first character of the previously concatenated string is $a$, and the last character is $b$.\n\nThe execution process of the function $dfs(i, a, b)$ is as follows:\n\n- If $i = n$, it means that all strings have been concatenated, return $0$;\n- Otherwise, we consider concatenating the $i$-th string to the end or the beginning of the already concatenated string, and get the lengths $x$ and $y$ of the concatenated string, then $dfs(i, a, b) = \\min(x, y) + |words[i]|$.\n\nTo avoid repeated calculations, we use the method of memoization search. Specifically, we use a three-dimensional array $f$ to store all the return values of $dfs(i, a, b)$. When we need to calculate $dfs(i, a, b)$, if $f[i][a][b]$ has been calculated, we directly return $f[i][a][b]$; otherwise, we calculate the value of $dfs(i, a, b)$ according to the above recurrence relation, and store it in $f[i][a][b]$.\n\nIn the main function, we directly return $|words[0]| + dfs(1, words[0][0], words[0][|words[0]| - 1])$.\n\nThe time complexity is $O(n \\times C^2)$, and the space complexity is $O(n \\times C^2)$. Where $C$ represents the maximum length of the string." }, "is_english": true, "time_complexity": "O(n \\times C^2)", "space_complexity": "O(n \\times C^2)" }, { "problem_id": 2747, "explanations": { "1": "We can sort all the queries by time from smallest to largest, and then process each query in chronological order.\n\nFor each query $q = (r, i)$, its window left boundary is $l = r - x$, and we need to count how many servers received requests within the window $[l, r]$. We use two pointers $j$ and $k$ to maintain the left and right boundaries of the window, initially $j = k = 0$. Each time, if the log time pointed by $k$ is less than or equal to $r$, we add it to the window, and then move $k$ to the right by one. If the log time pointed by $j$ is less than $l$, we remove it from the window, and then move $j$ to the right by one. During the movement, we need to count how many different servers are in the window, which can be implemented using a hash table. After the movement, the number of servers that did not receive requests in the current time interval is $n$ minus the number of different servers in the hash table.\n\nThe time complexity is $O(l \\times \\log l + m \\times \\log m + n)$, and the space complexity is $O(l + m)$. Here, $l$ and $n$ are the lengths of the arrays $\\textit{logs}$ and the number of servers, respectively, while $m$ is the length of the array $\\textit{queries}$." }, "is_english": true, "time_complexity": "O(l \\times \\log l + m \\times \\log m + n)", "space_complexity": "O(l + m)" }, { "problem_id": 2748, "explanations": { "1": "We can use an array $\\textit{cnt}$ of length $10$ to record the count of the first digit of each number.\n\nIterate through the array $\\textit{nums}$. For each number $x$, we enumerate each digit $y$ from $0$ to $9$. If $\\textit{cnt}[y]$ is not $0$ and $\\textit{gcd}(x \\mod 10, y) = 1$, then the answer is incremented by $\\textit{cnt}[y]$. Then, we increment the count of the first digit of $x$ by $1$.\n\nAfter the iteration, return the answer.\n\nThe time complexity is $O(n \\times (k + \\log M))$, and the space complexity is $O(k + \\log M)$. Here, $n$ is the length of the array $\\textit{nums}$, while $k$ and $M$ respectively represent the number of distinct numbers and the maximum value in the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times (k + \\log M))", "space_complexity": "O(k + \\log M)" }, { "problem_id": 2749, "explanations": { "1": "If we operate $k$ times, then the problem essentially becomes: determining whether $\\textit{num1} - k \\times \\textit{num2}$ can be split into the sum of $k$ $2^i$s.\n\nLet's assume $x = \\textit{num1} - k \\times \\textit{num2}$. Next, we discuss in categories:\n\n- If $x < 0$, then $x$ cannot be split into the sum of $k$ $2^i$s, because $2^i > 0$, which obviously has no solution;\n- If the number of $1$s in the binary representation of $x$ is greater than $k$, there is also no solution in this case;\n- Otherwise, for the current $k$, there must exist a splitting scheme.\n\nTherefore, we start enumerating $k$ from $1$. Once we find a $k$ that meets the condition, we can directly return the answer.\n\nThe time complexity is $O(\\log x)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log x)", "space_complexity": "O(1)" }, { "problem_id": 2750, "explanations": { "1": "Based on the problem description, we can draw a dividing line between two $1$s. Assuming the indices of the two $1$s are $j$ and $i$ respectively, then the number of different dividing lines that can be drawn is $i - j$. We find all the pairs of $j$ and $i$ that meet the condition, and then multiply all the $i - j$ together. If no dividing line can be found between two $1$s, it means there are no $1$s in the array, and the answer is $0$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2751, "explanations": { "1": "我们首先将机器人按照位置从小到大排序,用一个数组 $\\textit{idx}$ 存储排序后的机器人编号。然后我们使用一个栈来模拟碰撞过程:\n\n1. 从左到右遍历 $\\textit{idx}$ 中的机器人编号 $i$,如果 $directions[i]$ 是向右移动,则将 $i$ 入栈。\n2. 如果 $directions[i]$ 是向左移动,则与栈顶的向右移动的机器人发生碰撞,直到栈为空或当前机器人被移除。\n - 如果栈顶机器人健康度大于当前机器人,则当前机器人被移除,栈顶机器人健康度减 1。\n - 如果栈顶机器人健康度小于当前机器人,则栈顶机器人被移除,当前机器人健康度减 1,并继续与新的栈顶机器人发生碰撞。\n - 如果两者健康度相同,则两者都被移除。\n\n最后我们返回所有健康度大于 0 的机器人健康度。\n\n时间复杂度 $O(n \\times \\log n)$,空间复杂度 $O(n)$。其中 $n$ 是机器人的数量。" }, "is_english": false, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2752, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2753, "explanations": { "1": "We notice that there is at least one door open in the problem. We can first find one of the open doors.\n\nThen, we skip this open door and move to the right. Each time we move, we increment a counter by one. If we encounter an open door, we close it. The answer is the value of the counter the last time we encounter an open door.\n\nThe time complexity is $O(k)$, and the space complexity is $O(1)$.\n\nRelated problem:\n\n- [2728. Count Houses in a Circular Street](https://github.com/doocs/leetcode/blob/main/solution/2700-2799/2728.Count%20Houses%20in%20a%20Circular%20Street/README_EN.md)" }, "is_english": true, "time_complexity": "O(k)", "space_complexity": "O(1)" }, { "problem_id": 2754, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2755, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2756, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2757, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2758, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2759, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2760, "explanations": { "1": "We enumerate all $l$ in the range $[0,..n-1]$. If $nums[l]$ satisfies $nums[l] \\bmod 2 = 0$ and $nums[l] \\leq threshold$, then we start from $l+1$ to find the largest $r$ that meets the condition. At this time, the length of the longest odd-even subarray with $nums[l]$ as the left endpoint is $r - l$. We take the maximum of all $r - l$ as the answer.\n\nThe time complexity is $O(n^2)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$.", "2": "We notice that the problem actually divides the array into several disjoint subarrays that meet the condition. We only need to find the longest one among these subarrays. Therefore, when enumerating $l$ and $r$, we don't need to backtrack, we just need to traverse from left to right once.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(1)" }, { "problem_id": 2761, "explanations": { "1": "First, we pre-process all the prime numbers within the range of $n$, and record them in the array $primes$, where $primes[i]$ is `true` if $i$ is a prime number.\n\nNext, we enumerate $x$ in the range of $[2, \\frac{n}{2}]$. In this case, $y = n - x$. If both $primes[x]$ and $primes[y]$ are `true`, then $(x, y)$ is a pair of prime numbers, which is added to the answer.\n\nAfter the enumeration is complete, we return the answer.\n\nThe time complexity is $O(n \\log \\log n)$ and the space complexity is $O(n)$, where $n$ is the number given in the problem." }, "is_english": true, "time_complexity": "O(n \\log \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2762, "explanations": { "1": "We can use two pointers, $i$ and $j$, to maintain the left and right endpoints of the current subarray, and use an ordered list to maintain all elements in the current subarray.\n\nIterate through the array $nums$. For the current number $nums[i]$ we're iterating over, we add it to the ordered list. If the difference between the maximum and minimum values in the ordered list is greater than $2$, we then loop to move the pointer $i$ to the right, continuously removing $nums[i]$ from the ordered list, until the list is empty or the maximum difference between elements in the ordered list is not greater than $2$. At this point, the number of uninterrupted subarrays is $j - i + 1$, which we add to the answer.\n\nAfter the iteration, return the answer.\n\nThe time complexity is $O(n \\times \\log n)$ and the space complexity is $O(n)$, where $n$ is the length of the array $nums$.", "2": "" }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2763, "explanations": { "1": "We can first enumerate the left endpoint $i$ of the subarray. For each $i$, we enumerate the right endpoint $j$ of the subarray from small to large, and maintain all the elements in the current subarray with an ordered list. We also use a variable $cnt$ to maintain the unbalanced number of the current subarray.\n\nFor each number $nums[j]$, we find the first element $nums[k]$ in the ordered list that is greater than or equal to $nums[j]$, and the last element $nums[h]$ that is less than $nums[j]$:\n\n- If $nums[k]$ exists, and the difference between $nums[k]$ and $nums[j]$ is more than $1$, the unbalanced number increases by $1$;\n- If $nums[h]$ exists, and the difference between $nums[j]$ and $nums[h]$ is more than $1$, the unbalanced number increases by $1$;\n- If both $nums[k]$ and $nums[h]$ exist, then inserting the element $nums[j]$ between $nums[h]$ and $nums[k]$ will reduce the unbalanced number by $1$.\n\nThen, we add the unbalanced number of the current subarray to the answer, and continue the iteration until we finish iterating over all subarrays.\n\nThe time complexity is $O(n^2 \\times \\log n)$ and the space complexity is $O(n)$, where $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n^2 \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2764, "explanations": { "1": "我们先根据 $nodes$ 数据构建图 $g$,其中 $g[i]$ 表示节点 $i$ 的所有子节点。\n\n接下来,设计一个函数 $dfs(i)$,表示从节点 $i$ 开始进行先序遍历,用一个变量 $k$ 表示当前遍历到 $nodes$ 列表的第 $k$ 个节点,初始时 $k=0$。\n\n函数 $dfs(i)$ 的执行逻辑如下:\n\n- 如果 $i \\neq nodes[k][0]$,说明当前序列不是二叉树的先序遍历序列,返回 `false`。\n- 否则,我们将 $k$ 加 $1$,然后递归搜索 $i$ 的所有子节点,如果搜索过程中发现 `false`,那么提前返回 `false`,否则搜索结束,返回 `true`。\n\n在主函数中,我们调用 $dfs(nodes[0][0])$,如果返回值为 `true`,并且 $k = |nodes|$,那么 $nodes$ 序列是二叉树的先序遍历序列,返回 `true`,否则返回 `false`。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是 $nodes$ 中的节点数目。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2765, "explanations": { "1": "We can enumerate the left endpoint $i$ of the subarray, and for each $i$, we need to find the longest subarray that satisfies the condition. We can start traversing to the right from $i$, and each time we encounter adjacent elements whose difference does not satisfy the alternating condition, we find a subarray that satisfies the condition. We can use a variable $k$ to record whether the difference of the current element should be $1$ or $-1$. If the difference of the current element should be $-k$, then we take the opposite of $k$. When we find a subarray $nums[i..j]$ that satisfies the condition, we update the answer to $\\max(ans, j - i + 1)$.\n\nThe time complexity is $O(n^2)$, where $n$ is the length of the array. We need to enumerate the left endpoint $i$ of the subarray, and for each $i$, we need $O(n)$ time to find the longest subarray that satisfies the condition. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(1)" }, { "problem_id": 2766, "explanations": { "1": "Let's use a hash table $pos$ to record all stone positions. Initially, $pos$ contains all elements of $nums$. Then we iterate through $moveFrom$ and $moveTo$. Each time, we remove $moveFrom[i]$ from $pos$ and add $moveTo[i]$ to $pos$. Finally, we sort the elements in $pos$ and return.\n\nThe time complexity is $O(n \\times \\log n)$ and the space complexity is $O(n)$. Here, $n$ is the length of array $nums$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2767, "explanations": { "1": "Since the problem requires us to judge whether a string is the binary representation of a power of $5$, we might as well first preprocess all the powers of $5$ and record them in a hash table $ss$.\n\nNext, we design a function $dfs(i)$, which indicates the minimum number of cuts from the $i$-th character of the string $s$ to the end of the string. Then the answer is $dfs(0)$.\n\nThe calculation method of function $dfs(i)$ is as follows:\n\n- If $i \\geq n$, it means that all the characters have been processed, and the answer is $0$;\n- If $s[i] = 0$, it means that the current string contains leading $0$, which does not conform to the definition of a beautiful string, so the answer is infinite;\n- Otherwise, we enumerate the end position $j$ of the substring from $i$, and use $x$ to represent the decimal value of the substring $s[i..j]$. If $x$ is in the hash table $ss$, then we can take $s[i..j]$ as a beautiful substring, and the answer is $1 + dfs(j + 1)$. We need to enumerate all possible $j$ and take the minimum value of all answers.\n\nIn order to avoid repeated calculation, we can use the method of memory search.\n\nIn the main function, we first preprocess all the powers of $5$, and then call $dfs(0)$. If the return value is infinite, it means that the string $s$ cannot be divided into beautiful substrings, and the answer returns $-1$, otherwise, return the value of $dfs(0)$.\n\nTime complexity $O(n^2)$, space complexity $O(n)$. Where $n$ is the length of string $s$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 2768, "explanations": { "1": "For each $2 \\times 2$ submatrix, we can use its upper-left corner coordinate $(x, y)$ to represent it.\n\nFor each black cell $(x, y)$, its contribution to the 4 submatrices is $1$, namely the matrices $(x - 1, y - 1)$, $(x - 1, y)$, $(x, y - 1)$, $(x, y)$.\n\nTherefore, we traverse all the black cells, and then accumulate the number of black cells in each submatrix, recorded in the hash table $cnt$.\n\nFinally, we traverse all the values in $cnt$ (greater than $0$), count the number of times they appear, and record them in the answer array $ans$, while $ans[0]$ represents the number of submatrices without black cells, the value is $(m - 1) \\times (n - 1) - \\sum_{i = 1}^4 ans[i]$.\n\nTime complexity $O(l)$, space complexity $O(l)$, where $l$ is the length of $coordinates$." }, "is_english": true, "time_complexity": "O(l)", "space_complexity": "O(l)" }, { "problem_id": 2769, "explanations": { "1": "Notice that every time we can decrease $x$ by $1$ and increase $num$ by $1$, the difference between $x$ and $num$ will decrease by $2$, and we can do this operation at most $t$ times, so the maximum reachable number is $num + t \\times 2$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 2770, "explanations": { "1": "For each position $i$, we consider to jump to position $j$ which satisfies $|nums[i] - nums[j]| \\leq target$. Then we can jump from $i$ to $j$, and continue to jump from $j$ to the end.\n\nTherefore, we design a function $dfs(i)$, which represents the maximum number of jumps needed to jump to the end index starting from position $i$. Then the answer is $dfs(0)$.\n\nThe calculation process of function $dfs(i)$ is as follows:\n\n- If $i = n - 1$, then we have reached the end index and no jumps are required, so return $0$;\n- Otherwise, we need to enumerate the positions $j$ that can be jumped from position $i$, and calculate the maximum number of jumps needed to jump to the end index starting from $j$, then $dfs(i)$ is equal to the maximum value of all $dfs(j)$ plus $1$. If there is no position $j$ that can be jumped from $i$, then $dfs(i) = -\\infty$.\n\nTo avoid duplicate calculations, we can use memoization.\n\nTime complexity $O(n^2)$, space complexity $O(n)$. where $n$ is the length of array." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 2771, "explanations": { "1": "We define two variables $f$ and $g$, which represent the length of the longest non-decreasing subarray at the current position. Here, $f$ represents the length of the longest non-decreasing subarray ending with an element from $nums1$, and $g$ represents the length of the longest non-decreasing subarray ending with an element from $nums2$. Initially, $f = g = 1$, and the initial answer $ans = 1$.\n\nNext, we iterate over the array elements in the range $i \\in [1, n)$, and for each $i$, we define two variables $ff$ and $gg$, which represent the length of the longest non-decreasing subarray ending with $nums1[i]$ and $nums2[i]$ respectively. When initialized, $ff = gg = 1$.\n\nWe can calculate the values of $ff$ and $gg$ based on the values of $f$ and $g$:\n\n- If $nums1[i] \\ge nums1[i - 1]$, then $ff = \\max(ff, f + 1)$;\n- If $nums1[i] \\ge nums2[i - 1]$, then $ff = \\max(ff, g + 1)$;\n- If $nums2[i] \\ge nums1[i - 1]$, then $gg = \\max(gg, f + 1)$;\n- If $nums2[i] \\ge nums2[i - 1]$, then $gg = \\max(gg, g + 1)$.\n\nThen, we update $f = ff$ and $g = gg$, and update $ans$ to $\\max(ans, f, g)$.\n\nAfter the iteration ends, we return $ans$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2772, "explanations": { "1": "First, let's consider the first element of $nums$, $nums[0]$:\n\n- If $nums[0] = 0$, we don't need to do anything.\n- If $nums[0] > 0$, we need to operate on $nums[0..k-1]$ for $nums[0]$ times, subtracting $nums[0]$ from all elements in $nums[0..k-1]$, so $nums[0]$ becomes $0$.\n\nTo perform the add and subtract operations on a contiguous segment of elements simultaneously, we can use a difference array to manage these operations. We represent the difference array with $d[i]$, and calculating the prefix sum of the difference array gives us the change of the value at each position.\n\nTherefore, we iterate over $nums$. For each element $nums[i]$, the current position's change quantity is $s = \\sum_{j=0}^{i} d[j]$. We add $s$ to $nums[i]$ to get the actual value of $nums[i]$.\n\n- If $nums[i] = 0$, there's no need for any operation, and we can skip directly.\n- If $nums[i]=0$ or $i + k > n$, it indicates that after the previous operations, $nums[i]$ has become negative, or $nums[i..i+k-1]$ is out of bounds. Therefore, it's impossible to make all elements in $nums$ equal to $0$. We return `false`. Otherwise, we need to subtract $nums[i]$ from all elements in the interval $[i..i+k-1]$. Therefore, we subtract $nums[i]$ from $s$ and add $nums[i]$ to $d[i+k]$.\n- We continue to iterate over the next element.\n\nIf the iteration ends, it means that all elements in $nums$ can be made equal to $0$, so we return `true`.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2773, "explanations": { "1": "The key to the problem is how to determine whether a node is a leaf node. We design a function $dfs(root, d)$, where $root$ represents the current node, and $d$ represents the depth of the current node. Each time we search, we update the answer $ans = \\max(ans, d)$, and then determine whether the current node is a leaf node. If the current node has a left child, and the right child of the left child is not the current node, then we recursively call $dfs(root.left, d + 1)$. If the current node has a right child, and the left child of the right child is not the current node, then we recursively call $dfs(root.right, d + 1)$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2774, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2775, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2776, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2777, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2778, "explanations": { "1": "我们可以枚举数组中的每个元素,判断其是否为特殊元素,如果是则将其平方加入答案中。\n\n时间复杂度 $O(n)$,其中 $n$ 是数组的长度。空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2779, "explanations": { "1": "We notice that for each operation, all elements within the interval $[nums[i]-k, nums[i]+k]$ will increase by $1$. Therefore, we can use a difference array to record the contributions of these operations to the beauty value.\n\nIn the problem, $nums[i]-k$ might be negative. We add $k$ to all elements to ensure the results are non-negative. Thus, we can create a difference array $d$ with a length of $\\max(nums) + k \\times 2 + 2$.\n\nNext, we iterate through the array $nums$. For the current element $x$ being iterated, we increase $d[x]$ by $1$ and decrease $d[x+k\\times2+1]$ by $1$. In this way, we can calculate the prefix sum for each position using the $d$ array, which represents the beauty value for each position. The maximum beauty value can then be found.\n\nThe time complexity is $O(M + 2 \\times k + n)$, and the space complexity is $O(M + 2 \\times k)$. Here, $n$ is the length of the array $nums$, and $M$ is the maximum value in the array $nums$." }, "is_english": true, "time_complexity": "O(M + 2 \\times k + n)", "space_complexity": "O(M + 2 \\times k)" }, { "problem_id": 2780, "explanations": { "1": "我们用哈希表统计每个元素出现的次数,然后找出出现次数最多的元素 $x$,即为支配元素。要使得分割后的两个数组中都有支配元素,且支配元素相同,那么支配元素一定是 $x$。\n\n接下来,我们只需要遍历数组 $nums$,累加前缀中 $x$ 的出现次数 $cur$,并判断 $x$ 在后缀中出现的次数是否满足要求即可。如果满足要求,那么当前下标 $i$ 就是一个可行的分割下标,我们只需要选择所有可行分割下标中最小的那个即可。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 $nums$ 的长度。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2781, "explanations": { "1": "我们用哈希表 $s$ 记录所有禁止的字符串,然后用双指针 $i$ 和 $j$ 遍历字符串 $word$,其中 $i$ 和 $j$ 分别表示当前合法子字符串的左右边界。\n\n接下来,我们枚举子字符串的右端点 $j$,判断此时 $word[k..j]$ 是否合法,如果不合法,那么我们更新 $i = k + 1$。接下来更新答案 $ans = \\max(ans, j - i + 1)$。\n\n时间复杂度 $O(n \\times \\max(|forbidden[i]|^2) + m)$,空间复杂度 $O(m)$。其中 $n$ 和 $m$ 分别表示字符串 $word$ 和 $forbidden$ 的长度。" }, "is_english": false, "time_complexity": "O(n \\times \\max(|forbidden[i]|^2) + m)", "space_complexity": "O(m)" }, { "problem_id": 2782, "explanations": { "1": "我们用并查集来维护相同类别的元素,接下来枚举所有的元素对,如果两个元素属于相同的类别,那么就将它们合并到同一个集合中。最后统计并查集中有多少个集合,就是答案。\n\n时间复杂度 $(n^2 \\times \\alpha(n))$,空间复杂度 $O(n)$。其中 $n$ 是元素的个数,而 $\\alpha$ 是阿克曼函数的反函数。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2783, "explanations": { "1": "我们可以使用左连接将 `Flights` 和 `Passengers` 表连接起来,然后按照 `flight_id` 分组,统计每个航班的乘客数量。\n\n对于每个航班,我们可以使用 `count(passenger_id)` 统计乘客数量,取 `capacity` 和 `count(passenger_id)` 的最小值作为已预订的乘客数量,取 `count(passenger_id) - capacity` 和 $0$ 的最大值作为等待名单上的乘客数量。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2784, "explanations": { "1": "We can use a hash table or array $cnt$ to record the number of occurrences of each element in the array $nums$. Then we determine whether the following conditions are met:\n\n1. $cnt[n] = 2$, i.e., the largest element in the array appears twice;\n2. For $1 \\leq i \\leq n-1$, it holds that $cnt[i] = 1$, i.e., except for the largest element, all other elements appear only once.\n\nIf the above two conditions are met, then the array $nums$ is a good array, otherwise it is not.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2785, "explanations": { "1": "First, we store all the vowels in the string into an array or list $vs$, then we sort $vs$.\n\nNext, we traverse the string $s$, keeping the consonants unchanged. If it is a vowel, we replace it in order with the letters in the $vs$ array.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2786, "explanations": { "1": "Based on the problem description, we can draw the following conclusions:\n\n1. Moving from position $i$ to position $j$, if $nums[i]$ and $nums[j]$ have different parities, then $x$ points will be lost;\n2. Moving from position $i$ to position $j$, if $nums[i]$ and $nums[j]$ have the same parity, then no points will be lost.\n\nTherefore, we can use an array $f$ of length $2$ to represent the maximum score when the current position's parity is $0$ and $1$. Initially, the values of $f$ are $-\\infty$, and then we initialize $f[nums[0] \\& 1] = nums[0]$, indicating the score at the initial position.\n\nNext, we start traversing the array $nums$ from position $1$. For each position $i$ corresponding to the value $v$, we update the value of $f[v \\& 1]$ to be the larger value between $f[v \\& 1]$ and $f[v \\& 1 \\oplus 1] - x$ plus $v$, i.e., $f[v \\& 1] = \\max(f[v \\& 1], f[v \\& 1 \\oplus 1] - x) + v$.\n\nThe answer is the larger value between $f[0]$ and $f[1]$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2787, "explanations": { "1": "We define $f[i][j]$ as the number of ways to select some numbers from the first $i$ positive integers such that the sum of their $x$-th powers equals $j$. Initially, $f[0][0] = 1$, and all others are $0$. The answer is $f[n][n]$.\n\nFor each positive integer $i$, we can choose to either include it or not:\n\n- Not include it: the number of ways is $f[i-1][j]$;\n- Include it: the number of ways is $f[i-1][j-i^x]$ (provided that $j \\geq i^x$).\n\nTherefore, the state transition equation is:\n\n$$\nf[i][j] = f[i-1][j] + (j \\geq i^x ? f[i-1][j-i^x] : 0)\n$$\n\nNote that the answer can be very large, so we need to take modulo $10^9 + 7$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$, where $n$ is the given integer in the" }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 2788, "explanations": { "1": "We traverse the string array $words$. For each string $w$, we use `separator` as the delimiter to split it. If the split string is not empty, we add it to the answer array.\n\nThe time complexity is $O(n \\times m)$, and the space complexity is $O(m)$, where $n$ is the length of the string array $words$, and $m$ is the maximum length of the strings in the array $words$." }, "is_english": true, "time_complexity": "O(n \\times m)", "space_complexity": "O(m)" }, { "problem_id": 2789, "explanations": { "1": "According to the problem description, in order to maximize the maximum element in the merged array, we should merge the elements on the right first, making the elements on the right as large as possible, so as to perform as many merge operations as possible and finally get the maximum element.\n\nTherefore, we can traverse the array from right to left. For each position $i$, where $i \\in [0, n - 2]$, if $nums[i] \\leq nums[i + 1]$, we update $nums[i]$ to $nums[i] + nums[i + 1]$. Doing so is equivalent to merging $nums[i]$ and $nums[i + 1]$ and deleting $nums[i]$.\n\nIn the end, the maximum element in the array is the maximum element in the merged array.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2790, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2791, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2792, "explanations": { "1": "我们可以使用 DFS 后序遍历整棵树,对于每个节点,我们维护一个大根堆,堆中存储该节点的所有子树中最小的 k 个节点的值,如果当前节点的值大于堆顶元素,那么该节点就是一个「足够大」的节点,我们将答案加一。\n\n时间复杂度 $O(n \\times k \\times \\log k)$,空间复杂度 $(n \\times k)$。其中 $n$ 是树中节点的个数。" }, "is_english": false, "time_complexity": "O(n \\times k \\times \\log k)", "space_complexity": null }, { "problem_id": 2793, "explanations": { "1": "注意,如果多个人在同一时间预定了同一个航班,只要有空位,就都可以确认预定。" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2794, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2795, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2796, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2797, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2798, "explanations": { "1": "We can iterate through the array $hours$. For each employee, if their working hours $x$ is greater than or equal to $target$, then we increment the counter $ans$ by one.\n\nAfter the iteration, we return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $hours$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2799, "explanations": { "1": "First, we use a hash table to count the number of distinct elements in the array, denoted as $cnt$.\n\nNext, we enumerate the left endpoint index $i$ of the subarray and maintain a set $s$ to store the elements in the subarray. Each time we move the right endpoint index $j$ to the right, we add $nums[j]$ to the set $s$ and check whether the size of the set $s$ equals $cnt$. If it equals $cnt$, it means the current subarray is a complete subarray, and we increment the answer by $1$.\n\nAfter the enumeration ends, we return the answer.\n\nTime complexity: $O(n^2)$, Space complexity: $O(n)$, where $n$ is the length of the array.", "2": "Similar to Solution 1, we can use a hash table to count the number of distinct elements in the array, denoted as $cnt$.\n\nNext, we use two pointers to maintain a sliding window, where the right endpoint index is $j$ and the left endpoint index is $i$.\n\nEach time we fix the left endpoint index $i$, we move the right endpoint index $j$ to the right. When the number of distinct elements in the sliding window equals $cnt$, it means that all subarrays from the left endpoint index $i$ to the right endpoint index $j$ and beyond are complete subarrays. We then increment the answer by $n - j$, where $n$ is the length of the array. Afterward, we move the left endpoint index $i$ one step to the right and repeat the process.\n\nTime complexity: $O(n)$, Space complexity: $O(n)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 2800, "explanations": { "1": "We enumerate all permutations of the three strings, and for each permutation, we merge the three strings to find the shortest string with the smallest lexicographical order.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$. Where $n$ is the maximum length of the three strings.", "2": "We can use the KMP algorithm to optimize the string merging process.\n\nTime complexity is $O(n)$, and space complexity is $O(n)$. Here, $n$ is the sum of the lengths of the three strings." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 2801, "explanations": { "1": "We notice that the problem is asking for the number of stepping numbers in the interval $[low, high]$. For such an interval $[l,..r]$ problem, we can usually consider transforming it into finding the answers for $[1, r]$ and $[1, l-1]$, and then subtracting the latter from the former. Moreover, the problem only involves the relationship between different digits, not the specific values, so we can consider using Digit DP to solve it.\n\nWe design a function $dfs(pos, pre, lead, limit)$, which represents the number of schemes when we are currently processing the $pos$-th digit, the previous digit is $pre$, whether the current number only contains leading zeros is $lead$, and whether the current number has reached the upper limit is $limit$. The range of $pos$ is $[0, len(num))$.\n\nThe execution logic of the function $dfs(pos, pre, lead, limit)$ is as follows:\n\nIf $pos$ exceeds the length of $num$, it means that we have processed all the digits. If $lead$ is true at this time, it means that the current number only contains leading zeros and is not a valid number. We can return $0$ to indicate that the number of schemes is $0$; otherwise, we return $1$ to indicate that the number of schemes is $1$.\n\nOtherwise, we calculate the upper limit $up$ of the current digit, and then enumerate the digit $i$ in the range $[0,..up]$:\n\n- If $i=0$ and $lead$ is true, it means that the current number only contains leading zeros. We recursively calculate the value of $dfs(pos+1,pre, true, limit\\ and\\ i=up)$ and add it to the answer.\n- Otherwise, if $pre$ is $-1$, or the absolute difference between $i$ and $pre$ is $1$, it means that the current number is a valid stepping number. We recursively calculate the value of $dfs(pos+1,i, false, limit\\ and\\ i=up)$ and add it to the answer.\n\nFinally, we return the answer.\n\nIn the main function, we calculate the answers $a$ and $b$ for $[1, high]$ and $[1, low-1]$ respectively. The final answer is $a-b$. Note the modulo operation of the answer.\n\nThe time complexity is $O(\\log M \\times |\\Sigma|^2)$, and the space complexity is $O(\\log M \\times |\\Sigma|)$, where $M$ represents the size of the number $high$, and $|\\Sigma|$ represents the digit set.\n\nSimilar problems:\n\n- [2719. Count of Integers](https://github.com/doocs/leetcode/blob/main/solution/2700-2799/2719.Count%20of%20Integers/README_EN.md)" }, "is_english": true, "time_complexity": "O(\\log M \\times |\\Sigma|^2)", "space_complexity": "O(\\log M \\times |\\Sigma|)" }, { "problem_id": 2802, "explanations": { "1": "According to the problem description, a lucky number only contains the digits $4$ and $7$, so the number of $n$-digit lucky numbers is $2^n$.\n\nWe initialize $n=1$, then loop to check whether $k$ is greater than $2^n$. If it is, we subtract $2^n$ from $k$ and increment $n$, until $k$ is less than or equal to $2^n$. At this point, we just need to find the $k$-th lucky number among the $n$-digit lucky numbers.\n\nIf $k$ is less than or equal to $2^{n-1}$, then the first digit of the $k$-th lucky number is $4$, otherwise the first digit is $7$. Then we subtract $2^{n-1}$ from $k$ and continue to determine the second digit, until all digits of the $n$-digit lucky number are determined.\n\nThe time complexity is $O(\\log k)$, and the space complexity is $O(\\log k)$." }, "is_english": true, "time_complexity": "O(\\log k)", "space_complexity": "O(\\log k)" }, { "problem_id": 2803, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2804, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2805, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2806, "explanations": { "1": "We enumerate all multiples of 10 within the range $[0, 100]$, and find the one that is closest to `purchaseAmount`, denoted as $x$. The answer is $100 - x$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 2807, "explanations": { "1": "We use two pointers $pre$ and $cur$ to point to the current node and the next node respectively. We only need to insert a new node between $pre$ and $cur$. Therefore, each time we calculate the greatest common divisor $x$ of $pre$ and $cur$, we insert a new node with value $x$ between $pre$ and $cur$. Then we update $pre = cur$ and $cur = cur.next$, and continue to traverse the linked list until $cur$ is null.\n\nThe time complexity is $O(n \\times \\log M)$, where $n$ is the length of the linked list, and $M$ is the maximum value of the nodes in the linked list. Ignoring the space consumption of the result linked list, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(1)" }, { "problem_id": 2808, "explanations": { "1": "We assume that all elements eventually become $x$, and $x$ must be an element in the array.\n\nThe number $x$ can expand one bit to the left and right every second. If there are multiple identical $x$, then the time required to expand the entire array depends on the maximum distance between two adjacent $x$.\n\nTherefore, we enumerate each element as the final $x$, calculate the maximum distance $t$ between two adjacent elements in each $x$, then the final answer is $\\min\\limits_{x \\in nums} \\left\\lfloor \\frac{t}{2} \\right\\rfloor$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2809, "explanations": { "1": "We notice that if we operate on the same number multiple times, only the last operation is meaningful, and the rest of the operations on that number will only increase the other numbers. Therefore, we operate on each number at most once, that is to say, the number of operations is within $[0,..n]$.\n\nLet's assume that we have performed $j$ operations, and the indices of the numbers operated on are $i_1, i_2, \\cdots, i_j$. For these $j$ operations, the value that each operation can reduce the sum of array elements is:\n\n$$\n\\begin{aligned}\n& d_1 = nums_1[i_1] + nums_2[i_1] \\times 1 \\\\\n& d_2 = nums_1[i_2] + nums_2[i_2] \\times 2 \\\\\n& \\cdots \\\\\n& d_j = nums_1[i_j] + nums_2[i_j] \\times j\n\\end{aligned}\n$$\n\nFrom a greedy perspective, in order to maximize the reduction of the sum of array elements, we should let the larger elements in $nums_2$ be operated on as late as possible. Therefore, we can sort $nums_1$ and $nums_2$ in ascending order of the element values in $nums_2$.\n\nNext, we consider the implementation of dynamic programming. We use $f[i][j]$ to represent the maximum value that can reduce the sum of array elements for the first $i$ elements of the array $nums_1$ with $j$ operations. We can get the following state transition equation:\n\n$$\nf[i][j] = \\max \\{f[i-1][j], f[i-1][j-1] + nums_1[i] + nums_2[i] \\times j\\}\n$$\n\nFinally, we enumerate $j$ and find the smallest $j$ that satisfies $s_1 + s_2 \\times j - f[n][j] \\le x$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 2810, "explanations": { "1": "We directly simulate the keyboard input process, using a character array $t$ to record the text on the screen, initially $t$ is empty.\n\nFor each character $c$ in string $s$, if $c$ is not the character $'i'$, then we add $c$ to the end of $t$; otherwise, we reverse all characters in $t$.\n\nThe final answer is the string composed of characters in $t$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$, where $n$ is the length of string $s$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 2811, "explanations": { "1": "First, we preprocess to get the prefix sum array $s$, where $s[i]$ represents the sum of the first $i$ elements of the array $nums$.\n\nNext, we design a function $dfs(i, j)$, which represents whether there is a way to split the index range $[i, j]$ of the array $nums$ that meets the conditions. If it exists, return `true`, otherwise return `false`.\n\nThe calculation process of the function $dfs(i, j)$ is as follows:\n\nIf $i = j$, then there is only one element, no need to split, return `true`;\n\nOtherwise, we enumerate the split point $k$, where $k \\in [i, j]$, if the following conditions are met, then it can be split into two subarrays $nums[i,.. k]$ and $nums[k + 1,.. j]$:\n\n- The subarray $nums[i,..k]$ has only one element, or the sum of the elements of the subarray $nums[i,..k]$ is greater than or equal to $m$;\n- The subarray $nums[k + 1,..j]$ has only one element, or the sum of the elements of the subarray $nums[k + 1,..j]$ is greater than or equal to $m$;\n- Both $dfs(i, k)$ and $dfs(k + 1, j)$ are `true`.\n\nTo avoid repeated calculations, we use the method of memoization search, and use a two-dimensional array $f$ to record all the return values of $dfs(i, j)$, where $f[i][j]$ represents the return value of $dfs(i, j)$.\n\nThe time complexity is $O(n^3)$, and the space complexity is $O(n^2)$, where $n$ is the length of the array $nums$.", "2": "No matter how you operate, there will always be a `length == 2` subarray left in the end. Since there are no negative numbers in the elements, as the split operation proceeds, the length and sum of the subarray will gradually decrease. The sum of other `length > 2` subarrays must be larger than the sum of this subarray. Therefore, we only need to consider whether there is a `length == 2` subarray with a sum greater than or equal to `m`.\n\n> 📢 Note that when `nums.length <= 2`, no operation is needed.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n^3)", "space_complexity": "O(n^2)" }, { "problem_id": 2812, "explanations": { "1": "We can first find out the positions of all thieves, and then start multi-source BFS from these positions to get the shortest distance from each position to the thieves. Then sort in descending order according to the distance, and add each position to the union-find set one by one. If the start and end points are in the same connected component, the current distance is the answer.\n\nThe time complexity is $O(n^2 \\times \\log n)$, and the space complexity $O(n^2)$. Where $n$ is the size of the grid.", "2": "" }, "is_english": true, "time_complexity": "O(n^2 \\times \\log n)", "space_complexity": "O(n^2)" }, { "problem_id": 2813, "explanations": { "1": "We can sort all items by profit from large to small. First choose the first $k$ items and calculate the total profit $tot$. Use a hash table $vis$ to record the categories of these $k$ items, use a stack $dup$ to record the profits of the repeated categories in order, and use a variable $ans$ to record the current maximum elegance.\n\nNext, we consider starting from the $k+1$ item. If its category is already in $vis$, it means that if we choose this category, the number of different categories will not increase, so we can skip this item directly. If there is no duplicate category before, we can also skip this item directly. Otherwise, we can consider replacing the top item of $dup$ stack (the item with the minimum profit in the duplicate category) with the current item, which can increase the total profit by $p - dup.pop()$ and increase the number of different categories by $1$, so we can update $tot$ and $ans$.\n\nFinally, we return $ans$.\n\nThe time complexity is $O(n \\times \\log n)$ and the space complexity is $O(n)$, where $n$ is the number of items." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2814, "explanations": { "1": "First, we run a BFS (Breadth-First Search) to calculate the shortest distance from each cell to the water, and record it in the array $g$. Then, we run another BFS starting from the cell $(s_i, s_j)$ to find the shortest distance to the target cell $(d_i, d_j)$. During this process, if the adjacent cell $(x, y)$ of the current cell $(i, j)$ satisfies $g[x][y] > t + 1$, then we can move from $(x, y)$ to $(i, j)$.\n\nThe time complexity is $O(m \\times n)$ and the space complexity is $O(m \\times n)$. Where $m$ and $n$ are the number of rows and columns of the array $land$, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 2815, "explanations": { "1": "First, we initialize the answer variable $ans=-1$. Next, we directly enumerate all pairs $(nums[i], nums[j])$ where $i \\lt j$, and calculate their sum $v=nums[i] + nums[j]$. If $v$ is greater than $ans$ and the largest digit of $nums[i]$ and $nums[j]$ are the same, then we update $ans$ with $v$.\n\nThe time complexity is $O(n^2 \\times \\log M)$, where $n$ is the length of the array and $M$ is the maximum value in the array." }, "is_english": true, "time_complexity": "O(n^2 \\times \\log M)", "space_complexity": null }, { "problem_id": 2816, "explanations": { "1": "First, we reverse the linked list, then simulate the multiplication operation, and finally reverse the linked list back.\n\nTime complexity is $O(n)$, where $n$ is the length of the linked list. Ignoring the space taken by the answer linked list, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2817, "explanations": { "1": "We create an ordered set to store the elements whose distance to the current index is at least $x$.\n\nNext, we enumerate from index $i = x$, each time we add $nums[i - x]$ into the ordered set. Then we find the two elements in the ordered set which are closest to $nums[i]$, and the minimum absolute difference between them is the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the length of array $nums$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2818, "explanations": { "1": "It is not difficult to see that the number of subarrays with the highest prime score of an element $nums[i]$ is $cnt = (i - l) \\times (r - i)$, where $l$ is the leftmost index such that $primeScore(nums[l]) \\ge primeScore(nums[i])$, and $r$ is the rightmost index such that $primeScore(nums[r]) \\ge primeScore(nums[i])$.\n\nSince we are allowed to operate at most $k$ times, we can greedily enumerate $nums[i]$ from large to small, and compute the $cnt$ of each element. If $cnt \\le k$, then the contribution of $nums[i]$ to the answer is $nums[i]^{cnt}$, and we update $k = k - cnt$. If $cnt \\gt k$, then the contribution of $nums[i]$ to the answer is $nums[i]^{k}$, and we break out the loop.\n\nReturn the answer after the loop. Note that the power is large, so we need to use fast power.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2819, "explanations": { "1": "Based on the problem description, we know:\n\nIf $prices[i] \\leq k$, then Bob needs to pay $prices[i]$, and Alice doesn't need to pay. Therefore, Bob's relative loss is $prices[i]$. In this case, Bob should choose the chocolate with a lower price to minimize the relative loss.\n\nIf $prices[i] > k$, then Bob needs to pay $k$, and Alice needs to pay $prices[i] - k$. Therefore, Bob's relative loss is $k - (prices[i] - k) = 2k - prices[i]$. In this case, Bob should choose the chocolate with a higher price to minimize the relative loss.\n\nTherefore, we first sort the price array $prices$, and then preprocess the prefix sum array $s$, where $s[i]$ represents the sum of the prices of the first $i$ chocolates.\n\nNext, for each query $[k, m]$, we first use binary search to find the index $r$ of the first chocolate with a price greater than $k$. Then, we use binary search again to find the number of chocolates $l$ that should be chosen on the left, so the number of chocolates that should be chosen on the right is $m - l$. At this point, Bob's relative loss is $s[l] + 2k(m - l) - (s[n] - s[n - (m - l)])$.\n\nIn the second binary search process mentioned above, we need to judge whether $prices[mid] < 2k - prices[n - (m - mid)]$, where $right$ represents the number of chocolates that should be chosen on the right. If this inequality holds, it means that choosing the chocolate at position $mid$ has a lower relative loss, so we update $l = mid + 1$. Otherwise, it means that the chocolate at position $mid$ has a higher relative loss, so we update $r = mid$.\n\nThe time complexity is $O((n + m) \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ and $m$ are the lengths of the arrays $prices$ and $queries$, respectively." }, "is_english": true, "time_complexity": "O((n + m) \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2820, "explanations": { "1": "We can use the window function `count` to calculate the number of votes each voter gives to the candidates, then use the group statistics function `sum` to calculate the total number of votes for each candidate. Next, we use the window function `rank` to calculate the ranking of each candidate, and finally filter out the candidate who ranks first.\n\nNote that there may be multiple candidates ranking first in the result set, so we need to use `order by` to sort the candidates." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 2821, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2822, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2823, "explanations": { "1": "我们先判断当前对象是否为数组,如果是数组,我们就对数组中的每一个元素进行递归调用,然后过滤掉返回值为 `undefined` 的元素,最后返回过滤后的数组。\n\n如果当前对象不是数组,我们就判断当前对象是否为对象,如果是对象,我们就对对象中的每一个属性值进行递归调用,然后过滤掉返回值为 `undefined` 的属性值,最后返回过滤后的对象。\n\n如果当前对象既不是数组也不是对象,我们就直接返回 `fn(obj) ? obj : undefined`。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为对象中的元素个数。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2824, "explanations": { "1": "First, we sort the array $nums$. Then, for each $j$, we use binary search in the range $[0, j)$ to find the first index $i$ that is greater than or equal to $target - nums[j]$. All indices $k$ in the range $[0, i)$ meet the condition, so the answer increases by $i$.\n\nAfter the traversal, we return the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 2825, "explanations": { "1": "This problem actually requires us to determine whether a string $s$ is a subsequence of another string $t$. However, the characters do not have to match exactly. If two characters are the same, or one character is the next character of the other, they can match.\n\nThe time complexity is $O(m + n)$, where $m$ and $n$ are the lengths of the strings $str1$ and $str2$ respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m + n)", "space_complexity": "O(1)" }, { "problem_id": 2826, "explanations": { "1": "We define $f[i][j]$ as the minimum number of operations to turn the first $i$ numbers into a beautiful array, and the $i$th number is changed to $j+1$. The answer is $\\min(f[n][0], f[n][1], f[n][2])$.\n\nWe can enumerate all cases where the $i$th number is changed to $j+1$, and then take the minimum value. Here, we can use a rolling array to optimize the space complexity.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2827, "explanations": { "1": "We notice that the problem is asking for the number of beautiful integers in the interval $[low, high]$. For such an interval $[l,..r]$ problem, we can usually consider transforming it into finding the answers for $[1, r]$ and $[1, l-1]$, and then subtracting the latter from the former. Moreover, the problem only involves the relationship between different digits, not the specific values, so we can consider using Digit DP to solve it.\n\nWe design a function $dfs(pos, mod, diff, lead, limit)$, which represents the number of schemes when we are currently processing the $pos$-th digit, the result of the current number modulo $k$ is $mod$, the difference between the odd and even digits of the current number is $diff$, whether the current number has leading zeros is $lead$, and whether the current number has reached the upper limit is $limit$.\n\nThe execution logic of the function $dfs(pos, mod, diff, lead, limit)$ is as follows:\n\nIf $pos$ exceeds the length of $num$, it means that we have processed all the digits. If $mod=0$ and $diff=0$ at this time, it means that the current number meets the requirements of the problem, so we return $1$, otherwise we return $0$.\n\nOtherwise, we calculate the upper limit $up$ of the current digit, and then enumerate the digit $i$ in the range $[0,..up]$:\n\n- If $i=0$ and $lead$ is true, it means that the current number only contains leading zeros. We recursively calculate the value of $dfs(pos + 1, mod, diff, 1, limit\\ and\\ i=up)$ and add it to the answer.\n- Otherwise, we update the value of $diff$ according to the parity of $i$, and then recursively calculate the value of $dfs(pos + 1, (mod \\times 10 + i) \\bmod k, diff, 0, limit\\ and\\ i=up)$ and add it to the answer.\n\nFinally, we return the answer.\n\nIn the main function, we calculate the answers $a$ and $b$ for $[1, high]$ and $[1, low-1]$ respectively. The final answer is $a-b$.\n\nThe time complexity is $O((\\log M)^2 \\times k \\times |\\Sigma|)$, and the space complexity is $O((\\log M)^2 \\times k)$, where $M$ represents the size of the number $high$, and $|\\Sigma|$ represents the digit set.\n\nSimilar problems:\n\n- [2719. Count of Integers](https://github.com/doocs/leetcode/blob/main/solution/2700-2799/2719.Count%20of%20Integers/README_EN.md)" }, "is_english": true, "time_complexity": "O((\\log M)^2 \\times k \\times |\\Sigma|)", "space_complexity": "O((\\log M)^2 \\times k)" }, { "problem_id": 2828, "explanations": { "1": "We can iterate over each string in the array $words$, concatenate their first letters to form a new string $t$, and then check if $t$ is equal to $s$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $words$.", "2": "First, we check if the number of strings in $words$ is equal to the length of $s$. If not, $s$ is definitely not an acronym of the first letters of $words$, and we directly return $false$.\n\nThen, we iterate over each character in $s$, checking if it is equal to the first letter of the corresponding string in $words$. If not, $s$ is definitely not an acronym of the first letters of $words$, and we directly return $false$.\n\nAfter the iteration, if we haven't returned $false$, then $s$ is an acronym of the first letters of $words$, and we return $true$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $words$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2829, "explanations": { "1": "Starting from the positive integer $i = 1$, we sequentially determine if $i$ can be added to the array. If it can be added, we add $i$ to the array, accumulate it to the answer, and then mark $k - i$ as visited, indicating that $k-i$ cannot be added to the array. We continue this process until the array's length reaches $n$.\n\nThe time complexity is $O(n + k)$, and the space complexity is $O(n + k)$. Where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n + k)", "space_complexity": "O(n + k)" }, { "problem_id": 2830, "explanations": { "1": "We sort all the purchase offers by $end$ in ascending order, and then use dynamic programming to solve the problem.\n\nDefine $f[i]$ to represent the maximum amount of gold we can get from the first $i$ purchase offers. The answer is $f[n]$.\n\nFor $f[i]$, we can choose not to sell the $i$th purchase offer, in which case $f[i] = f[i - 1]$; or we can choose to sell the $i$th purchase offer, in which case $f[i] = f[j] + gold_i$, where $j$ is the largest index that satisfies $end_j \\leq start_i$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the number of purchase offers." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2831, "explanations": { "1": "We use two pointers to maintain a monotonically variable length window, and a hash table to maintain the number of occurrences of each element in the window.\n\nThe number of all elements in the window minus the number of the most frequently occurring element in the window is the number of elements that need to be deleted from the window.\n\nEach time, we add the element pointed to by the right pointer to the window, then update the hash table, and also update the number of the most frequently occurring element in the window. When the number of elements that need to be deleted from the window exceeds $k$, we move the left pointer once, and then update the hash table.\n\nAfter the traversal, return the number of the most frequently occurring element.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array.", "2": "We can use a hash table $g$ to maintain the index list of each element.\n\nNext, we enumerate each element as the equal value element. We take out the index list $ids$ of this element from the hash table $g$. Then we define two pointers $l$ and $r$ to maintain a window, so that the number of elements in the window minus the number of equal value elements does not exceed $k$. Therefore, we only need to find the largest window that meets the condition.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2832, "explanations": { "1": "This problem is a template for monotonic stack. We only need to use the monotonic stack to find the position of the first element larger than $nums[i]$ on the left and right, denoted as $left[i]$ and $right[i]$. Then, the interval length with $nums[i]$ as the maximum value is $right[i] - left[i] - 1$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2833, "explanations": { "1": "When encountering the character '_', we can choose to move left or right. The problem requires us to find the farthest point from the origin. Therefore, we can first traverse once, greedily move all '_' to the left, and find the farthest point from the origin at this time. Then traverse again, greedily move all '\\_' to the right, and find the farthest point from the origin at this time. Finally, take the maximum of the two traversals.\n\nFurther, we only need to calculate the difference between the number of 'L' and 'R' in the string, and then add the number of '\\_'.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2834, "explanations": { "1": "We can greedily construct the array `nums` starting from $x = 1$, choosing $x$ each time and excluding $target - x$.\n\nLet's denote $m = \\left\\lfloor \\frac{target}{2} \\right\\rfloor$.\n\nIf $x <= m$, then the numbers we can choose are $1, 2, \\cdots, n$, so the sum of the array is $\\left\\lfloor \\frac{(1+n)n}{2} \\right\\rfloor$.\n\nIf $x > m$, then the numbers we can choose are $1, 2, \\cdots, m$, a total of $m$ numbers, and $n - m$ numbers starting from $target$, so the sum of the array is $\\left\\lfloor \\frac{(1+m)m}{2} \\right\\rfloor + \\left\\lfloor \\frac{(target + target + n - m - 1)(n-m)}{2} \\right\\rfloor$.\n\nNote that we need to take the modulus of $10^9 + 7$ for the result.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 2835, "explanations": { "1": "Observing the operation in the problem, we find that each operation actually splits a number greater than $1$ into two equal numbers, which means that the sum of the elements in the array will not change after the operation. Therefore, if the sum of the elements in the array $s$ is less than $target$, it is impossible to obtain a subsequence with a sum of $target$ through the operation described in the problem, and we can directly return $-1$. Otherwise, we can definitely make the sum of some subsequences in the array equal to $target$ through the split operation.\n\nIn addition, the split operation will actually set the binary high bit of the number to $0$ and add $2$ to the lower bit. Therefore, we first use an array of length $32$ to record the number of times $1$ appears on each binary bit in the binary representation of all elements in the array $nums$.\n\nNext, starting from the low bit of $target$, for the $i$th bit of $target$, if the current bit number is $0$, skip it directly, that is, $i = i + 1$. If the current bit number is $1$, we need to find the smallest number $j$ (where $j \\ge i$) in the array $cnt$ such that $cnt[j] > 0$, and then we split the number $1$ at this bit to the lower bit $i$, that is, subtract $1$ from $cnt[j]$, and set each bit from $i$ to $j-1$ in $cnt$ to $1$, and the number of operations is $j-i$. Next, we let $j = i$, and then $i = i + 1$. Repeat the above operation until $i$ exceeds the index range of the array $cnt$, and return the number of operations at this time.\n\nNote that if $j < i$, actually two lower bits of $1$ can be combined into a higher bit of $1$. Therefore, if $j < i$, we add $\\frac{cnt[j]}{2}$ to $cnt[j+1]$, and take $cnt[j]$ modulo $2$, then let $j = j + 1$, and continue the above operation.\n\nThe time complexity is $O(n \\times \\log M)$, and the space complexity is $O(\\log M)$. Here, $n$ is the length of the array $nums$, and $M$ is the maximum value in the array $nums$." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(\\log M)" }, { "problem_id": 2836, "explanations": { "1": "The problem asks us to find the maximum sum of the player IDs who have touched the ball within $k$ passes starting from each player $i$. If we solve it by brute force, we need to traverse upwards $k$ times starting from $i$, with a time complexity of $O(k)$, which will obviously time out.\n\nWe can use dynamic programming combined with binary lifting to handle this.\n\nWe define $f[i][j]$ as the player ID that can be reached by passing the ball $2^j$ times starting from player $i$, and define $g[i][j]$ as the sum of the player IDs that can be reached by passing the ball $2^j$ times starting from player $i$ (excluding the last player).\n\nWhen $j=0$, the number of passes is $1$, so $f[i][0] = receiver[i]$, and $g[i][0] = i$.\n\nWhen $j > 0$, the number of passes is $2^j$, which is equivalent to passing the ball $2^{j-1}$ times starting from player $i$, and then passing the ball $2^{j-1}$ times starting from player $f[i][j-1]$, so $f[i][j] = f[f[i][j-1]][j-1]$, and $g[i][j] = g[i][j-1] + g[f[i][j-1]][j-1]$.\n\nNext, we can enumerate each player $i$ as the starting player, then accumulate upwards according to the binary representation of $k$, and finally get the maximum sum of the player IDs who have touched the ball within $k$ passes starting from player $i$.\n\nThe time complexity is $O(n \\times \\log k)$, and the space complexity is $O(n \\times \\log k)$. Here, $n$ is the number of players.\n\nSimilar problems:\n\n- [1483. Kth Ancestor of a Tree Node](https://github.com/doocs/leetcode/blob/main/solution/1400-1499/1483.Kth%20Ancestor%20of%20a%20Tree%20Node/README_EN.md)" }, "is_english": true, "time_complexity": "O(k)", "space_complexity": "O(n \\times \\log k)" }, { "problem_id": 2837, "explanations": { "1": "We can use a left join to connect the two tables, and then use group by sum to calculate the total distance for each user. Note that if a user has not completed any rides, their distance should be considered as $0$." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 2838, "explanations": { "1": "We can sort the monsters and coins in ascending order of the monsters' combat power, and then use prefix sum to calculate the total number of coins each hero can get by defeating the first $i$ monsters.\n\nNext, for each hero, we can use binary search to find the strongest monster he can defeat, and then use prefix sum to calculate the total number of coins he can get.\n\nThe time complexity is $O((m + n) \\times \\log n)$, and the space complexity is $O(m)$. Here, $m$ and $n$ are the number of monsters and heroes, respectively." }, "is_english": true, "time_complexity": "O((m + n) \\times \\log n)", "space_complexity": "O(m)" }, { "problem_id": 2839, "explanations": { "1": "We observe the operation in the problem, and find that if the parity of the two indices $i$ and $j$ of the string is the same, then their order can be changed by swapping.\n\nTherefore, we can count the occurrence times of the characters at odd indices and even indices in the two strings. If the counting results of the two strings are the same, then we can make the two strings equal through the operation.\n\nThe time complexity is $O(n + |\\Sigma|)$, and the space complexity is $O(|\\Sigma|)$. Here, $n$ is the length of the string, and $\\Sigma$ is the character set.\n\nSimilar problems:\n\n- [2840. Check if Strings Can be Made Equal With Operations II](https://github.com/doocs/leetcode/blob/main/solution/2800-2899/2840.Check%20if%20Strings%20Can%20be%20Made%20Equal%20With%20Operations%20II/README_EN.md)" }, "is_english": true, "time_complexity": "O(n + |\\Sigma|)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 2840, "explanations": { "1": "We observe the operation in the problem, and find that if the parity of the two indices $i$ and $j$ of the string is the same, then their order can be changed by swapping.\n\nTherefore, we can count the occurrence times of the characters at odd indices and even indices in the two strings. If the counting results of the two strings are the same, then we can make the two strings equal through the operation.\n\nThe time complexity is $O(n + |\\Sigma|)$, and the space complexity is $O(|\\Sigma|)$. Here, $n$ is the length of the string, and $\\Sigma$ is the character set.\n\nSimilar problems:\n\n- [2839. Check if Strings Can be Made Equal With Operations I](https://github.com/doocs/leetcode/blob/main/solution/2800-2899/2839.Check%20if%20Strings%20Can%20be%20Made%20Equal%20With%20Operations%20I/README_EN.md)" }, "is_english": true, "time_complexity": "O(n + |\\Sigma|)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 2841, "explanations": { "1": "We can traverse the array $nums$, maintain a window of size $k$, use a hash table $cnt$ to count the occurrence of each element in the window, and use a variable $s$ to sum all elements in the window. If the number of different elements in $cnt$ is greater than or equal to $m$, then we update the answer $ans = \\max(ans, s)$.\n\nAfter the traversal ends, return the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(k)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(k)" }, { "problem_id": 2842, "explanations": { "1": "First, we use a hash table $f$ to count the occurrence of each character in the string $s$, i.e., $f[c]$ represents the number of times character $c$ appears in the string $s$.\n\nSince a $k$-subsequence is a subsequence of length $k$ in the string $s$ with unique characters, if the number of different characters in $f$ is less than $k$, then there is no $k$-subsequence, and we can directly return $0$.\n\nOtherwise, to maximize the beauty value of the $k$-subsequence, we need to make characters with high beauty values appear as much as possible in the $k$-subsequence. Therefore, we can sort the values in $f$ in reverse order to get an array $vs$.\n\nWe denote the occurrence of the $k$th character in the array $vs$ as $val$, and there are $x$ characters with an occurrence of $val$.\n\nThen we first find out the characters with occurrences greater than $val$, multiply the occurrences of each character to get the initial answer $ans$, and update the remaining number of characters to be selected to $k$. We need to select $k$ characters from $x$ characters, so the answer needs to be multiplied by the combination number $C_x^k$, and finally multiplied by $val^k$, i.e., $ans = ans \\times C_x^k \\times val^k$.\n\nNote that we need to use fast power and modulo operations here.\n\nThe time complexity is $O(n)$, and the space complexity is $O(|\\Sigma|)$. Here, $n$ is the length of the string, and $\\Sigma$ is the character set. In this problem, the character set is lowercase letters, so $|\\Sigma| = 26$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 2843, "explanations": { "1": "We enumerate each integer $x$ in the range $[low, high]$, and check whether it is a palindromic number. If it is, then the answer $ans$ is increased by $1$.\n\nThe time complexity is $O(n \\times \\log m)$, and the space complexity is $O(\\log m)$. Here, $n$ is the number of integers in the range $[low, high]$, and $m$ is the maximum integer given in the problem." }, "is_english": true, "time_complexity": "O(n \\times \\log m)", "space_complexity": "O(\\log m)" }, { "problem_id": 2844, "explanations": { "1": "We notice that an integer $x$ can be divisible by $25$, i.e., $x \\bmod 25 = 0$. Therefore, we can design a function $dfs(i, k)$, which represents the minimum number of digits to be deleted to make the number a special number, starting from the $i$th digit of the string $num$, and the current number modulo $25$ is $k$. The answer is $dfs(0, 0)$.\n\nThe execution logic of the function $dfs(i, k)$ is as follows:\n\n- If $i = n$, i.e., all digits of the string $num$ have been processed, then if $k = 0$, the current number can be divisible by $25$, return $0$, otherwise return $n$;\n- Otherwise, the $i$th digit can be deleted, in this case one digit needs to be deleted, i.e., $dfs(i + 1, k) + 1$; if the $i$th digit is not deleted, then the value of $k$ becomes $(k \\times 10 + \\textit{num}[i]) \\bmod 25$, i.e., $dfs(i + 1, (k \\times 10 + \\textit{num}[i]) \\bmod 25)$. Take the minimum of these two.\n\nTo prevent repeated calculations, we can use memoization to optimize the time complexity.\n\nThe time complexity is $O(n \\times 25)$, and the space complexity is $O(n \\times 25)$. Here, $n$ is the length of the string $num$." }, "is_english": true, "time_complexity": "O(n \\times 25)", "space_complexity": "O(n \\times 25)" }, { "problem_id": 2845, "explanations": { "1": "The problem requires the number of indices $i$ in an interval that satisfy $nums[i] \\bmod modulo = k$. We can transform the array $nums$ into a $0-1$ array $arr$, where $arr[i] = 1$ indicates $nums[i] \\bmod modulo = k$, otherwise $arr[i] = 0$.\n\nFor an interval $[l, r]$, we can calculate the number of $1$s in $arr[l..r]$ through the prefix sum array $s$, i.e., $s[r] - s[l - 1]$, where $s[0] = 0$.\n\nWe use a hash table $cnt$ to record the number of occurrences of the prefix sum $s \\bmod modulo$, initially $cnt[0]=1$.\n\nNext, we traverse the array $arr$, calculate the prefix sum $s$, add the number of occurrences of $(s-k) \\bmod modulo$ to the answer, and then add $1$ to the number of occurrences of $s \\bmod modulo$.\n\nAfter the traversal ends, return the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2846, "explanations": { "1": "The problem asks for the minimum number of operations to make all edge weights the same on the path between any two points. This is essentially the length of the path between these two points, minus the number of times the most frequently occurring edge appears on the path.\n\nThe length of the path between two points can be obtained by finding the LCA (Lowest Common Ancestor) using binary lifting. Let's denote the two points as $u$ and $v$, and their LCA as $x$. Then, the path length from $u$ to $v$ is $depth(u) + depth(v) - 2 \\times depth(x)$.\n\nAdditionally, we can use an array $cnt[n][26]$ to record the number of occurrences of each edge weight from the root node to each node. Then, the number of times the most frequently occurring edge appears on the path from $u$ to $v$ is $\\max_{0 \\leq j < 26} cnt[u][j] + cnt[v][j] - 2 \\times cnt[x][j]$, where $x$ is the LCA of $u$ and $v$.\n\nThe process of finding the LCA using binary lifting is as follows:\n\nWe denote the depth of each node as $depth$, its parent node as $p$, and $f[i][j]$ as the $2^j$th ancestor of node $i$. Then, for any two points $x$ and $y$, we can find their LCA as follows:\n\n1. If $depth(x) < depth(y)$, then swap $x$ and $y$, i.e., ensure that the depth of $x$ is not less than the depth of $y$;\n2. Next, we continuously raise the depth of $x$ until the depths of $x$ and $y$ are the same, at which point the depths of $x$ and $y$ are both $depth(x)$;\n3. Then, we raise the depths of $x$ and $y$ simultaneously until the parents of $x$ and $y$ are the same, at which point the parents of $x$ and $y$ are both $f[x][0]$, which is the LCA of $x$ and $y$.\n\nFinally, the minimum number of operations from node $u$ to node $v$ is $depth(u) + depth(v) - 2 \\times depth(x) - \\max_{0 \\leq j < 26} cnt[u][j] + cnt[v][j] - 2 \\times cnt[x][j]$.\n\nThe time complexity is $O((n + q) \\times C \\times \\log n)$, and the space complexity is $O(n \\times C \\times \\log n)$. Here, $C$ is the maximum value of the edge weight." }, "is_english": true, "time_complexity": "O((n + q) \\times C \\times \\log n)", "space_complexity": "O(n \\times C \\times \\log n)" }, { "problem_id": 2847, "explanations": { "1": "We consider prime factorizing the number $n$. If there are prime factors greater than $9$ in $n$, then it is impossible to find a number that meets the conditions, because prime factors greater than $9$ cannot be obtained by multiplying numbers from $1$ to $9$. For example, $11$ cannot be obtained by multiplying numbers from $1$ to $9$. Therefore, we only need to consider whether there are prime factors greater than $9$ in $n$. If there are, return $-1$ directly.\n\nOtherwise, if the prime factors include $7$ and $5$, then the number $n$ can first be decomposed into several $7$s and $5$s. Two $3$s can be combined into a $9$, three $2$s can be combined into an $8$, and a $2$ and a $3$ can be combined into a $6$. Therefore, we only need to decompose the number into numbers from $2$ to $9$. We can use a greedy method, preferentially decomposing into $9$, then decomposing into $8$, and so on.\n\nThe time complexity is $O(\\log n)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 2848, "explanations": { "1": "According to the problem description, we need to add one vehicle to each interval $[\\textit{start}_i, \\textit{end}_i]$. We can use a difference array to achieve this.\n\nWe define an array $d$ of length 102. For each interval $[\\textit{start}_i, \\textit{end}_i]$, we increment $d[\\textit{start}_i]$ by 1 and decrement $d[\\textit{end}_i + 1]$ by 1.\n\nFinally, we perform a prefix sum operation on $d$ and count the number of elements in the prefix sum that are greater than 0.\n\nThe time complexity is $O(n + m)$, and the space complexity is $O(m)$, where $n$ is the length of the given array, and $m$ is the maximum value in the array. In this problem, $m \\leq 102$.", "2": "If the range of intervals in the problem is large, we can use a hash table to store the start and end points of the intervals. Then, we sort the keys of the hash table and perform prefix sum statistics.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the given array." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(m)" }, { "problem_id": 2849, "explanations": { "1": "If the starting point and the destination are the same, then we can only reach the destination within the given time if $t \\neq 1$.\n\nOtherwise, we can calculate the difference in the x and y coordinates between the starting point and the destination, and then take the maximum value. If the maximum value is less than or equal to the given time, then we can reach the destination within the given time.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 2850, "explanations": { "1": "The problem is essentially finding the shortest path from the initial state to the target state in a state graph, so we can use BFS to solve it. The initial state is `grid`, and the target state is `[[1, 1, 1], [1, 1, 1], [1, 1, 1]]`. In each operation, we can move a stone greater than $1$ from a cell to an adjacent cell that does not exceed $1$. If the target state is found, we can return the current layer number, which is the minimum number of moves.", "2": "We can put all the coordinates $(i, j)$ of cells with a value of $0$ into an array $left$. If the value $v$ of a cell is greater than $1$, we put $v-1$ coordinates $(i, j)$ into an array $right$. The problem then becomes that each coordinate $(i, j)$ in $right$ needs to be moved to a coordinate $(x, y)$ in $left$, and we need to find the minimum number of moves.\n\nLet's denote the length of $left$ as $n$. We can use an $n$-bit binary number to represent whether each coordinate in $left$ is filled by a coordinate in $right$, where $1$ represents being filled, and $0$ represents not being filled. Initially, $f[i] = \\infty$, and the rest $f[0]=0$.\n\nConsider $f[i]$, let the number of $1$s in the binary representation of $i$ be $k$. We enumerate $j$ in the range $[0..n)$, if the $j$th bit of $i$ is $1$, then $f[i]$ can be transferred from $f[i \\oplus (1 << j)]$, and the cost of the transfer is $cal(left[k-1], right[j])$, where $cal$ represents the Manhattan distance between two coordinates. The final answer is $f[(1 << n) - 1]$.\n\nThe time complexity is $O(n \\times 2^n)$, and the space complexity is $O(2^n)$. Here, $n$ is the length of $left$, and in this problem, $n \\le 9$." }, "is_english": true, "time_complexity": "O(n \\times 2^n)", "space_complexity": "O(2^n)" }, { "problem_id": 2851, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2852, "explanations": { "1": "First, we count the number of non-blocking cells in the matrix, denoted as $cnt$. Then, starting from each non-blocking cell, we use DFS to calculate the sum $s$ of the cells in each connected block and the number of cells $t$. Then, all $(cnt - t)$ cells in other connected blocks can be added with $s$. We sum up the results of all connected blocks.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ is the side length of the matrix." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 2853, "explanations": { "1": "We can first calculate the highest salary for each department, and then calculate the difference between the two highest salaries." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 2854, "explanations": { "1": "We can use the window function `LAG() OVER()` to calculate the difference in days between the current date and the date before the last date for each user. If the difference is $2$, it means that there are continuous data for $3$ days between these two dates. We can use the window function `AVG() OVER()` to calculate the average of these $3$ data." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 2855, "explanations": { "1": "First, we use a pointer $i$ to traverse the array $nums$ from left to right, finding a continuous increasing sequence until $i$ reaches the end of the array or $nums[i - 1] > nums[i]$. Next, we use another pointer $k$ to traverse the array $nums$ from $i + 1$, finding a continuous increasing sequence until $k$ reaches the end of the array or $nums[k - 1] > nums[k]$ and $nums[k] > nums[0]$. If $k$ reaches the end of the array, it means the array is already increasing, so we return $n - i$; otherwise, we return $-1$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2856, "explanations": { "1": "We use a hash table $cnt$ to count the occurrence of each element in the array $nums$, then add each value in $cnt$ to a priority queue (max heap) $pq$. Each time we take out two elements $x$ and $y$ from $pq$, decrease their values by one. If the value after decrement is still greater than $0$, we add the decremented value back to $pq$. Each time we take out two elements from $pq$, it means we delete a pair of numbers from the array, so the length of the array decreases by $2$. When the size of $pq$ is less than $2$, we stop the deletion operation.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2857, "explanations": { "1": "We can use a hash table $cnt$ to count the occurrence of each point in the array $coordinates$.\n\nNext, we enumerate each point $(x_2, y_2)$ in the array $coordinates$. Since the range of $k$ is $[0, 100]$, and the result of $x_1 \\oplus x_2$ or $y_1 \\oplus y_2$ is always greater than or equal to $0$, we can enumerate the result $a$ of $x_1 \\oplus x_2$ in the range $[0,..k]$. Then, the result of $y_1 \\oplus y_2$ is $b = k - a$. In this way, we can calculate the values of $x_1$ and $y_1$, and add the occurrence of $(x_1, y_1)$ to the answer.\n\nThe time complexity is $O(n \\times k)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $coordinates$." }, "is_english": true, "time_complexity": "O(n \\times k)", "space_complexity": "O(n)" }, { "problem_id": 2858, "explanations": { "1": "时间复杂度 $O(n)$,空间复杂度 $O(n)$。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2859, "explanations": { "1": "We directly traverse each index $i$, and check whether the number of $1$s in its binary representation is equal to $k$. If it is, we add the corresponding element to the answer $ans$.\n\nAfter the traversal ends, we return the answer.\n\nThe time complexity is $O(n \\times \\log n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(1)" }, { "problem_id": 2860, "explanations": { "1": "Assume that $k$ students are selected, then the following conditions hold:\n\n- If $nums[i] = k$, then there is no grouping method;\n- If $nums[i] > k$, then student $i$ is not selected;\n- If $nums[i] < k$, then student $i$ is selected.\n\nTherefore, the selected students must be the first $k$ elements in the sorted $nums$ array.\n\nWe enumerate $k$ in the range $[0,..n]$. For the current number of selected students $i$, we can get the maximum student number in the group $i-1$, which is $nums[i-1]$. If $i > 0$ and $nums[i-1] \\ge i$, then there is no grouping method; if $i < n$ and $nums[i] \\le i$, then there is no grouping method. Otherwise, there is a grouping method, and the answer is increased by one.\n\nAfter the enumeration ends, return the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 2861, "explanations": { "1": "We note that all alloys need to be made by the same machine, so we can enumerate which machine to use to make the alloy.\n\nFor each machine, we can use binary search to find the maximum integer $x$ such that we can use this machine to make $x$ alloys. The maximum of all $x$ is the answer.\n\nThe time complexity is $O(n \\times k \\times \\log M)$, where $M$ is the upper bound of the binary search, and in this problem, $M \\leq 2 \\times 10^8$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times k \\times \\log M)", "space_complexity": "O(1)" }, { "problem_id": 2862, "explanations": { "1": "We note that if a number can be expressed in the form of $k \\times j^2$, then all numbers of this form have the same $k$.\n\nTherefore, we can enumerate $k$ in the range $[1,..n]$, and then start enumerating $j$ from $1$, each time adding the value of $nums[k \\times j^2 - 1]$ to $t$, until $k \\times j^2 > n$. At this point, update the answer to $ans = \\max(ans, t)$.\n\nFinally, return the answer $ans$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2863, "explanations": { "1": "The problem is essentially finding the maximum length of the inverse pairs. We can use a hash table $d$ to record the index $i$ corresponding to each number $x$ in the array.\n\nNext, we traverse the keys of the hash table in descending order of the numbers. We maintain a number $k$ to keep track of the smallest index that has appeared so far. For the current number $x$, we can get a maximum inverse pair length of $d[x][|d[x]|-1]-k + 1$, where $|d[x]|$ represents the length of the array $d[x]$, i.e., the number of times the number $x$ appears in the original array. We update the answer accordingly. Then, we update $k$ to $d[x][0]$, which is the index where the number $x$ first appears in the original array. We continue to traverse the keys of the hash table until all keys are traversed.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2864, "explanations": { "1": "First, we count the number of '1's in the string $s$, denoted as $cnt$. Then, we place $cnt - 1$ '1's at the highest position, followed by the remaining $|s| - cnt$ '0's, and finally add one '1'.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2865, "explanations": { "1": "We can enumerate each tower as the tallest tower, each time expanding to the left and right, calculating the height of each other position, and then accumulating to get the height sum $t$. The maximum of all height sums is the answer.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(1)$. Here, $n$ is the length of the array $maxHeights$.", "2": "Solution 1 is sufficient to pass this problem, but the time complexity is relatively high. We can use \"Dynamic Programming + Monotonic Stack\" to optimize the enumeration process.\n\nWe define $f[i]$ to represent the height sum of the beautiful tower scheme with the last tower as the tallest tower among the first $i+1$ towers. We can get the following state transition equation:\n\n$$\nf[i]=\n\\begin{cases}\nf[i-1]+heights[i],&\\textit{if } heights[i]\\geq heights[i-1]\\\\\nheights[i]\\times(i-j)+f[j],&\\textit{if } heights[i] j$, we do not need to perform any operation, and return $0$.\n\nOtherwise, we consider the two endpoints of the interval $[i, j]$:\n\n- If we perform the first operation on endpoint $i$, since the cost $x$ is fixed, the optimal choice is to reverse $idx[i]$ and $idx[j]$, and then recursively calculate $dfs(i + 1, j - 1)$, with a total cost of $dfs(i + 1, j - 1) + x$.\n- If we perform the second operation on endpoint $i$, we need to reverse all the characters in $[idx[i]..idx[i + 1]]$, and then recursively calculate $dfs(i + 2, j)$, with a total cost of $dfs(i + 2, j) + idx[i + 1] - idx[i]$.\n- If we perform the second operation on endpoint $j$, we need to reverse all the characters in $[idx[j - 1]..idx[j]]$, and then recursively calculate $dfs(i, j - 2)$, with a total cost of $dfs(i, j - 2) + idx[j] - idx[j - 1]$.\n\nWe take the minimum value of the above three operations as the value of $dfs(i, j)$.\n\nTo avoid redundant calculations, we can use memoization to record the return value of $dfs(i, j)$ in a 2D array $f$. If $f[i][j]$ is not equal to $-1$, it means that we have already calculated it, so we can directly return $f[i][j]$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ is the length of the strings.", "2": "" }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 2897, "explanations": { "1": "According to the problem description, for an operation, we can change $nums[i]$ to $nums[i] \\textit{ AND } nums[j]$, and change $nums[j]$ to $nums[i] \\textit{ OR } nums[j]$. Let's consider the bits of the numbers. If two bits are both $1$ or both $0$, the result of the operation will not change the bits. If two bits are different, the result of the operation will change the bits to $0$ and $1$, respectively. Therefore, we can move $1$ bits to $0$ bits, but not vice versa.\n\nWe can use an array $cnt$ to count the number of $1$ bits in each position, and then select $k$ numbers from them. To maximize the sum of squares, we should choose the largest numbers as much as possible. This is because, assuming the sum of squares of two numbers is $a^2 + b^2$ (where $a \\gt b$), changing them to $(a + c)^2 + (b - c)^2 = a^2 + b^2 + 2c(a - b) + 2c^2 \\gt a^2 + b^2$ will increase the sum of squares. Therefore, to maximize the sum of squares, we should choose the largest number.\n\nThe time complexity is $O(n \\times \\log M)$, and the space complexity is $O(\\log M)$. Here, $M$ is the maximum value in the array." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(\\log M)" }, { "problem_id": 2898, "explanations": { "1": "We can transform the equation as follows:\n\n$$\nprices[i] - i = prices[j] - j\n$$\n\nIn fact, the problem is to find the maximum sum of all $prices[i]$ under the same $prices[i] - i$.\n\nTherefore, we can use a hash table $cnt$ to store the sum of all $prices[i]$ under the same $prices[i] - i$, and finally take the maximum value in the hash table.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the $prices$ array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2899, "explanations": { "1": "We directly simulate according to the problem description.\n\nDefine an array $\\textit{seen}$ to store the positive integers we have encountered, and an array $\\textit{ans}$ to store the answer. We also need a variable $k$ to record the number of consecutive $-1$s.\n\nWe traverse the array $\\textit{nums}$:\n\n- If the current element $x = -1$, we increment $k$ by 1. If $k$ is greater than the length of $\\textit{seen}$, we append $-1$ to $\\textit{ans}$; otherwise, we append the $k$-th element from the end of $\\textit{seen}$ to $\\textit{ans}$.\n- If the current element $x$ is a positive integer, we reset $k$ to 0 and append $x$ to the end of $\\textit{seen}$.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2900, "explanations": { "1": "We can traverse the array $groups$, and for the current index $i$, if $i=0$ or $groups[i] \\neq groups[i - 1]$, we add $words[i]$ to the answer array.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $groups$. The space complexity is $O(n)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2901, "explanations": { "1": "We define $f[i]$ as the length of the longest adjacent non-equal subsequence ending with the $i$-th word, and $g[i]$ as the predecessor index of the longest adjacent non-equal subsequence ending with the $i$-th word. Initially, we set $f[i] = 1$ and $g[i] = -1$.\n\nIn addition, we define a variable $mx$ to represent the length of the longest adjacent non-equal subsequence.\n\nWe traverse $i$ and $j \\in [0, i)$, and if $groups[i] \\neq groups[j]$, $f[i] \\lt f[j] + 1$, and the Hamming distance between $words[i]$ and $words[j]$ is $1$, we update $f[i] = f[j] + 1$, $g[i] = j$, and update $mx = \\max(mx, f[i])$.\n\nFinally, we find the index $i$ corresponding to the maximum value in the $f$ array, and then continuously search backwards from $i$ until we find $g[i] = -1$, which gives us the longest adjacent non-equal subsequence.\n\nThe time complexity is $O(n^2 \\times L)$, and the space complexity is $O(n)$. Here, $L$ represents the maximum length of a word." }, "is_english": true, "time_complexity": "O(n^2 \\times L)", "space_complexity": "O(n)" }, { "problem_id": 2902, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2903, "explanations": { "1": "We use two pointers $i$ and $j$ to maintain a sliding window with a gap of $indexDifference$, where $j$ and $i$ point to the left and right boundaries of the window, respectively. Initially, $i$ points to $indexDifference$, and $j` points to $0$.\n\nWe use $mi$ and $mx$ to maintain the indices of the minimum and maximum values to the left of pointer $j$.\n\nWhen pointer $i$ moves to the right, we need to update $mi$ and $mx$. If $nums[j] \\lt nums[mi]$, then $mi$ is updated to $j$; if $nums[j] \\gt nums[mx]$, then $mx$ is updated to $j$. After updating $mi$ and $mx$, we can determine whether we have found a pair of indices that satisfy the condition. If $nums[i] - nums[mi] \\ge valueDifference$, then we have found a pair of indices $[mi, i]$ that satisfy the condition; if $nums[mx] - nums[i] >= valueDifference$, then we have found a pair of indices $[mx, i]$ that satisfy the condition.\n\nIf pointer $i$ moves to the end of the array and we have not found a pair of indices that satisfy the condition, we return $[-1, -1]$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2904, "explanations": { "1": "We can enumerate all substrings $s[i: j]$, where $i \\lt j$, and check if they are beautiful substrings. If so, we update the answer.\n\nThe time complexity is $O(n^3)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $s$.", "2": "We can also use two pointers to maintain a sliding window, where pointer $i$ points to the left boundary of the window, and pointer $j$ points to the right boundary of the window. Initially, $i$ and $j$ both point to $0$. In addition, we use a variable $cnt$ to record the number of $1$s in the sliding window.\n\nWe first move pointer $j$ to the right, add $s[j]$ to the sliding window, and update $cnt$. If $cnt$ is greater than $k$, or if $i$ is less than $j$ and $s[i]$ is $0$, we move pointer $i$ to the right and update $cnt$.\n\nWhen $cnt$ equals $k$, we have found a beautiful substring. We compare it with the current answer and update the answer if necessary.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n^3)", "space_complexity": "O(n)" }, { "problem_id": 2905, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2906, "explanations": { "1": "We can preprocess the suffix product (excluding itself) of each element, and then traverse the matrix to calculate the prefix product (excluding itself) of each element. The product of the two gives us the result for each position.\n\nSpecifically, we use $p[i][j]$ to represent the result of the element in the $i$-th row and $j$-th column of the matrix. We define a variable $suf$ to represent the product of all elements below and to the right of the current position. Initially, $suf$ is set to $1$. We start traversing from the bottom right corner of the matrix. For each position $(i, j)$, we assign $suf$ to $p[i][j]$, and then update $suf$ to $suf \\times grid[i][j] \\bmod 12345$. This way, we can obtain the suffix product of each position.\n\nNext, we start traversing from the top left corner of the matrix. For each position $(i, j)$, we multiply $p[i][j]$ by $pre$, take the result modulo $12345$, and then update $pre$ to $pre \\times grid[i][j] \\bmod 12345$. This way, we can obtain the prefix product of each position.\n\nAfter the traversal, we return the result matrix $p$.\n\nThe time complexity is $O(n \\times m)$, where $n$ and $m$ are the number of rows and columns in the matrix, respectively. Ignoring the space occupied by the result matrix, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times m)", "space_complexity": "O(1)" }, { "problem_id": 2907, "explanations": { "1": "We can enumerate the middle element $profits[j]$, and then enumerate the left element $profits[i]$ and the right element $profits[k]$. For each $profits[j]$, we need to find the maximum $profits[i]$ and the maximum $profits[k]$ such that $prices[i] < prices[j] < prices[k]$. We define $left$ as the maximum value on the left of $profits[j]$, and $right$ as the maximum value on the right of $profits[j]$. If they exist, we update the answer as $ans = \\max(ans, left + profits[j] + right)$.\n\nThe time complexity is $O(n^2)$, where $n$ is the length of the array. The space complexity is $O(1)$.", "2": "We can use two Binary Indexed Trees (BITs) to maintain the maximum profit on the left and right of each price, respectively. Then, we enumerate the middle price, query the maximum profit on both sides through the BIT, and finally take the maximum value.\n\nThe time complexity is $O(n \\times \\log M)$, and the space complexity is $O(M)$. Here, $n$ is the length of the array $prices$, and $M$ is the maximum value in the array $prices$. In this problem, $M \\le 10^6$.\n\nSince the length of $prices$ does not exceed $2000$, and the value of $prices[i]$ reaches $10^6$, we can discretize $prices$, which can reduce the space complexity to $O(n)$.", "3": "" }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(1)" }, { "problem_id": 2908, "explanations": { "1": "We can preprocess the minimum value on the right side of each position and record it in the array $right[i]$, where $right[i]$ represents the minimum value in $nums[i+1..n-1]$.\n\nNext, we enumerate the middle element $nums[i]$ of the mountain triplet from left to right, and use a variable $left$ to represent the minimum value in $ums[0..i-1]$, and a variable $ans$ to represent the current minimum element sum found. For each $i$, we need to find the element $nums[i]$ that satisfies $left < nums[i]$ and $right[i+1] < nums[i]$, and update $ans$.\n\nFinally, if $ans$ is still the initial value, it means that there is no mountain triplet, and we return $-1$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2909, "explanations": { "1": "We can preprocess the minimum value on the right side of each position and record it in the array $right[i]$, where $right[i]$ represents the minimum value in $nums[i+1..n-1]$.\n\nNext, we enumerate the middle element $nums[i]$ of the mountain triplet from left to right, and use a variable $left$ to represent the minimum value in $ums[0..i-1]$, and a variable $ans$ to represent the current minimum element sum found. For each $i$, we need to find the element $nums[i]$ that satisfies $left < nums[i]$ and $right[i+1] < nums[i]$, and update $ans$.\n\nFinally, if $ans$ is still the initial value, it means that there is no mountain triplet, and we return $-1$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2910, "explanations": { "1": "We use a hash table $cnt$ to count the number of occurrences of each number in the array $nums$. Let $k$ be the minimum value of the number of occurrences, and then we can enumerate the size of the groups in the range $[k,..1]$. Since the difference in size between each group is not more than $1$, the group size can be either $k$ or $k+1$.\n\nFor the current group size $k$ being enumerated, we traverse each occurrence $v$ in the hash table. If $\\lfloor \\frac{v}{k} \\rfloor < v \\bmod k$, it means that we cannot divide the occurrence $v$ into $k$ or $k+1$ groups with the same value, so we can skip this group size $k$ directly. Otherwise, it means that we can form groups, and we only need to form as many groups of size $k+1$ as possible to ensure the minimum number of groups. Therefore, we can divide $v$ numbers into $\\lceil \\frac{v}{k+1} \\rceil$ groups and add them to the current enumerated answer. Since we enumerate $k$ from large to small, as long as we find a valid grouping scheme, it must be optimal.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2911, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2912, "explanations": { "1": "We define the following states:\n\n- $f[0]$ represents the number of ways to move from `source` to `source` itself;\n- $f[1]$ represents the number of ways to move from `source` to another row in the same column;\n- $f[2]$ represents the number of ways to move from `source` to another column in the same row;\n- $f[3]$ represents the number of ways to move from `source` to another row and another column.\n\nInitially, $f[0] = 1$, and the other states are all $0$.\n\nFor each state, we can calculate the current state based on the previous state, as follows:\n\n$$\n\\begin{aligned}\ng[0] &= (n - 1) \\times f[1] + (m - 1) \\times f[2] \\\\\ng[1] &= f[0] + (n - 2) \\times f[1] + (m - 1) \\times f[3] \\\\\ng[2] &= f[0] + (m - 2) \\times f[2] + (n - 1) \\times f[3] \\\\\ng[3] &= f[1] + f[2] + (n - 2) \\times f[3] + (m - 2) \\times f[3]\n\\end{aligned}\n$$\n\nWe loop $k$ times, and finally check whether `source` and `dest` are in the same row or column, and return the corresponding state.\n\nThe time complexity is $O(k)$, where $k$ is the number of moves. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(k)", "space_complexity": "O(1)" }, { "problem_id": 2913, "explanations": { "1": "We can enumerate the left endpoint index $i$ of the subarray, and for each $i$, we enumerate the right endpoint index $j$ in the range $[i, n)$, and calculate the distinct count of $nums[i..j]$ by adding the count of $nums[j]$ to a set $s$, and then taking the square of the size of $s$ as the contribution of $nums[i..j]$ to the answer.\n\nAfter the enumeration, we return the answer.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 2914, "explanations": { "1": "We only need to traverse all odd indices $1, 3, 5, \\cdots$ of the string $s$. If the current odd index is different from the previous index, i.e., $s[i] \\ne s[i - 1]$, we need to modify the current character so that $s[i] = s[i - 1]$. Therefore, the answer needs to be incremented by $1$.\n\nAfter the traversal, we return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2915, "explanations": { "1": "We define $f[i][j]$ as the length of the longest subsequence that selects several numbers from the first $i$ numbers and the sum of these numbers is exactly $j$. Initially, $f[0][0]=0$, and all other positions are $-\\infty$.\n\nFor $f[i][j]$, we consider the $i$th number $x$. If we do not select $x$, then $f[i][j]=f[i-1][j]$. If we select $x$, then $f[i][j]=f[i-1][j-x]+1$, where $j\\ge x$. Therefore, we have the state transition equation:\n\n$$\nf[i][j]=\\max\\{f[i-1][j],f[i-1][j-x]+1\\}\n$$\n\nThe final answer is $f[n][target]$. If $f[n][target]\\le0$, there is no subsequence with a sum of $target$, return $-1$.\n\nThe time complexity is $O(n\\times target)$, and the space complexity is $O(n\\times target)$. Here, $n$ is the length of the array, and $target$ is the target value.\n\nWe notice that the state of $f[i][j]$ is only related to $f[i-1][\\cdot]$, so we can optimize the first dimension and reduce the space complexity to $O(target)$.", "2": "" }, "is_english": true, "time_complexity": "O(n\\times target)", "space_complexity": "O(n\\times target)" }, { "problem_id": 2916, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2917, "explanations": { "1": "We can enumerate each bit $i$ in the range $[0, 32)$, and count the number of numbers in the array $nums$ whose $i$-th bit is $1$, denoted as $cnt$. If $cnt \\ge k$, we add $2^i$ to the answer.\n\nAfter the enumeration, we return the answer.\n\nThe time complexity is $O(n \\times \\log M)$, where $n$ and $M$ are the length of the array $nums$ and the maximum value in $nums$, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(1)" }, { "problem_id": 2918, "explanations": { "1": "We consider the case where we treat all $0$s in the array as $1$s, and calculate the sum of the two arrays separately, denoted as $s_1$ and $s_2$. Without loss of generality, we assume that $s_1 \\le s_2$.\n\n- If $s_1 = s_2$, then the answer is $s_1$.\n- If $s_1 \\lt s_2$, then there must exist a $0$ in $nums1$ to make the sum of the two arrays equal. In this case, the answer is $s_2$. Otherwise, it means that it is impossible to make the sum of the two arrays equal, and we return $-1$.\n\nThe time complexity is $O(n + m)$, where $n$ and $m$ are the lengths of the arrays $nums1$ and $nums2$, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(1)" }, { "problem_id": 2919, "explanations": { "1": "We define $f$, $g$, and $h$ as the minimum number of increment operations needed to get the maximum value from the last three items in the first $i$ items, initially $f = 0$, $g = 0$, $h = 0$.\n\nNext, we traverse the array $nums$. For each $x$, we need to update the values of $f$, $g$, and $h$ to meet the requirements of the problem, that is:\n\n$$\n\\begin{aligned}\nf' &= g \\\\\ng' &= h \\\\\nh' &= \\min(f, g, h) + \\max(k - x, 0)\n\\end{aligned}\n$$\n\nFinally, we only need to return the minimum value among $f$, $g$, and $h$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2920, "explanations": { "1": "First, we construct a graph $g$ based on the edges given in the problem, where $g[i]$ represents all adjacent nodes of node $i$. Then we can use the method of memoization search to solve this problem.\n\nWe design a function $dfs(i, fa, j)$, which represents that the current node is $i$, the parent node is $fa$, the number of gold coins of the current node needs to be shifted to the right by $j$ bits, and the maximum score that can be obtained.\n\nThe execution process of the function $dfs(i, fa, j)$ is as follows:\n\nIf we use the first method to collect the gold coins of the current node, then the score of the current node is $(coins[i] >> j) - k$. Then we traverse all the adjacent nodes $c$ of the current node. If $c$ is not equal to $fa$, then we add the result of $dfs(c, i, j)$ to the score of the current node.\n\nIf we use the second method to collect the gold coins of the current node, then the score of the current node is $coins[i] >> (j + 1)$. Then we traverse all the adjacent nodes $c$ of the current node. If $c$ is not equal to $fa$, then we add the result of $dfs(c, i, j + 1)$ to the score of the current node. Note that since the maximum value of $coins[i]$ given in the problem is $10^4$, we can only shift to the right by at most $14$ bits, so that the value of $coins[i] >> (j + 1)$ is $0$.\n\nFinally, we return the maximum score that can be obtained by using the two methods at the current node.\n\nIn order to avoid repeated calculations, we use the method of memoization search and store the result of $dfs(i, fa, j)$ in $f[i][j]$, where $f[i][j]$ represents that the current node is $i$, the parent node is $fa$, the number of gold coins of the current node needs to be shifted to the right by $j$ bits, and the maximum score that can be obtained.\n\nThe time complexity is $O(n \\times \\log M)$, and the space complexity is $O(n \\times \\log M)$. Where $M$ represents the maximum value of $coins[i]$." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(n \\times \\log M)" }, { "problem_id": 2921, "explanations": { "1": "We can use two Binary Indexed Trees (BITs) to maintain the maximum profit on the left and right of each price, respectively. Then, we enumerate the middle price, query the maximum profit on both sides through the BIT, and finally take the maximum value.\n\nThe time complexity is $O(n \\times \\log M)$, and the space complexity is $O(M)$. Here, $n$ is the length of the array $prices$, and $M$ is the maximum value in the array $prices$. In this problem, $M \\le 5000$." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(M)" }, { "problem_id": 2922, "explanations": { "1": "We can use equijoin to connect the `Orders` table and the `Users` table according to `seller_id`, then connect `Items` according to `item_id`, and filter out the records where `item_brand` is not equal to `favorite_brand`. Then, group by `seller_id` and count the number of `item_id` corresponding to each `seller_id`. Finally, use a subquery to find the `seller_id` with the most `item_id`." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 2923, "explanations": { "1": "We can enumerate each team $i$. If team $i$ has won every match, then team $i$ is the champion, and we can directly return $i$.\n\nThe time complexity is $O(n^2)$, where $n$ is the number of teams. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(1)" }, { "problem_id": 2924, "explanations": { "1": "Based on the problem description, we only need to count the in-degrees of each node and record them in an array $indeg$. If only one node has an in-degree of $0$, then this node is the champion; otherwise, there is no unique champion.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes.", "2": "" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2925, "explanations": { "1": "The problem is actually asking us to select some nodes from all nodes of the tree so that the sum of these nodes' values is maximized, and there is one node on each path from the root node to the leaf node that is not selected.\n\nWe can use the method of tree DP to solve this problem.\n\nWe design a function $dfs(i, fa)$, where $i$ represents the current node with node $i$ as the root of the subtree, and $fa$ represents the parent node of $i$. The function returns an array of length $2$, where $[0]$ represents the sum of the values of all nodes in the subtree, and $[1]$ represents the maximum value of the subtree satisfying that there is one node not selected on each path.\n\nThe value of $[0]$ can be obtained directly by DFS accumulating the values of each node, while the value of $[1]$ needs to consider two situations, namely whether node $i$ is selected. If it is selected, then each subtree of node $i$ must satisfy that there is one node not selected on each path; if it is not selected, then all nodes of each subtree of node $i$ can be selected. We take the maximum of these two situations.\n\nIt should be noted that the value of $[1]$ of the leaf node is $0$, because the leaf node has no subtree, so there is no need to consider the situation where there is one node not selected on each path.\n\nThe answer is $dfs(0, -1)[1]$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2926, "explanations": { "1": "According to the problem description, we can transform the inequality $nums[i] - nums[j] \\ge i - j$ into $nums[i] - i \\ge nums[j] - j$. Therefore, we consider defining a new array $arr$, where $arr[i] = nums[i] - i$. A balanced subsequence satisfies that for any $j < i$, $arr[j] \\le arr[i]$. The problem is transformed into selecting an increasing subsequence in $arr$ such that the corresponding sum in $nums$ is maximized.\n\nSuppose $i$ is the index of the last element in the subsequence, then we consider the index $j$ of the second to last element in the subsequence. If $arr[j] \\le arr[i]$, we can consider whether to add $j$ to the subsequence.\n\nTherefore, we define $f[i]$ as the maximum sum of $nums$ when the index of the last element in the subsequence is $i$. The answer is $\\max_{i=0}^{n-1} f[i]$.\n\nThe state transition equation is:\n\n$$\nf[i] = \\max(\\max_{j=0}^{i-1} f[j], 0) + nums[i]\n$$\n\nwhere $j$ satisfies $arr[j] \\le arr[i]$.\n\nWe can use a Binary Indexed Tree to maintain the maximum value of the prefix, i.e., for each $arr[i]$, we maintain the maximum value of $f[i]$ in the prefix $arr[0..i]$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2927, "explanations": { "1": "According to the problem description, we need to distribute $n$ candies to $3$ children, with each child receiving between $[0, limit]$ candies.\n\nThis is equivalent to placing $n$ balls into $3$ boxes. Since the boxes can be empty, we can add $3$ virtual balls, and then use the method of inserting partitions, i.e., there are a total of $n + 3$ balls, and we insert $2$ partitions among the $n + 3 - 1$ positions, thus dividing the actual $n$ balls into $3$ groups, and allowing the boxes to be empty. Therefore, the initial number of schemes is $C_{n + 2}^2$.\n\nWe need to exclude the schemes where the number of balls in a box exceeds $limit$. Consider that there is a box where the number of balls exceeds $limit$, then the remaining balls (including virtual balls) have at most $n + 3 - (limit + 1) = n - limit + 2$, and the number of positions is $n - limit + 1$, so the number of schemes is $C_{n - limit + 1}^2$. Since there are $3$ boxes, the number of such schemes is $3 \\times C_{n - limit + 1}^2$. In this way, we will exclude too many schemes where the number of balls in two boxes exceeds $limit$ at the same time, so we need to add the number of such schemes, i.e., $3 \\times C_{n - 2 \\times limit}^2$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 2928, "explanations": { "1": "According to the problem description, we need to distribute $n$ candies to $3$ children, with each child receiving between $[0, limit]$ candies.\n\nThis is equivalent to placing $n$ balls into $3$ boxes. Since the boxes can be empty, we can add $3$ virtual balls, and then use the method of inserting partitions, i.e., there are a total of $n + 3$ balls, and we insert $2$ partitions among the $n + 3 - 1$ positions, thus dividing the actual $n$ balls into $3$ groups, and allowing the boxes to be empty. Therefore, the initial number of schemes is $C_{n + 2}^2$.\n\nWe need to exclude the schemes where the number of balls in a box exceeds $limit$. Consider that there is a box where the number of balls exceeds $limit$, then the remaining balls (including virtual balls) have at most $n + 3 - (limit + 1) = n - limit + 2$, and the number of positions is $n - limit + 1$, so the number of schemes is $C_{n - limit + 1}^2$. Since there are $3$ boxes, the number of such schemes is $3 \\times C_{n - limit + 1}^2$. In this way, we will exclude too many schemes where the number of balls in two boxes exceeds $limit$ at the same time, so we need to add the number of such schemes, i.e., $3 \\times C_{n - 2 \\times limit}^2$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 2929, "explanations": { "1": "According to the problem description, we need to distribute $n$ candies to $3$ children, with each child receiving between $[0, limit]$ candies.\n\nThis is equivalent to placing $n$ balls into $3$ boxes. Since the boxes can be empty, we can add $3$ virtual balls, and then use the method of inserting partitions, i.e., there are a total of $n + 3$ balls, and we insert $2$ partitions among the $n + 3 - 1$ positions, thus dividing the actual $n$ balls into $3$ groups, and allowing the boxes to be empty. Therefore, the initial number of schemes is $C_{n + 2}^2$.\n\nWe need to exclude the schemes where the number of balls in a box exceeds $limit$. Consider that there is a box where the number of balls exceeds $limit$, then the remaining balls (including virtual balls) have at most $n + 3 - (limit + 1) = n - limit + 2$, and the number of positions is $n - limit + 1$, so the number of schemes is $C_{n - limit + 1}^2$. Since there are $3$ boxes, the number of such schemes is $3 \\times C_{n - limit + 1}^2$. In this way, we will exclude too many schemes where the number of balls in two boxes exceeds $limit$ at the same time, so we need to add the number of such schemes, i.e., $3 \\times C_{n - 2 \\times limit}^2$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 2930, "explanations": { "1": "We design a function $dfs(i, l, e, t)$, which represents the number of good strings that can be formed when the remaining string length is $i$, and there are at least $l$ characters 'l', $e$ characters 'e' and $t$ characters 't'. The answer is $dfs(n, 0, 0, 0)$.\n\nThe execution logic of the function $dfs(i, l, e, t)$ is as follows:\n\nIf $i = 0$, it means that the current string has been constructed. If $l = 1$, $e = 2$ and $t = 1$, it means that the current string is a good string, return $1$, otherwise return $0$.\n\nOtherwise, we can consider adding any lowercase letter other than 'l', 'e', 't' at the current position, there are 23 in total, so the number of schemes obtained at this time is $dfs(i - 1, l, e, t) \\times 23$.\n\nWe can also consider adding 'l' at the current position, and the number of schemes obtained at this time is $dfs(i - 1, \\min(1, l + 1), e, t)$. Similarly, the number of schemes for adding 'e' and 't' are $dfs(i - 1, l, \\min(2, e + 1), t)$ and $dfs(i - 1, l, e, \\min(1, t + 1))$ respectively. Add them up and take the modulus of $10^9 + 7$ to get the value of $dfs(i, l, e, t)$.\n\nTo avoid repeated calculations, we can use memorization search.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string.", "2": "We can consider reverse thinking, that is, calculate the number of strings that do not contain the substring \"leet\", and then subtract this number from the total.\n\nWe divide it into the following cases:\n\n- Case $a$: represents the number of schemes where the string does not contain the character 'l', so we have $a = 25^n$.\n- Case $b$: similar to $a$, represents the number of schemes where the string does not contain the character 't', so we have $b = 25^n$.\n- Case $c$: represents the number of schemes where the string does not contain the character 'e' or only contains one character 'e', so we have $c = 25^n + n \\times 25^{n - 1}$.\n- Case $ab$: represents the number of schemes where the string does not contain the characters 'l' and 't', so we have $ab = 24^n$.\n- Case $ac$: represents the number of schemes where the string does not contain the characters 'l' and 'e' or only contains one character 'e', so we have $ac = 24^n + n \\times 24^{n - 1}$.\n- Case $bc$: similar to $ac$, represents the number of schemes where the string does not contain the characters 't' and 'e' or only contains one character 'e', so we have $bc = 24^n + n \\times 24^{n - 1}$.\n- Case $abc$: represents the number of schemes where the string does not contain the characters 'l', 't' and 'e' or only contains one character 'e', so we have $abc = 23^n + n \\times 23^{n - 1}$.\n\nThen according to the inclusion-exclusion principle, $a + b + c - ab - ac - bc + abc$ is the number of strings that do not contain the substring \"leet\".\n\nThe total number $tot = 26^n$, so the answer is $tot - (a + b + c - ab - ac - bc + abc)$, remember to take the modulus of $10^9 + 7$.\n\nThe time complexity is $O(\\log n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the string." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2931, "explanations": { "1": "According to the problem description, we should prioritize purchasing items with smaller values and leave items with larger values to be purchased later in order to maximize the total cost. Therefore, we use a priority queue (min-heap) to store the smallest value item that has not been purchased in each store. Initially, we add the rightmost item in each store to the priority queue.\n\nEach day, we take out the item with the smallest value from the priority queue, add it to the answer, and add the previous item in the store where the item is located to the priority queue. We repeat the above operation until the priority queue is empty.\n\nThe time complexity is $O(m \\times n \\times \\log m)$, and the space complexity is $O(m)$. Here, $m$ and $n$ are the number of rows and columns of the array $values$, respectively." }, "is_english": true, "time_complexity": "O(m \\times n \\times \\log m)", "space_complexity": "O(m)" }, { "problem_id": 2932, "explanations": { "1": "We can enumerate each pair of numbers $(x, y)$ in the array. If $|x - y| \\leq \\min(x, y)$, then this pair is a strong pair. We can calculate the XOR value of this pair and update the answer.\n\nThe time complexity is $O(n^2)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$.", "2": "Observing the inequality $|x - y| \\leq \\min(x, y)$, which involves absolute value and minimum value, we can assume $x \\leq y$, then we have $y - x \\leq x$, that is, $y \\leq 2x$. We can enumerate $y$ from small to large, then $x$ must satisfy the inequality $y \\leq 2x$.\n\nTherefore, we sort the array $nums$, and then enumerate $y$ from small to large. We use two pointers to maintain a window so that the elements $x$ in the window satisfy the inequality $y \\leq 2x$. We can use a binary trie to maintain the elements in the window, so we can find the maximum XOR value in the window in $O(1)$ time. Each time we add $y$ to the trie, and remove the elements at the left end of the window that do not satisfy the inequality, this can ensure that the elements in the window satisfy the inequality $y \\leq 2x$. Then query the maximum XOR value from the trie and update the answer.\n\nThe time complexity is $O(n \\times \\log M)$, and the space complexity is $O(n \\times \\log M)$. Here, $n$ is the length of the array $nums$, and $M$ is the maximum value in the array $nums$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(1)" }, { "problem_id": 2933, "explanations": { "1": "We use a hash table $d$ to store all access times of each employee, where the key is the employee's name, and the value is an integer array, representing all access times of the employee, which are the number of minutes from the start of the day at 00:00.\n\nFor each employee, we sort all their access times in ascending order. Then we traverse all access times of the employee. If there are three consecutive access times $t_1, t_2, t_3$ that satisfy $t_3 - t_1 < 60$, then the employee is a high-frequency visitor, and we add their name to the answer array.\n\nFinally, we return the answer array.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the number of access records." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2934, "explanations": { "1": "We can discuss two cases:\n\n1. Do not swap the values of $nums1[n - 1]$ and $nums2[n - 1]$\n2. Swap the values of $nums1[n - 1]$ and $nums2[n - 1]$\n\nFor each case, we denote the last values of the arrays $nums1$ and $nums2$ as $x$ and $y$, respectively. Then we traverse the first $n - 1$ values of the arrays $nums1$ and $nums2$, and use a variable $cnt$ to record the number of swaps. If $nums1[i] \\leq x$ and $nums2[i] \\leq y$, then no swap is needed. Otherwise, if $nums1[i] \\leq y$ and $nums2[i] \\leq x$, then a swap is needed. If neither condition is met, return $-1$. Finally, return $cnt$.\n\nWe denote the number of swaps in the two cases as $a$ and $b$, respectively. If $a + b = -2$, then it is impossible to satisfy both conditions, so return $-1$. Otherwise, return $\\min(a, b + 1)$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2935, "explanations": { "1": "Observing the inequality $|x - y| \\leq \\min(x, y)$, which involves absolute value and minimum value, we can assume $x \\leq y$, then we have $y - x \\leq x$, that is, $y \\leq 2x$. We can enumerate $y$ from small to large, then $x$ must satisfy the inequality $y \\leq 2x$.\n\nTherefore, we sort the array $nums$, and then enumerate $y$ from small to large. We use two pointers to maintain a window so that the elements $x$ in the window satisfy the inequality $y \\leq 2x$. We can use a binary trie to maintain the elements in the window, so we can find the maximum XOR value in the window in $O(1)$ time. Each time we add $y$ to the trie, and remove the elements at the left end of the window that do not satisfy the inequality, this can ensure that the elements in the window satisfy the inequality $y \\leq 2x$. Then query the maximum XOR value from the trie and update the answer.\n\nThe time complexity is $O(n \\times \\log M)$, and the space complexity is $O(n \\times \\log M)$. Here, $n$ is the length of the array $nums$, and $M$ is the maximum value in the array $nums$. In this problem, $M = 2^{20}$." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(n \\times \\log M)" }, { "problem_id": 2936, "explanations": { "1": "We can use binary search to find the right boundary of each block. Specifically, we traverse the array from left to right. For each index $i$, we use binary search to find the smallest index $j$ such that all elements between $[i,j)$ are equal to $nums[i]$. Then we update $i$ to $j$ and continue to traverse the array until $i$ is greater than or equal to the length of the array.\n\nThe time complexity is $O(m \\times \\log n)$, where $m$ is the number of different elements in the array $num$, and $n$ is the length of the array $num$. The space complexity is $O(1)$.", "2": "We can use the divide and conquer method to calculate the answer. Specifically, we divide the array into two subarrays, recursively calculate the answer for each subarray, and then merge the answers. If the last element of the first subarray is equal to the first element of the second subarray, then we need to subtract one from the answer.\n\nThe time complexity is $O(\\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array $num$." }, "is_english": true, "time_complexity": "O(m \\times \\log n)", "space_complexity": "O(1)" }, { "problem_id": 2937, "explanations": { "1": "According to the problem description, we know that if the three strings are equal after deleting characters, then they have a common prefix of length greater than $1$. Therefore, we can enumerate the position $i$ of the common prefix. If the three characters at the current index $i$ are not all equal, then the length of the common prefix is $i$. At this point, we check if $i$ is $0$. If it is, return $-1$. Otherwise, return $s - 3 \\times i$, where $s$ is the sum of the lengths of the three strings.\n\nThe time complexity is $O(n)$, where $n$ is the minimum length of the three strings. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2938, "explanations": { "1": "We consider moving all the '1's to the rightmost side. We use a variable $cnt$ to record the current number of '1's that have been moved to the rightmost side, and a variable $ans$ to record the number of moves.\n\nWe traverse the string from right to left. If the current position is '1', then we increment $cnt$ by one, and add $n - i - cnt$ to $ans$, where $n$ is the length of the string. Finally, we return $ans$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2939, "explanations": { "1": "According to the problem description, we can assign a number to the $[0..n)$ bits of $a$ and $b$ in binary at the same time, so that the product of $a$ and $b$ is maximized.\n\nTherefore, we first extract the parts of $a$ and $b$ that are higher than the $n$ bits, denoted as $ax$ and $bx$.\n\nNext, we consider each bit in $[0..n)$ from high to low. We denote the current bits of $a$ and $b$ as $x$ and $y$.\n\nIf $x = y$, then we can set the current bit of $ax$ and $bx$ to $1$ at the same time. Therefore, we update $ax = ax \\mid 1 << i$ and $bx = bx \\mid 1 << i$. Otherwise, if $ax < bx$, to maximize the final product, we should set the current bit of $ax$ to $1$. Otherwise, we can set the current bit of $bx$ to $1$.\n\nFinally, we return $ax \\times bx \\bmod (10^9 + 7)$ as the answer.\n\nThe time complexity is $O(n)$, where $n$ is the integer given in the problem. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2940, "explanations": { "1": "Let's denote $queries[i] = [l_i, r_i]$, where $l_i \\le r_i$. If $l_i = r_i$ or $heights[l_i] < heights[r_i]$, then the answer is $r_i$. Otherwise, we need to find the smallest $j$ among all $j > r_i$ and $heights[j] > heights[l_i]$.\n\nWe can sort $queries$ in descending order of $r_i$, and use a pointer $j$ to point to the current index of $heights$ being traversed.\n\nNext, we traverse each query $queries[i] = (l, r)$. For the current query, if $j > r$, then we loop to insert $heights[j]$ into the binary indexed tree. The binary indexed tree maintains the minimum index of the suffix height (after discretization). Then, we judge whether $l = r$ or $heights[l] < heights[r]$. If it is, then the answer to the current query is $r$. Otherwise, we query the minimum index of $heights[l]$ in the binary indexed tree, which is the answer to the current query.\n\nThe time complexity is $O((n + m) \\times \\log n + m \\times \\log m)$, and the space complexity is $O(n + m)$. Where $n$ and $m$ are the lengths of $heights$ and $queries$ respectively.\n\nSimilar problems:\n\n- [2736. Maximum Sum Queries](https://github.com/doocs/leetcode/blob/main/solution/2700-2799/2736.Maximum%20Sum%20Queries/README_EN.md)" }, "is_english": true, "time_complexity": "O((n + m) \\times \\log n + m \\times \\log m)", "space_complexity": "O(n + m)" }, { "problem_id": 2941, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2942, "explanations": { "1": "We directly traverse each string `words[i]` in the string array `words`. If `x` appears in `words[i]`, we add `i` to the answer array.\n\nAfter the traversal, we return the answer array.\n\nThe time complexity is $O(L)$, where $L$ is the sum of the lengths of all strings in the array `words`. Ignoring the space consumption of the answer array, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(L)", "space_complexity": "O(1)" }, { "problem_id": 2943, "explanations": { "1": "The problem essentially asks us to find the length of the longest consecutive increasing subsequence in the array, and then add $1$.\n\nWe define a function $f(\\textit{nums})$ to represent the length of the longest consecutive increasing subsequence in the array $\\textit{nums}$.\n\nFor the array $\\textit{nums}$, we first sort it, then iterate through the array. If the current element $\\textit{nums}[i]$ equals the previous element $\\textit{nums}[i - 1]$ plus $1$, it means the current element can be added to the consecutive increasing subsequence. Otherwise, the current element cannot be added to the consecutive increasing subsequence, and we need to restart counting the length of the consecutive increasing subsequence. Finally, we return the length of the consecutive increasing subsequence plus $1$.\n\nAfter finding the lengths of the longest consecutive increasing subsequences in $\\textit{hBars}$ and $\\textit{vBars}$, we take the minimum of the two as the side length of the square, and then calculate the area of the square.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{hBars}$ or $\\textit{vBars}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2944, "explanations": { "1": "We define a function $\\textit{dfs}(i)$ to represent the minimum number of coins needed to buy all the fruits starting from the $i$-th fruit. The answer is $\\textit{dfs}(1)$.\n\nThe execution logic of the function $\\textit{dfs}(i)$ is as follows:\n\n- If $i \\times 2 \\geq n$, it means that buying the $(i - 1)$-th fruit is sufficient, and the remaining fruits can be obtained for free, so return $\\textit{prices}[i - 1]$.\n- Otherwise, we can buy fruit $i$, and then choose a fruit $j$ to start buying from the next $i + 1$ to $2i + 1$ fruits. Thus, $\\textit{dfs}(i) = \\textit{prices}[i - 1] + \\min_{i + 1 \\le j \\le 2i + 1} \\textit{dfs}(j)$.\n\nTo avoid redundant calculations, we use memoization to store the results that have already been computed. When encountering the same situation again, we directly return the result.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{prices}$.", "2": "We can rewrite the memoization search in Solution 1 into a dynamic programming form.\n\nSimilar to Solution 1, we define $f[i]$ to represent the minimum number of coins needed to buy all the fruits starting from the $i$-th fruit. The answer is $f[1]$.\n\nThe state transition equation is $f[i] = \\min_{i + 1 \\le j \\le 2i + 1} f[j] + \\textit{prices}[i - 1]$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{prices}$.\n\nIn the code implementation, we can directly use the $\\textit{prices}$ array to store the $f$ array, thus optimizing the space complexity to $O(1)$.", "3": "Observing the state transition equation in Solution 2, we can see that for each $i$, we need to find the minimum value of $f[i + 1], f[i + 2], \\cdots, f[2i + 1]$. As $i$ decreases, the range of these values also decreases. This is essentially finding the minimum value in a sliding window with a narrowing range, which can be optimized using a monotonic queue.\n\nWe calculate from back to front, maintaining a monotonically increasing queue $q$, where the queue stores indices. If the front element of $q$ is greater than $i \\times 2 + 1$, it means that the elements after $i$ will not be used, so we dequeue the front element. If $i$ is not greater than $(n - 1) / 2$, we can add $\\textit{prices}[q[0] - 1]$ to $\\textit{prices}[i - 1]$, and then add $i$ to the back of the queue. If the fruit price corresponding to the back element of $q$ is greater than or equal to $\\textit{prices}[i - 1]$, we dequeue the back element until the fruit price corresponding to the back element is less than $\\textit{prices}[i - 1]$ or the queue is empty, then add $i$ to the back of the queue.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{prices}$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 2945, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2946, "explanations": { "1": "We iterate over each element of the matrix and check whether its position after the cyclic shift is the same as the element at the original position.\n\nFor odd-indexed rows, we shift elements to the right by $k$ positions, so element $(i, j)$ moves to position $(i, (j + k) \\bmod n)$ after the cyclic shift, where $n$ is the number of columns.\n\nFor even-indexed rows, we shift elements to the left by $k$ positions, so element $(i, j)$ moves to position $(i, (j - k + n) \\bmod n)$ after the cyclic shift.\n\nIf at any point during the traversal we find that an element's position after the cyclic shift differs from the original, we return $\\text{false}$. If all elements remain the same after the full traversal, we return $\\text{true}$.\n\nThe time complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns of the matrix, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(1)" }, { "problem_id": 2947, "explanations": { "1": "We enumerate the starting position $i$ of the substring in the range $[0, n)$, and the ending position $j$ in the range $[i, n)$, count the number of vowels and consonants in the substring $s[i \\dots j]$, and check whether it is a beautiful substring. If so, we increment the answer by $1$.\n\nThe time complexity is $O(n^2)$, where $n$ is the length of the string. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(1)" }, { "problem_id": 2948, "explanations": { "1": "According to the problem description, the sorted array $\\textit{nums}$ can be partitioned into several subarrays such that the difference between adjacent elements in each subarray does not exceed $\\textit{limit}$.\n\nThe lexicographically smallest array obtainable through swapping is thus the one where the elements within each subarray are sorted and placed back into their original positions in order.\n\nWe first pair each element in $\\textit{nums}$ with its index to form an array of tuples, then sort by element value. We then traverse the sorted tuple array, identify the range of each subarray, sort the elements within each subarray by their original indices, and fill them back into the corresponding positions to obtain the final result.\n\nThe time complexity is $O(n \\times \\log n)$ and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2949, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2950, "explanations": { "1": "First, we use a hash table or array $mp$ to record the number corresponding to each letter.\n\nThen, we enumerate the starting position $i$ of the substring, and then enumerate the ending position $j$ of the substring, calculate the numerical sum $s$ of the substring $s[i..j]$. If $s$ can be divided by $j-i+1$, then a divisible substring is found, and the answer is increased by one.\n\nAfter the enumeration is over, return the answer.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(C)$. Where $n$ is the length of the string $word$, and $C$ is the size of the character set, in this question $C=26$.", "2": "Similar to Solution 1, we first use a hash table or array $mp$ to record the number corresponding to each letter.\n\nIf the sum of the numbers in an integer subarray can be divided by its length, then the average value of this subarray must be an integer. And because the number of each element in the subarray is in the range of $[1, 9]$, the average value of the subarray can only be one of $1, 2, \\cdots, 9$.\n\nWe can enumerate the average value $i$ of the subarray. If the sum of the elements in a subarray can be divided by $i$, suppose the subarray is $a_1, a_2, \\cdots, a_k$, then $a_1 + a_2 + \\cdots + a_k = i \\times k$, that is, $(a_1 - i) + (a_2 - i) + \\cdots + (a_k - i) = 0$. If we regard $a_k - i$ as a new element $b_k$, then the original subarray becomes $b_1, b_2, \\cdots, b_k$, where $b_1 + b_2 + \\cdots + b_k = 0$. We only need to find out how many subarrays in the new array have an element sum of $0$, which can be implemented with \"hash table\" combined with \"prefix sum\".\n\nThe time complexity is $O(10 \\times n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $word$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(C)" }, { "problem_id": 2951, "explanations": { "1": "We directly traverse the index $i \\in [1, n-2]$. For each index $i$, if $mountain[i-1] < mountain[i]$ and $mountain[i + 1] < mountain[i]$, then $mountain[i]$ is a peak, and we add index $i$ to the answer array.\n\nAfter the traversal ends, we return the answer array.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. Ignoring the space consumption of the answer array, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2952, "explanations": { "1": "Suppose the current amount we need to construct is $s$, and we have already constructed all amounts in $[0,...,s-1]$. If there is a new coin $x$, we add it to the array, which can construct all amounts in $[x, s+x-1]$.\n\nNext, we discuss in two cases:\n\n- If $x \\le s$, then we can merge the two intervals above to get all amounts in $[0, s+x-1]$.\n- If $x \\gt s$, then we need to add a coin with a face value of $s$, so that we can construct all amounts in $[0, 2s-1]$. Then we consider the size relationship between $x$ and $s$ and continue to analyze.\n\nTherefore, we sort the array $coins$ in ascending order, and then traverse the coins in the array from small to large. For each coin $x$, we discuss in the above two cases until $s > target$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 2953, "explanations": { "1": "According to condition 2 in the problem description, we can find that in a complete string, the difference between two adjacent characters does not exceed 2. Therefore, we traverse the string $word$, and we can use two pointers to split $word$ into several substrings. The number of character types in these substrings does not exceed 26, and the difference between adjacent characters does not exceed 2. Next, we only need to count the number of substrings in each substring where each character appears $k$ times.\n\nWe define a function $f(s)$, which is used to count the number of substrings in the string $s$ where each character appears $k$ times. Since the number of character types in $s$ does not exceed 26, we can enumerate each character type $i$, where $1 \\le i \\le 26$, then the length of the substring with character type $i$ is $l = i \\times k$.\n\nWe can use an array or hash table $cnt$ to maintain the number of times each character appears in a sliding window of length $l$, and use another hash table $freq$ to maintain the number of times each frequency appears. If $freq[k] = i$, that is, there are $i$ characters that appear $k$ times, then we have found a substring that meets the conditions. We can use two pointers to maintain this sliding window. Each time we move the right pointer, we increase the number of times the character pointed to by the right pointer appears and update the $freq$ array; each time we move the left pointer, we decrease the number of times the character pointed to by the left pointer appears and update the $freq$ array. After each pointer movement, we judge whether $freq[k]$ is equal to $i$. If it is equal, it means that we have found a substring that meets the conditions.\n\nThe time complexity is $O(n \\times |\\Sigma|)$, and the space complexity is $O(|\\Sigma|)$, where $n$ is the length of the string $word$; and $\\Sigma$ is the size of the character set. In this problem, the character set is lowercase English letters, so $|\\Sigma| = 26$." }, "is_english": true, "time_complexity": "O(n \\times |\\Sigma|)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 2954, "explanations": { "1": "According to the problem description, the children who have a cold have divided the children who have not yet caught a cold into several continuous segments. We can use an array $nums$ to record the number of children who are not cold in each segment, and there are a total of $s = \\sum_{i=0}^{k} nums[k]$ children who are not cold. We can find that the number of cold sequences is the number of permutations of $s$ different elements, that is, $s!$.\n\nAssuming that there is only one transmission scheme for each segment of children who are not cold, there are $\\frac{s!}{\\prod_{i=0}^{k} nums[k]!}$ cold sequences in total.\n\nNext, we consider the transmission scheme of each segment of children who are not cold. Suppose there are $x$ children in a segment who are not cold, then they have $2^{x-1}$ transmission schemes, because each time you can choose one end from the left and right ends of a segment to transmit, that is: two choices, there are a total of $x-1$ transmissions. However, if it is the first segment or the last segment, there is only one choice.\n\nIn summary, the total number of cold sequences is:\n\n$$\n\\frac{s!}{\\prod_{i=0}^{k} nums[k]!} \\prod_{i=1}^{k-1} 2^{nums[i]-1}\n$$\n\nFinally, we need to consider that the answer may be very large and need to be modulo $10^9 + 7$. Therefore, we need to preprocess the factorial and multiplicative inverse.\n\nThe time complexity is $O(m)$, where $m$ is the length of the array $sick$. Ignoring the space consumption of the preprocessing array, the space complexity is $O(m)$." }, "is_english": true, "time_complexity": "O(m)", "space_complexity": "O(m)" }, { "problem_id": 2955, "explanations": { "1": "We can preprocess the prefix sum for each letter and record it in the array $cnt$, where $cnt[i][j]$ represents the number of times the $i$-th letter appears in the first $j$ characters. In this way, for each interval $[l, r]$, we can enumerate each letter $c$ in the interval, quickly calculate the number of times $c$ appears in the interval $x$ using the prefix sum array. We can arbitrarily choose two of them to form a tail-equal substring, the number of substrings is $C_x^2=\\frac{x(x-1)}{2}$, plus the situation where each letter in the interval can form a tail-equal substring alone, there are $r - l + 1$ letters in total. Therefore, for each query $[l, r]$, the number of tail-equal substrings that meet the conditions is $r - l + 1 + \\sum_{c \\in \\Sigma} \\frac{x_c(x_c-1)}{2}$, where $x_c$ represents the number of times the letter $c$ appears in the interval $[l, r]$.\n\nThe time complexity is $O((n + m) \\times |\\Sigma|)$, and the space complexity is $O(n \\times |\\Sigma|)$. Here, $n$ and $m$ are the lengths of the string $s$ and the number of queries, respectively, and $\\Sigma$ represents the set of letters appearing in the string $s$, in this problem $|\\Sigma|=26$." }, "is_english": true, "time_complexity": "O((n + m) \\times |\\Sigma|)", "space_complexity": "O(n \\times |\\Sigma|)" }, { "problem_id": 2956, "explanations": { "1": "We can use two hash tables or arrays $s1$ and $s2$ to record the elements that appear in the two arrays respectively.\n\nNext, we create an array $ans$ of length $2$, where $ans[0]$ represents the number of elements in $nums1$ that appear in $s2$, and $ans[1]$ represents the number of elements in $nums2$ that appear in $s1$.\n\nThen, we traverse each element $x$ in the array $nums1$. If $x$ has appeared in $s2$, we increment $ans[0]$. After that, we traverse each element $x$ in the array $nums2$. If $x$ has appeared in $s1$, we increment $ans[1]$.\n\nFinally, we return the array $ans$.\n\nThe time complexity is $O(n + m)$, and the space complexity is $O(n + m)$. Here, $n$ and $m$ are the lengths of the arrays $nums1$ and $nums2$ respectively." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(n + m)" }, { "problem_id": 2957, "explanations": { "1": "We start traversing the string `word` from index $1$. If `word[i]` and `word[i - 1]` are approximately equal, we greedily replace `word[i]` with a character that is not equal to both `word[i - 1]` and `word[i + 1]` (we can choose not to perform the replacement operation, just record the number of operations). Then, we skip `word[i + 1]` and continue to traverse the string `word`.\n\nFinally, we return the recorded number of operations.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string `word`. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2958, "explanations": { "1": "We can use two pointers $j$ and $i$ to represent the left and right endpoints of the subarray, initially both pointers point to the first element of the array.\n\nNext, we iterate over each element $x$ in the array $nums$. For each element $x$, we increment the occurrence count of $x$, then check if the current subarray meets the requirements. If the current subarray does not meet the requirements, we move the pointer $j$ one step to the right, and decrement the occurrence count of $nums[j]$, until the current subarray meets the requirements. Then we update the answer $ans = \\max(ans, i - j + 1)$. Continue the iteration until $i$ reaches the end of the array.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2959, "explanations": { "1": "We notice that $n \\leq 10$, so we might as well consider using the method of binary enumeration to enumerate all subsets of departments.\n\nFor each subset of departments, we can use the Floyd algorithm to calculate the shortest distance between the remaining departments, and then judge whether it meets the requirements of the problem. Specifically, we first enumerate the middle point $k$, then enumerate the starting point $i$ and the ending point $j$. If $g[i][k] + g[k][j] < g[i][j]$, then we update $g[i][j]$ with the shorter distance $g[i][k] + g[k][j]$.\n\nThe time complexity is $O(2^n \\times (n^3 + m))$, and the space complexity is $O(n^2)$. Here, $n$ and $m$ are the number of departments and the number of roads, respectively." }, "is_english": true, "time_complexity": "O(2^n \\times (n^3 + m))", "space_complexity": "O(n^2)" }, { "problem_id": 2960, "explanations": { "1": "Assume that the current number of devices we have tested is $ans$. When testing a new device $i$, its remaining battery is $\\max(0, batteryPercentages[i] - ans)$. If the remaining battery is greater than $0$, it means this device can be tested, and we need to increase $ans$ by $1$.\n\nFinally, return $ans$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2961, "explanations": { "1": "We can directly simulate according to the problem description. For the power operation modulo, we can use the fast power method to speed up the calculation.\n\nThe time complexity is $O(n \\times \\log M)$, where $n$ is the length of the array $variables$; and $M$ is the maximum value in $b_i$ and $c_i$, in this problem $M \\le 10^3$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(1)" }, { "problem_id": 2962, "explanations": { "1": "Let's denote the maximum value in the array as $mx$.\n\nWe use two pointers $i$ and $j$ to maintain a sliding window, such that in the subarray between $[i, j)$, there are $k$ elements equal to $mx$. If we fix the left endpoint $i$, then all right endpoints greater than or equal to $j-1$ meet the condition, totaling $n - (j - 1)$.\n\nTherefore, we enumerate the left endpoint $i$, use the pointer $j$ to maintain the right endpoint, use a variable $cnt$ to record the number of elements equal to $mx$ in the current window. When $cnt$ is greater than or equal to $k$, we have found a subarray that meets the condition, and we increase the answer by $n - (j - 1)$. Then we update $cnt$ and continue to enumerate the next left endpoint.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2963, "explanations": { "1": "According to the problem description, we know that the same number must be in the same subarray. Therefore, we use a hash table $last$ to record the index of the last occurrence of each number.\n\nNext, we use an index $j$ to mark the index of the last element that has appeared among the elements, and use a variable $k$ to record the number of subarrays that can currently be divided.\n\nThen, we traverse the array $nums$ from left to right. For the current number $nums[i]$ we are traversing, we get its last occurrence index and update $j = \\max(j, last[nums[i]])$. If $i = j$, it means that the current position can be the end of a subarray, and we increase $k$ by $1$. Continue to traverse until the entire array is traversed.\n\nFinally, we consider the number of division schemes for $k$ subarrays. The number of subarrays is $k$, and there are $k-1$ positions that can be divided (concatenated), so the number of schemes is $2^{k-1}$. Since the answer may be very large, we need to take the modulo of $10^9 + 7$. Here we can use fast power to speed up the calculation.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2964, "explanations": { "1": "We can use a hash table $cnt$ to record the occurrence times of $nums[i] \\bmod d$, then enumerate $j$ and $k$, calculate the value of $nums[i] \\bmod d$ that makes the equation $(nums[i] + nums[j] + nums[k]) \\bmod d = 0$ hold, which is $(d - (nums[j] + nums[k]) \\bmod d) \\bmod d$, and accumulate its occurrence times to the answer. Then we increase the occurrence times of $nums[j] \\bmod d$ by one. Continue to enumerate $j$ and $k$ until $j$ reaches the end of the array.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 2965, "explanations": { "1": "We create an array $cnt$ of length $n^2 + 1$ to count the frequency of each number in the matrix.\n\nNext, we traverse $i \\in [1, n^2]$. If $cnt[i] = 2$, then $i$ is the duplicated number, and we set the first element of the answer to $i$. If $cnt[i] = 0$, then $i$ is the missing number, and we set the second element of the answer to $i$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ is the side length of the matrix." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 2966, "explanations": { "1": "First, we sort the array. Then, we take out three elements each time. If the difference between the maximum and minimum values of these three elements is greater than $k$, then the condition cannot be satisfied, and we return an empty array. Otherwise, we add the array composed of these three elements to the answer array.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2967, "explanations": { "1": "The range of palindrome numbers in the problem is $[1, 10^9]$. Due to the symmetry of palindrome numbers, we can enumerate in the range of $[1, 10^5]$, then reverse and concatenate them to get all palindrome numbers. Note that if it is an odd-length palindrome number, we need to remove the last digit before reversing. The array of palindrome numbers obtained by preprocessing is denoted as $ps$. We sort the array $ps$.\n\nNext, we sort the array $nums$ and take the median $x$ of $nums$. We only need to find a number in the palindrome array $ps$ that is closest to $x$ through binary search, and then calculate the cost of $nums$ becoming this number to get the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(M)$. Here, $n$ is the length of the array $nums$, and $M$ is the length of the palindrome array $ps$.\n\nSimilar problems:\n\n- [906. Super Palindromes](https://github.com/doocs/leetcode/blob/main/solution/0900-0999/0906.Super%20Palindromes/README_EN.md)" }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(M)" }, { "problem_id": 2968, "explanations": { "1": "The problem asks for the maximum frequency of the mode we can get after performing at most $k$ operations. If we sort the array $nums$ in ascending order, it would be best to turn a continuous segment of numbers into the same number, which can reduce the number of operations and increase the frequency of the mode.\n\nTherefore, we might as well sort the array $nums$ first.\n\nNext, we analyze that if a frequency $x$ is feasible, then for any $y \\le x$, the frequency $y$ is also feasible, which shows monotonicity. Therefore, we can use binary search to find the maximum feasible frequency.\n\nWe binary search the frequency, define the left boundary of the binary search as $l = 0$, and the right boundary as $r = n$, where $n$ is the length of the array. In each binary search process, we take the middle value $mid = \\lfloor \\frac{l + r + 1}{2} \\rfloor$, and then determine whether there exists a continuous subarray of length $mid$ in $nums$, such that all elements in this subarray become the median of this subarray, and the number of operations does not exceed $k$. If it exists, then we update the left boundary $l$ to $mid$, otherwise we update the right boundary $r$ to $mid - 1$.\n\nTo determine whether such a subarray exists, we can use prefix sum. We first define two pointers $i$ and $j$, initially $i = 0$, $j = i + mid$. Then all elements from $nums[i]$ to $nums[j - 1]$ are changed to $nums[(i + j) / 2]$, and the number of operations required is $left + right$, where:\n\n$$\n\\begin{aligned}\n\\textit{left} &= \\sum_{k = i}^{(i + j) / 2 - 1} (nums[(i + j) / 2] - nums[k]) \\\\\n&= ((i + j) / 2 - i) \\times nums[(i + j) / 2] - \\sum_{k = i}^{(i + j) / 2 - 1} nums[k]\n\\end{aligned}\n$$\n\n$$\n\\begin{aligned}\n\\textit{right} &= \\sum_{k = (i + j) / 2 + 1}^{j} (nums[k] - nums[(i + j) / 2]) \\\\\n&= \\sum_{k = (i + j) / 2 + 1}^{j} nums[k] - (j - (i + j) / 2) \\times nums[(i + j) / 2]\n\\end{aligned}\n$$\n\nWe can use the prefix sum array $s$ to calculate $\\sum_{k = i}^{j} nums[k]$, so as to calculate $left$ and $right$ in $O(1)$ time.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2969, "explanations": { "1": "We define $f[i]$ as the minimum number of coins needed to buy all fruits starting from the $i$th fruit. So the answer is $f[1]$.\n\nThe state transition equation is $f[i] = \\min_{i + 1 \\le j \\le 2i + 1} f[j] + prices[i - 1]$.\n\nIn implementation, we calculate from back to front, and we can directly perform state transition on the array $prices$, which can save space.\n\nThe time complexity of the above method is $O(n^2)$. Since the scale of $n$ in this problem reaches $10^5$, it will time out.\n\nWe observe the state transition equation and find that for each $i$, we need to find the minimum value of $f[i + 1], f[i + 2], \\cdots, f[2i + 1]$, and as $i$ decreases, the range of these values is also decreasing. This is actually finding the minimum value of a monotonically narrowing sliding window, and we can use a monotonic queue to optimize.\n\nWe calculate from back to front, maintain a monotonically increasing queue $q$, and the queue stores the index. If the head element of $q$ is greater than $i \\times 2 + 1$, it means that the elements after $i$ will not be used, so we dequeue the head element. If $i$ is not greater than $(n - 1) / 2$, then we can add $prices[q[0] - 1]$ to $prices[i - 1]$, and then add $i$ to the tail of the queue. If the price of the fruit corresponding to the tail element of $q$ is greater than or equal to $prices[i - 1]$, then we dequeue the tail element until the price of the fruit corresponding to the tail element is less than $prices[i - 1]$ or the queue is empty, and then add $i$ to the tail of the queue.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $prices$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 2970, "explanations": { "1": "According to the problem description, after removing a subarray, the remaining elements are strictly increasing. Therefore, there are several situations:\n\n1. The remaining elements only include the prefix of the array $nums$ (which can be empty);\n2. The remaining elements only include the suffix of the array $nums$;\n3. The remaining elements include both the prefix and the suffix of the array $nums$.\n\nThe second and third situations can be combined into one, that is, the remaining elements include the suffix of the array $nums$. So there are two situations in total:\n\n1. The remaining elements only include the prefix of the array $nums$ (which can be empty);\n2. The remaining elements include the suffix of the array $nums$.\n\nFirst, consider the first situation, that is, the remaining elements only include the prefix of the array $nums$. We can use a pointer $i$ to point to the last element of the longest increasing prefix of the array $nums$, that is, $nums[0] \\lt nums[1] \\lt \\cdots \\lt nums[i]$, then the number of remaining elements is $n - i - 1$, where $n$ is the length of the array $nums$. Therefore, for this situation, to make the remaining elements strictly increasing, we can choose to remove the following subarrays:\n\n1. $nums[i+1,...,n-1]$;\n2. $nums[i,...,n-1]$;\n3. $nums[i-1,...,n-1]$;\n4. $nums[i-2,...,n-1]$;\n5. $\\cdots$;\n6. $nums[0,...,n-1]$.\n\nThere are $i + 2$ situations in total, so for this situation, the number of removed increasing subarrays is $i + 2$.\n\nNext, consider the second situation, that is, the remaining elements include the suffix of the array $nums$. We can use a pointer $j$ to point to the first element of the increasing suffix of the array $nums$. We enumerate $j$ as the first element of the increasing suffix in the range $[n - 1,...,1]$. Each time, we need to move the pointer $i$ to make $nums[i] \\lt nums[j]$, then the number of removed increasing subarrays increases by $i + 2$. When $nums[j - 1] \\ge nums[j]$, we stop enumerating because the suffix is not strictly increasing at this time.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2971, "explanations": { "1": "我们可以将数组 $nums$ 排序,然后定义一个答案变量 $ans$,初始值为 $-1$。\n\n接下来,我们在 $[3, n]$ 的范围内枚举最长边 $a_k$,如果 $a_1 + a_2 + \\cdots + a_{k-1} > a_k$,那么就可以构成一个周长为 $a_1 + a_2 + \\cdots + a_k$ 的多边形。这里,我们可以使用前缀和数组 $s$,其中 $s_i = a_1 + a_2 + \\cdots + a_i$,那么 $a_1 + a_2 + \\cdots + a_{k-1} = s_{k-1}$,判断是否 $s_{k-1} > a_k$,如果是,那么更新答案 $ans = \\max(ans, s_k)$。\n\n时间复杂度 $O(n \\times \\log n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 $nums$ 的长度。" }, "is_english": false, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2972, "explanations": { "1": "According to the problem description, after removing a subarray, the remaining elements are strictly increasing. Therefore, there are several situations:\n\n1. The remaining elements only include the prefix of the array $nums$ (which can be empty);\n2. The remaining elements only include the suffix of the array $nums$;\n3. The remaining elements include both the prefix and the suffix of the array $nums$.\n\nThe second and third situations can be combined into one, that is, the remaining elements include the suffix of the array $nums$. So there are two situations in total:\n\n1. The remaining elements only include the prefix of the array $nums$ (which can be empty);\n2. The remaining elements include the suffix of the array $nums$.\n\nFirst, consider the first situation, that is, the remaining elements only include the prefix of the array $nums$. We can use a pointer $i$ to point to the last element of the longest increasing prefix of the array $nums$, that is, $nums[0] \\lt nums[1] \\lt \\cdots \\lt nums[i]$, then the number of remaining elements is $n - i - 1$, where $n$ is the length of the array $nums$. Therefore, for this situation, to make the remaining elements strictly increasing, we can choose to remove the following subarrays:\n\n1. $nums[i+1,...,n-1]$;\n2. $nums[i,...,n-1]$;\n3. $nums[i-1,...,n-1]$;\n4. $nums[i-2,...,n-1]$;\n5. $\\cdots$;\n6. $nums[0,...,n-1]$.\n\nThere are $i + 2$ situations in total, so for this situation, the number of removed increasing subarrays is $i + 2$.\n\nNext, consider the second situation, that is, the remaining elements include the suffix of the array $nums$. We can use a pointer $j$ to point to the first element of the increasing suffix of the array $nums$. We enumerate $j$ as the first element of the increasing suffix in the range $[n - 1,...,1]$. Each time, we need to move the pointer $i$ to make $nums[i] \\lt nums[j]$, then the number of removed increasing subarrays increases by $i + 2$. When $nums[j - 1] \\ge nums[j]$, we stop enumerating because the suffix is not strictly increasing at this time.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2973, "explanations": { "1": "According to the problem description, there are two situations for the number of coins placed at each node $a$:\n\n- If the number of nodes in the subtree corresponding to node $a$ is less than $3$, then place $1$ coin;\n- If the number of nodes in the subtree corresponding to node $a$ is greater than or equal to $3$, then we need to take out $3$ different nodes from the subtree, calculate the maximum value of their cost product, and then place the corresponding number of coins at node $a$. If the maximum product is negative, place $0$ coins.\n\nThe first situation is relatively simple, we just need to count the number of nodes in the subtree of each node during the traversal.\n\nFor the second situation, if all costs are positive, we should take the $3$ nodes with the largest costs; if there are negative costs, we should take the $2$ nodes with the smallest costs and the $1$ node with the largest cost. Therefore, we need to maintain the smallest $2$ costs and the largest $3$ costs in each subtree.\n\nWe first construct the adjacency list $g$ based on the given two-dimensional array $edges$, where $g[a]$ represents all neighbor nodes of node $a$.\n\nNext, we design a function $dfs(a, fa)$, which returns an array $res$, which stores the smallest $2$ costs and the largest $3$ costs in the subtree of node $a$ (may not be $5$).\n\nIn the function $dfs(a, fa)$, we add the cost $cost[a]$ of node $a$ to the array $res$, and then traverse all neighbor nodes $b$ of node $a$. If $b$ is not the parent node $fa$ of node $a$, then we add the result of $dfs(b, a)$ to the array $res$.\n\nThen, we sort the array $res$, and then calculate the number of coins placed at node $a$ based on the length $m$ of the array $res$, and update $ans[a]$:\n\n- If $m \\ge 3$, then the number of coins placed at node $a$ is $\\max(0, res[m - 1] \\times res[m - 2] \\times res[m - 3], res[0] \\times res[1] \\times res[m - 1])$, otherwise the number of coins placed at node $a$ is $1$;\n- If $m > 5$, then we only need to keep the first $2$ elements and the last $3$ elements of the array $res$.\n\nFinally, we call the function $dfs(0, -1)$, and return the answer array $ans$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2974, "explanations": { "1": "We can put the elements of the array $\\textit{nums}$ into a min heap one by one. Each time, we take out two elements $a$ and $b$ from the min heap, and then sequentially put $b$ and $a$ into the answer array until the min heap is empty.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$.", "2": "We can sort the array $\\textit{nums}$, and then iterate through the array, swapping adjacent elements each time until the iteration is complete, and return the swapped array.\n\nThe time complexity is $O(n \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 2975, "explanations": { "1": "We can enumerate any two horizontal fences $a$ and $b$ in $\\textit{hFences}$, calculate the distance $d$ between $a$ and $b$, and record it in the hash table $hs$. Then, we enumerate any two vertical fences $c$ and $d$ in $\\textit{vFences}$, calculate the distance $d$ between $c$ and $d$, and record it in the hash table $vs$. Finally, we traverse the hash table $hs$. If a certain distance $d$ in $hs$ also exists in the hash table $vs$, it indicates that there exists a square field with a side length of $d$, and the area is $d^2$. We just need to take the largest $d$ and calculate $d^2 \\bmod 10^9 + 7$.\n\nThe time complexity is $O(h^2 + v^2)$, and the space complexity is $O(h^2 + v^2)$. Here, $h$ and $v$ are the lengths of $\\textit{hFences}$ and $\\textit{vFences}$, respectively." }, "is_english": true, "time_complexity": "O(h^2 + v^2)", "space_complexity": "O(h^2 + v^2)" }, { "problem_id": 2976, "explanations": { "1": "According to the problem description, we can consider each letter as a node, and the conversion cost between each pair of letters as a directed edge. We first initialize a $26 \\times 26$ two-dimensional array $g$, where $g[i][j]$ represents the minimum cost of converting letter $i$ to letter $j$. Initially, $g[i][j] = \\infty$, and if $i = j$, then $g[i][j] = 0$.\n\nNext, we traverse the arrays $original$, $changed$, and $cost$. For each index $i$, we update the cost $cost[i]$ of converting $original[i]$ to $changed[i]$ to $g[original[i]][changed[i]]$, taking the minimum value.\n\nThen, we use the Floyd algorithm to calculate the minimum cost between any two nodes in $g$. Finally, we traverse the strings $source$ and $target$. If $source[i] \\neq target[i]$ and $g[source[i]][target[i]] \\geq \\infty$, it means that the conversion cannot be completed, so we return $-1$. Otherwise, we add $g[source[i]][target[i]]$ to the answer.\n\nAfter the traversal ends, we return the answer.\n\nThe time complexity is $O(m + n + |\\Sigma|^3)$, and the space complexity is $O(|\\Sigma|^2)$. Where $m$ and $n$ are the lengths of the arrays $original$ and $source$ respectively; and $|\\Sigma|$ is the size of the alphabet, that is, $|\\Sigma| = 26$." }, "is_english": true, "time_complexity": "O(m + n + |\\Sigma|^3)", "space_complexity": "O(|\\Sigma|^2)" }, { "problem_id": 2977, "explanations": { "1": "According to the problem description, we can consider each string as a node, and the conversion cost between each pair of strings as a directed edge. We first initialize a $26 \\times 26$ two-dimensional array $g$, where $g[i][j]$ represents the minimum cost of converting string $i$ to string $j$. Initially, $g[i][j] = \\infty$, and if $i = j$, then $g[i][j] = 0$. Here, we can use a trie to store the strings in `original` and `changed` along with their corresponding integer identifiers.\n\nNext, we use the Floyd algorithm to calculate the minimum cost between any two strings.\n\nThen, we define a function $dfs(i)$ to represent the minimum cost of converting the string $source[i..]$ to the string $target[i..]$. The answer is $dfs(0)$.\n\nThe calculation process of the function $dfs(i)$ is as follows:\n\n- If $i \\geq |source|$, no conversion is needed, return $0$.\n- Otherwise, if $source[i] = target[i]$, we can skip directly and recursively calculate $dfs(i + 1)$. We can also enumerate the index $j$ in the range $[i, |source|)$, if $source[i..j]$ and $target[i..j]$ are both in the trie, and their corresponding integer identifiers $x$ and $y$ are both greater than or equal to $0$, then we can add $dfs(j + 1)$ and $g[x][y]$ to get the cost of one conversion scheme, and we take the minimum value among all schemes.\n\nIn summary, we can get:\n\n$$\ndfs(i) = \\begin{cases}\n0, & i \\geq |source| \\\\\ndfs(i + 1), & source[i] = target[i] \\\\\n\\min_{i \\leq j < |source|} \\{ dfs(j + 1) + g[x][y] \\}, & \\textit{otherwise}\n\\end{cases}\n$$\n\nWhere $x$ and $y$ are the integer identifiers of $source[i..j]$ and $target[i..j]$ in the trie, respectively.\n\nTo avoid repeated calculations, we can use memoization search.\n\nThe time complexity is $O(m^3 + n^2 + m \\times n)$, and the space complexity is $O(m^2 + m \\times n + n)$. Where $m$ and $n$ are the lengths of the arrays `original` and `source`, respectively." }, "is_english": true, "time_complexity": "O(m^3 + n^2 + m \\times n)", "space_complexity": "O(m^2 + m \\times n + n)" }, { "problem_id": 2978, "explanations": { "1": "We can use the window function `ROW_NUMBER()` to add an auto-incrementing sequence number to each row. Then, we perform a self join on the two tables, with the join conditions being `p1.x = p2.y AND p1.y = p2.x AND p1.x <= p1.y AND p1.id != p2.id`. Finally, we sort and remove duplicates." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 2979, "explanations": { "1": "According to the Chicken McNugget Theorem, for two coprime positive integers $a$ and $b$, the largest number that cannot be expressed as a combination of $a$ and $b$ is $ab - a - b$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 2980, "explanations": { "1": "According to the problem statement, if there are two or more elements in the array whose bitwise OR operation results in trailing zeros, then there must be at least two even numbers in the array. Therefore, we can count the number of even numbers in the array. If the count of even numbers is greater than or equal to $2$, then return `true`, otherwise return `false`.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2981, "explanations": { "1": "We notice that if there exists a special substring of length $x$ that appears at least three times, then a special substring of length $x-1$ must also exist. This exhibits a monotonicity, so we can use binary search to find the longest special substring.\n\nWe define the left boundary of the binary search as $l = 0$ and the right boundary as $r = n$, where $n$ is the length of the string. In each binary search, we take $mid = \\lfloor \\frac{l + r + 1}{2} \\rfloor$. If a special substring of length $mid$ exists, we update the left boundary to $mid$. Otherwise, we update the right boundary to $mid - 1$. During the binary search, we use a sliding window to count the number of special substrings.\n\nSpecifically, we design a function $check(x)$ to indicate whether a special substring of length $x$ that appears at least three times exists.\n\nIn the function $check(x)$, we define a hash table or an array of length $26$ named $cnt$, where $cnt[i]$ represents the count of special substrings of length $x$ composed of the $i$-th lowercase letter. We traverse the string $s$. If the current character is $s[i]$, we move the pointer $j$ to the right until $s[j] \\neq s[i]$. At this point, $s[i \\cdots j-1]$ is a special substring of length $x$. We increase $cnt[s[i]]$ by $\\max(0, j - i - x + 1)$, and then update the pointer $i$ to $j$.\n\nAfter the traversal, we go through the array $cnt$. If there exists $cnt[i] \\geq 3$, it means a special substring of length $x$ that appears at least three times exists, so we return $true$. Otherwise, we return $false$.\n\nThe time complexity is $O((n + |\\Sigma|) \\times \\log n)$, and the space complexity is $O(|\\Sigma|)$, where $n$ is the length of the string $s$, and $|\\Sigma|$ represents the size of the character set. In this problem, the character set is lowercase English letters, so $|\\Sigma| = 26$.", "2": "The time complexity is $O(n)$" }, "is_english": true, "time_complexity": "O((n + |\\Sigma|) \\times \\log n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 2982, "explanations": { "1": "We notice that if there exists a special substring of length $x$ that appears at least three times, then a special substring of length $x-1$ must also exist. This exhibits a monotonicity, so we can use binary search to find the longest special substring.\n\nWe define the left boundary of the binary search as $l = 0$ and the right boundary as $r = n$, where $n$ is the length of the string. In each binary search, we take $mid = \\lfloor \\frac{l + r + 1}{2} \\rfloor$. If a special substring of length $mid$ exists, we update the left boundary to $mid$. Otherwise, we update the right boundary to $mid - 1$. During the binary search, we use a sliding window to count the number of special substrings.\n\nSpecifically, we design a function $check(x)$ to indicate whether a special substring of length $x$ that appears at least three times exists.\n\nIn the function $check(x)$, we define a hash table or an array of length $26$ named $cnt$, where $cnt[i]$ represents the count of special substrings of length $x$ composed of the $i$-th lowercase letter. We traverse the string $s$. If the current character is $s[i]$, we move the pointer $j$ to the right until $s[j] \\neq s[i]$. At this point, $s[i \\cdots j-1]$ is a special substring of length $x$. We increase $cnt[s[i]]$ by $\\max(0, j - i - x + 1)$, and then update the pointer $i$ to $j$.\n\nAfter the traversal, we go through the array $cnt$. If there exists $cnt[i] \\geq 3$, it means a special substring of length $x$ that appears at least three times exists, so we return $true$. Otherwise, we return $false$.\n\nThe time complexity is $O((n + |\\Sigma|) \\times \\log n)$, and the space complexity is $O(|\\Sigma|)$, where $n$ is the length of the string $s$, and $|\\Sigma|$ represents the size of the character set. In this problem, the character set is lowercase English letters, so $|\\Sigma| = 26$." }, "is_english": true, "time_complexity": "O((n + |\\Sigma|) \\times \\log n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 2983, "explanations": { "1": "Let's denote the length of string $s$ as $n$, then half of the length is $m = \\frac{n}{2}$. Next, we divide string $s$ into two equal-length segments, where the second segment is reversed to get string $t$, and the first segment remains as $s$. For each query $[a_i, b_i, c_i, d_i]$, where $c_i$ and $d_i$ need to be transformed to $n - 1 - d_i$ and $n - 1 - c_i$. The problem is transformed into: for each query $[a_i, b_i, c_i, d_i]$, determine whether $s[a_i, b_i]$ and $t[c_i, d_i]$ can be rearranged to make strings $s$ and $t$ equal.\n\nWe preprocess the following information:\n\n1. The prefix sum array $pre_1$ of string $s$, where $pre_1[i][j]$ represents the quantity of character $j$ in the first $i$ characters of string $s$;\n2. The prefix sum array $pre_2$ of string $t$, where $pre_2[i][j]$ represents the quantity of character $j$ in the first $i$ characters of string $t$;\n3. The difference array $diff$ of strings $s$ and $t$, where $diff[i]$ represents the quantity of different characters in the first $i$ characters of strings $s$ and $t$.\n\nFor each query $[a_i, b_i, c_i, d_i]$, let's assume $a_i \\le c_i$, then we need to discuss the following cases:\n\n1. The prefix substrings $s[..a_i-1]$ and $t[..a_i-1]$ of strings $s$ and $t$ must be equal, and the suffix substrings $s[\\max(b_i, d_i)+1..]$ and $t[\\max(b_i, d_i)..]$ must also be equal, otherwise, it is impossible to rearrange to make strings $s$ and $t$ equal;\n2. If $d_i \\le b_i$, it means the interval $[a_i, b_i]$ contains the interval $[c_i, d_i]$. If the substrings $s[a_i, b_i]$ and $t[a_i, b_i]$ contain the same quantity of characters, then it is possible to rearrange to make strings $s$ and $t$ equal, otherwise, it is impossible;\n3. If $b_i < c_i$, it means the intervals $[a_i, b_i]$ and $[c_i, d_i]$ do not intersect. Then the substrings $s[b_i+1, c_i-1]$ and $t[b_i+1, c_i-1]$ must be equal, and the substrings $s[a_i, b_i]$ and $t[a_i, b_i]$ must be equal, and the substrings $s[c_i, d_i]$ and $t[c_i, d_i]$ must be equal, otherwise, it is impossible to rearrange to make strings $s$ and $t$ equal.\n4. If $c_i \\le b_i < d_i$, it means the intervals $[a_i, b_i]$ and $[c_i, d_i]$ intersect. Then the characters contained in $s[a_i, b_i]$, minus the characters contained in $t[a_i, c_i-1]$, must be equal to the characters contained in $t[c_i, d_i]$, minus the characters contained in $s[b_i+1, d_i]$, otherwise, it is impossible to rearrange to make strings $s$ and $t$ equal.\n\nBased on the above analysis, we iterate through each query $[a_i, b_i, c_i, d_i]$, and determine whether it satisfies the above conditions.\n\nThe time complexity is $O((n + q) \\times |\\Sigma|)$, and the space complexity is $O(n \\times |\\Sigma|)$. Where $n$ and $q$ are the lengths of string $s$ and the query array $queries$ respectively; and $|\\Sigma|$ is the size of the character set. In this problem, the character set is lowercase English letters, so $|\\Sigma| = 26$." }, "is_english": true, "time_complexity": "O((n + q) \\times |\\Sigma|)", "space_complexity": "O(n \\times |\\Sigma|)" }, { "problem_id": 2984, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2985, "explanations": { "1": "We use the `SUM` function to calculate the total quantity of products and the total number of orders, then divide the total quantity by the total number of orders to get the average. Finally, we use the `ROUND` function to round the result to two decimal places." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 2986, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2987, "explanations": { "1": "We group the `Listings` table by `city`, then calculate the average house price for each city, and finally filter out the cities where the average house price is greater than the national average house price." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 2988, "explanations": { "1": "We can first count the number of employees in each department, denoted as table `T`. Then we join `T` with the `Employees` table, with the join condition being `T.dep_id = Employees.dep_id` and `Employees.position = 'Manager'`. This way, we can get the manager of each department. Finally, we filter out the department with the most employees." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 2989, "explanations": { "1": "We can use the `MAX` and `MIN` functions to get the maximum and minimum sums of `assignment1`, `assignment2`, and `assignment3`, respectively. Then, subtract the minimum from the maximum." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 2990, "explanations": { "1": "We can group the `Loans` table by `user_id` to find users who have both `Refinance` and `Mortgage`. Then, sort the results by `user_id`." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 2991, "explanations": { "1": "We can first group the `Wineries` table by `country` and `winery`, calculate the total score `points` for each group, then use the window function `RANK()` to group the data by `country` again, sort by `points` in descending order and `winery` in ascending order, and use the `CONCAT()` function to concatenate `winery` and `points`, resulting in the following data, denoted as table `T`:\n\n| country | winery | rk |\n| --------- | -------------------- | --- |\n| Australia | HarmonyHill (100) | 1 |\n| Australia | GrapesGalore (85) | 2 |\n| Australia | WhisperingPines (84) | 3 |\n| Hungary | MoonlitCellars (60) | 1 |\n| India | SunsetVines (69) | 1 |\n| USA | RoyalVines (86) | 1 |\n| USA | Eagle'sNest (45) | 2 |\n| USA | PacificCrest (9) | 3 |\n\nNext, we just need to filter out the data where `rk = 1`, then join table `T` to itself twice, connecting the data where `rk = 2` and `rk = 3` respectively, to get the final result." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 2992, "explanations": { "1": "We can use a binary number $mask$ to represent the current permutation state, where the $i$-th bit is $1$ indicates that the number $i$ has been used, and $0$ indicates that the number $i$ has not been used yet.\n\nThen, we design a function $dfs(mask)$, which represents the number of permutations that can be constructed from the current permutation state $mask$ and meet the requirements of the problem. The answer is $dfs(0)$.\n\nWe can use the method of memoization search to calculate the value of $dfs(mask)$.\n\nIn the process of calculating $dfs(mask)$, we use $i$ to indicate which number is to be added to the permutation. If $i \\gt n$, it means that the permutation has been constructed, and we can return $1$.\n\nOtherwise, we enumerate the numbers $j$ that have not been used in the current permutation. If $i$ and $j$ meet the requirements of the problem, then we can add $j$ to the permutation. At this time, the state becomes $mask \\mid 2^j$, where $|$ represents bitwise OR operation. Since $j$ has been used, we need to recursively calculate the value of $dfs(mask \\mid 2^j)$ and add it to $dfs(mask)$.\n\nFinally, we can get the value of $dfs(0)$, which is the answer.\n\nThe time complexity is $O(n \\times 2^n)$, and the space complexity is $O(2^n)$. Where $n$ is the length of the permutation.", "2": "We can rewrite the memoization search in Solution 1 into the form of dynamic programming, define $f[mask]$ to represent the number of permutations that the current permutation state is $mask$ and meet the requirements of the problem. Initially, $f[0]=1$, and the rest are $0$.\n\nWe enumerate $mask$ in the range of $[0, 2^n)$, for each $mask$, we use $i$ to represent which number is the last one to join the permutation, then we enumerate the last number $j$ added to the current permutation. If $i$ and $j$ meet the requirements of the problem, then the state $f[mask]$ can be transferred from the state $f[mask \\oplus 2^(j-1)]$, where $\\oplus$ represents bitwise XOR operation. We add all the values of the transferred state $f[mask \\oplus 2^(j-1)]$ to $f[mask]$, which is the value of $f[mask]$.\n\nFinally, we can get the value of $f[2^n - 1]$, which is the answer.\n\nThe time complexity is $O(n \\times 2^n)$, and the space complexity is $O(2^n)$. Where $n$ is the length of the permutation." }, "is_english": true, "time_complexity": "O(n \\times 2^n)", "space_complexity": "O(2^n)" }, { "problem_id": 2993, "explanations": { "1": "The date functions we use include:\n\n- `DATE_FORMAT(date, format)`: Formats a date as a string\n- `DAYOFWEEK(date)`: Returns the day of the week for a date, where 1 represents Sunday, 2 represents Monday, and so on\n- `DAYOFMONTH(date)`: Returns the day of the month for a date\n\nFirst, we use the `DATE_FORMAT` function to format the date in the form of `YYYYMM`, then filter out the records of November 2023 that fall on a Friday. Next, we group the records by `purchase_date` and calculate the total consumption amount for each Friday." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 2994, "explanations": { "1": "We can generate a table `T` that contains all dates in November 2023 using recursion, then use a left join to connect `T` and the `Purchases` table by date. Finally, group and sum according to the requirements of the problem." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 2995, "explanations": { "1": "We can use the window function `RANK()` to rank each session by `user_id` dimension, and record it in table `T`. Then, we equi-join `T` and the `Sessions` table by `user_id`, and filter out the records in `T` where the rank is 1, and `session_type` is `Viewer`, and `session_type` in the `Sessions` table is `Streamer`. Finally, we group by `user_id` and sum up." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 2996, "explanations": { "1": "First, we calculate the longest prefix sum $s$ of the array $nums$. Then, starting from $s$, we enumerate the integer $x$. If $x$ is not in the array $nums$, then $x$ is the answer. Here, we can use a hash table to quickly determine whether an integer is in the array $nums$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 2997, "explanations": { "1": "We can perform a bitwise XOR operation on all elements in the array $nums$. The number of bits that differ from the binary representation of $k$ in the result is the minimum number of operations.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 2998, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 2999, "explanations": { "1": "This problem is essentially about finding the count of numbers in the given range $[l, .., r]$ that satisfy the conditions. The count depends on the number of digits and the value of each digit. We can solve this problem using the Digit DP approach, where the size of the number has minimal impact on the complexity.\n\nFor the range $[l, .., r]$, we typically transform it into two subproblems: $[1, .., r]$ and $[1, .., l - 1]$, i.e.,\n\n$$\nans = \\sum_{i=1}^{r} ans_i - \\sum_{i=1}^{l-1} ans_i\n$$\n\nFor this problem, we calculate the count of numbers in $[1, \\textit{finish}]$ that satisfy the conditions, and subtract the count of numbers in $[1, \\textit{start} - 1]$ that satisfy the conditions to get the final answer.\n\nWe use memoization to implement Digit DP. Starting from the topmost digit, we recursively calculate the number of valid numbers, accumulate the results layer by layer, and finally return the answer from the starting point.\n\nThe basic steps are as follows:\n\n1. Convert $\\textit{start}$ and $\\textit{finish}$ to strings for easier manipulation in Digit DP.\n2. Design a function $\\textit{dfs}(\\textit{pos}, \\textit{lim})$, which represents the count of valid numbers starting from the $\\textit{pos}$-th digit, with the current restriction condition $\\textit{lim}$.\n3. If the maximum number of digits is less than the length of $\\textit{s}$, return 0.\n4. If the remaining number of digits equals the length of $\\textit{s}$, check if the current number satisfies the condition and return 1 or 0.\n5. Otherwise, calculate the upper limit of the current digit as $\\textit{up} = \\min(\\textit{lim} ? \\textit{t}[\\textit{pos}] : 9, \\textit{limit})$. Then iterate through the digits $i$ from 0 to $\\textit{up}$, recursively call $\\textit{dfs}(\\textit{pos} + 1, \\textit{lim} \\&\\& i == \\textit{t}[\\textit{pos}])$, and accumulate the results.\n6. If $\\textit{lim}$ is false, store the current result in the cache to avoid redundant calculations.\n7. Finally, return the result.\n\nThe answer is the count of valid numbers in $[1, \\textit{finish}]$ minus the count of valid numbers in $[1, \\textit{start} - 1]$.\n\nTime complexity is $O(\\log M \\times D)$, and space complexity is $O(\\log M)$, where $M$ is the upper limit of the number, and $D = 10$." }, "is_english": true, "time_complexity": "O(\\log M \\times D)", "space_complexity": "O(\\log M)" }, { "problem_id": 3000, "explanations": { "1": "According to the Pythagorean theorem, the square of the diagonal of a rectangle is $l^2 + w^2$, where $l$ and $w$ are the length and width of the rectangle, respectively.\n\nWe can iterate through all the rectangles, calculate the square of their diagonal lengths, and keep track of the maximum diagonal length and the corresponding area.\n\nAfter the iteration, we return the recorded maximum area.\n\nThe time complexity is $O(n)$, where $n$ is the number of rectangles. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3001, "explanations": { "1": "According to the problem description, we can categorize the scenarios for capturing the black queen as follows:\n\n1. The white rook and the black queen are in the same row with no other pieces in between. In this case, the white rook only needs to move once.\n2. The white rook and the black queen are in the same column with no other pieces in between. In this case, the white rook only needs to move once.\n3. The white bishop and the black queen are on the same diagonal `\\` with no other pieces in between. In this case, the white bishop only needs to move once.\n4. The white bishop and the black queen are on the same diagonal `/` with no other pieces in between. In this case, the white bishop only needs to move once.\n5. In other cases, only two moves are needed.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 3002, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3003, "explanations": { "1": "We design a function $\\textit{dfs}(i, \\textit{cur}, t)$ that represents the maximum number of partitions we can obtain when currently processing index $i$ of string $s$, the current prefix already contains the character set $\\textit{cur}$, and we can still modify $t$ characters. Then the answer is $\\textit{dfs}(0, 0, 1)$.\n\nThe execution logic of function $\\textit{dfs}(i, \\textit{cur}, t)$ is as follows:\n\n1. If $i \\geq n$, it means we have finished processing string $s$, return 1.\n2. Calculate the bitmask $v = 1 \\ll (s[i] - 'a')$ corresponding to the current character $s[i]$, and calculate the updated character set $\\textit{nxt} = \\textit{cur} \\mid v$.\n3. If the number of bits in $\\textit{nxt}$ exceeds $k$, it means the current prefix already contains more than $k$ distinct characters. We need to make a partition, increment the partition count by 1, and recursively call $\\textit{dfs}(i + 1, v, t)$. Otherwise, continue recursively calling $\\textit{dfs}(i + 1, \\textit{nxt}, t)$.\n4. If $t > 0$, it means we can still modify a character once. We try to change the current character $s[i]$ to any lowercase letter (26 choices in total). For each choice, calculate the updated character set $\\textit{nxt} = \\textit{cur} \\mid (1 \\ll j)$, and based on whether it exceeds $k$ distinct characters, choose the corresponding recursive call method to update the maximum partition count.\n5. Use a hash table to cache already computed states to avoid redundant calculations.\n\nThe time complexity is $O(n \\times |\\Sigma| \\times k)$ and the space complexity is $O(n \\times |\\Sigma| \\times k)$, where $n$ is the length of string $s$, and $|\\Sigma|$ is the size of the character set." }, "is_english": true, "time_complexity": "O(n \\times |\\Sigma| \\times k)", "space_complexity": "O(n \\times |\\Sigma| \\times k)" }, { "problem_id": 3004, "explanations": { "1": "First, according to the edge information given in the problem, we construct an adjacency list $g$, where $g[a]$ represents all adjacent nodes of node $a$. Then we create an array $size$ of length $n$, where $size[a]$ represents the number of nodes in the subtree with node $a$ as the root.\n\nNext, we design a function $dfs(a, fa)$, which will return whether the subtree with node $a$ as the root meets the requirements of the problem. The execution process of the function $dfs(a, fa)$ is as follows:\n\n- First, we use a variable $ok$ to record whether the subtree with node $a$ as the root meets the requirements of the problem, and initially $ok$ is $true$.\n- Then, we traverse all adjacent nodes $b$ of node $a$. If $b$ is not the parent node $fa$ of $a$, then we recursively call $dfs(b, a)$, save the return value into the variable $t$, and update $ok$ to the value of $ok$ and $colors[a] = colors[b] \\land t$, where $\\land$ represents logical AND operation. Then, we update $size[a] = size[a] + size[b]$.\n- After that, we judge the value of $ok$. If $ok$ is $true$, then we update the answer $ans = \\max(ans, size[a])$.\n- Finally, we return the value of $ok$.\n\nWe call $dfs(0, -1)$, where $0$ represents the root node number, and $-1$ represents that the root node has no parent node. The final answer is $ans$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3005, "explanations": { "1": "We can use a hash table or array $cnt$ to record the occurrence of each element.\n\nThen we traverse $cnt$ to find the element with the most occurrences, and let its occurrence be $mx$. We sum up the occurrences of elements that appear $mx$ times, which is the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3006, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3007, "explanations": { "1": "We notice that if $\\textit{num}$ increases, the total value from $1$ to $\\textit{num}$ also increases. Therefore, we can use a binary search method to find the largest cheap number.\n\nWe define the left boundary of the binary search as $l = 1$. Since there is at least one valuable number in every $2^x + 1$ numbers, and the total value does not exceed $10^{15}$, we can set the right boundary of the binary search as $r = 10^{18}$.\n\nNext, we perform a binary search. For each $\\textit{mid}$, we use the digit DP method to calculate the total value from $1$ to $\\textit{mid}$. If the total value does not exceed $k$, it means $\\textit{mid}$ is a cheap number, and we update the left boundary $l$ to $\\textit{mid}$. Otherwise, we update the right boundary $r$ to $\\textit{mid} - 1$.\n\nFinally, we return the left boundary $l$.\n\nThe time complexity is $O(\\log^2 k)$, and the space complexity is $O(\\log k)$." }, "is_english": true, "time_complexity": "O(\\log^2 k)", "space_complexity": "O(\\log k)" }, { "problem_id": 3008, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3009, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3010, "explanations": { "1": "We set the first element of the array $nums$ as $a$, the smallest element among the remaining elements as $b$, and the second smallest element as $c$. The answer is $a+b+c$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3011, "explanations": { "1": "We can use two pointers to divide the array $\\textit{nums}$ into several subarrays, each subarray containing elements with the same number of $1$s in their binary representation. For each subarray, we only need to focus on its maximum and minimum values. If the minimum value is less than the maximum value of the previous subarray, then it is impossible to make the array ordered by swapping.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3012, "explanations": { "1": "Let's denote the smallest element in the array $nums$ as $mi$.\n\nIf $mi$ appears only once, we can perform operations with $mi$ and the other elements in the array $nums$ to eliminate all other elements, leaving only $mi$. The answer is $1$.\n\nIf $mi$ appears multiple times, we need to check whether all elements in the array $nums$ are multiples of $mi$. If not, there exists at least one element $x$ such that $0 < x \\bmod mi < mi$. This means we can construct an element smaller than $mi$ through operations. This smaller element can eliminate all other elements through operations, leaving only this smaller element. The answer is $1$. If all elements are multiples of $mi$, we can first use $mi$ to eliminate all elements larger than $mi$. The remaining elements are all $mi$, with a count of $cnt$. Pair them up, and perform an operation for each pair. Finally, there will be $\\lceil cnt / 2 \\rceil$ elements left, so the answer is $\\lceil cnt / 2 \\rceil$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3013, "explanations": { "1": "The problem requires us to divide the array $\\textit{nums}$ into $k$ consecutive and non-overlapping subarrays, and the distance between the first element of the second subarray and the first element of the $k$-th subarray should not exceed $\\textit{dist}$. This is equivalent to finding a subarray of size $\\textit{dist}+1$ starting from the element at index $1$ in $\\textit{nums}$, and calculating the sum of the smallest $k-1$ elements in it. We subtract $1$ from $k$, so we only need to find the sum of the smallest $k$ elements and add $\\textit{nums}[0]$ to it.\n\nWe can use two ordered sets $\\textit{l}$ and $\\textit{r}$ to maintain the elements of the window of size $\\textit{dist} + 1$. The set $\\textit{l}$ maintains the smallest $k$ elements, while the set $\\textit{r}$ maintains the remaining elements of the window. We maintain a variable $\\textit{s}$ to represent the sum of $\\textit{nums}[0]$ and the elements in $\\textit{l}$. Initially, we add the sum of the first $\\textit{dist}+2$ elements to $\\textit{s}$ and add all elements with indices $[1, \\textit{dist} + 1]$ to $\\textit{l}$. If the size of $\\textit{l}$ is greater than $k$, we repeatedly move the largest element from $\\textit{l}$ to $\\textit{r}$ until the size of $\\textit{l}$ equals $k$, updating the value of $\\textit{s}$ in the process.\n\nAt this point, the initial answer is $\\textit{ans} = \\textit{s}$.\n\nNext, we traverse $\\textit{nums}$ starting from $\\textit{dist}+2$. For each element $\\textit{nums}[i]$, we need to remove $\\textit{nums}[i-\\textit{dist}-1]$ from either $\\textit{l}$ or $\\textit{r}$, and then add $\\textit{nums}[i]$ to either $\\textit{l}$ or $\\textit{r}$. If $\\textit{nums}[i]$ is less than the largest element in $\\textit{l}$, we add $\\textit{nums}[i]$ to $\\textit{l}$; otherwise, we add it to $\\textit{r}$. If the size of $\\textit{l}$ is less than $k$, we move the smallest element from $\\textit{r}$ to $\\textit{l}$ until the size of $\\textit{l}$ equals $k$. If the size of $\\textit{l}$ is greater than $k$, we move the largest element from $\\textit{l}$ to $\\textit{r}$ until the size of $\\textit{l}$ equals $k$. During this process, we update the value of $\\textit{s}$ and update $\\textit{ans} = \\min(\\textit{ans}, \\textit{s})$.\n\nThe final answer is $\\textit{ans}$.\n\nThe time complexity is $O(n \\times \\log \\textit{dist})$, and the space complexity is $O(\\textit{dist})$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times \\log \\textit{dist})", "space_complexity": "O(\\textit{dist})" }, { "problem_id": 3014, "explanations": { "1": "We notice that all the letters in the string $word$ are different. Therefore, we can greedily distribute the letters evenly across the $8$ keys to minimize the number of key presses.\n\nThe time complexity is $O(n / 8)$, where $n$ is the length of the string $word$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n / 8)", "space_complexity": "O(1)" }, { "problem_id": 3015, "explanations": { "1": "We can enumerate each pair of points $(i, j)$. The shortest distance from $i$ to $j$ is $min(|i - j|, |i - x| + 1 + |j - y|, |i - y| + 1 + |j - x|)$. We add $2$ to the count of this distance because both $(i, j)$ and $(j, i)$ are valid pairs of points.\n\nThe time complexity is $O(n^2)$, where $n$ is the $n$ given in the problem. Ignoring the space consumption of the answer array, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(1)" }, { "problem_id": 3016, "explanations": { "1": "We use a hash table or array $cnt$ to count the number of occurrences of each letter in the string $word$. Next, we sort the letters in descending order of their counts, and then group every $8$ letters together, assigning each group to the $8$ keys.\n\nThe time complexity is $O(n + |\\Sigma| \\times \\log |\\Sigma|)$, and the space complexity is $O(|\\Sigma|)$. Here, $n$ is the length of the string $word$, and $\\Sigma$ is the set of letters that appear in the string $word$." }, "is_english": true, "time_complexity": "O(n + |\\Sigma| \\times \\log |\\Sigma|)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 3017, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3018, "explanations": { "1": "We define $f[i][j]$ as the maximum number of queries we can handle when the numbers in the interval $[i, j]$ have not been deleted yet.\n\nConsider $f[i][j]$:\n\n- If $i > 0$, the value of $f[i][j]$ can be transferred from $f[i - 1][j]$. If $nums[i - 1] \\ge queries[f[i - 1][j]]$, we can choose to delete $nums[i - 1]$. Therefore, we have $f[i][j] = f[i - 1][j] + (nums[i - 1] \\ge queries[f[i - 1][j]])$.\n- If $j + 1 < n$, the value of $f[i][j]$ can be transferred from $f[i][j + 1]$. If $nums[j + 1] \\ge queries[f[i][j + 1]]$, we can choose to delete $nums[j + 1]$. Therefore, we have $f[i][j] = f[i][j + 1] + (nums[j + 1] \\ge queries[f[i][j + 1]])$.\n- If $f[i][j] = m$, we can directly return $m$.\n\nThe final answer is $\\max\\limits_{0 \\le i < n} f[i][i] + (nums[i] \\ge queries[f[i][i]])$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 3019, "explanations": { "1": "We can traverse the string, each time checking whether the lowercase form of the current character is the same as the lowercase form of the previous character. If they are different, it means that the key has been changed, and we can increment the answer accordingly.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3020, "explanations": { "1": "We use a hash table $cnt$ to record the occurrence count of each element in the array $nums$. For each element $x$, we can keep squaring it until its count in the hash table $cnt$ is less than $2$. At this point, we check if the count of $x$ in the hash table $cnt$ is $1$. If it is, it means that $x$ can still be included in the subset. Otherwise, we need to remove an element from the subset to ensure the subset count is odd. Then we update the answer and continue to enumerate the next element.\n\nNote that we need to handle the case of $x = 1$ specially.\n\nThe time complexity is $O(n \\times \\log \\log M)$, and the space complexity is $O(n)$. Here, $n$ and $M$ are the length of the array $nums$ and the maximum value in the array $nums$, respectively." }, "is_english": true, "time_complexity": "O(n \\times \\log \\log M)", "space_complexity": "O(n)" }, { "problem_id": 3021, "explanations": { "1": "According to the problem description, in each move, the player will choose to move in a clockwise or counterclockwise direction and then pick a flower. Since Alice moves first, when $x + y$ is odd, Alice will definitely win the game.\n\nTherefore, the number of flowers $x$ and $y$ meet the following conditions:\n\n1. $x + y$ is odd;\n2. $1 \\le x \\le n$;\n3. $1 \\le y \\le m$.\n\nIf $x$ is odd, $y$ must be even. At this time, the number of values of $x$ is $\\lceil \\frac{n}{2} \\rceil$, the number of values of $y$ is $\\lfloor \\frac{m}{2} \\rfloor$, so the number of pairs that meet the conditions is $\\lceil \\frac{n}{2} \\rceil \\times \\lfloor \\frac{m}{2} \\rfloor$.\n\nIf $x$ is even, $y$ must be odd. At this time, the number of values of $x$ is $\\lfloor \\frac{n}{2} \\rfloor$, the number of values of $y$ is $\\lceil \\frac{m}{2} \\rceil$, so the number of pairs that meet the conditions is $\\lfloor \\frac{n}{2} \\rfloor \\times \\lceil \\frac{m}{2} \\rceil$.\n\nTherefore, the number of pairs that meet the conditions is $\\lceil \\frac{n}{2} \\rceil \\times \\lfloor \\frac{m}{2} \\rfloor + \\lfloor \\frac{n}{2} \\rfloor \\times \\lceil \\frac{m}{2} \\rceil$, which is $\\lfloor \\frac{n + 1}{2} \\rfloor \\times \\lfloor \\frac{m}{2} \\rfloor + \\lfloor \\frac{n}{2} \\rfloor \\times \\lfloor \\frac{m + 1}{2} \\rfloor$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$.", "2": "The result obtained from Solution 1 is $\\lfloor \\frac{n + 1}{2} \\rfloor \\times \\lfloor \\frac{m}{2} \\rfloor + \\lfloor \\frac{n}{2} \\rfloor \\times \\lfloor \\frac{m + 1}{2} \\rfloor$.\n\nIf both $n$ and $m$ are odd, then the result is $\\frac{n + 1}{2} \\times \\frac{m - 1}{2} + \\frac{n - 1}{2} \\times \\frac{m + 1}{2}$, which is $\\frac{n \\times m - 1}{2}$.\n\nIf both $n$ and $m$ are even, then the result is $\\frac{n}{2} \\times \\frac{m}{2} + \\frac{n}{2} \\times \\frac{m}{2}$, which is $\\frac{n \\times m}{2}$.\n\nIf $n$ is odd and $m$ is even, then the result is $\\frac{n + 1}{2} \\times \\frac{m}{2} + \\frac{n - 1}{2} \\times \\frac{m}{2}$, which is $\\frac{n \\times m}{2}$.\n\nIf $n$ is even and $m$ is odd, then the result is $\\frac{n}{2} \\times \\frac{m - 1}{2} + \\frac{n}{2} \\times \\frac{m + 1}{2}$, which is $\\frac{n \\times m}{2}$.\n\nThe above four cases can be combined into $\\lfloor \\frac{n \\times m}{2} \\rfloor$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 3022, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3023, "explanations": { "1": "We notice that the length of the array $pattern$ does not exceed $100$, therefore, we can use two $64$-bit integers $a$ and $b$ to represent the binary numbers of the left and right halves of $pattern$.\n\nNext, we traverse the data stream, also maintaining two $64$-bit integers $x$ and $y$ to represent the binary numbers of the current window of the length of $pattern$. If the current length reaches the window length, we compare whether $a$ and $x$ are equal, and whether $b$ and $y$ are equal. If they are, we return the index of the current data stream.\n\nThe time complexity is $O(n + m)$, where $n$ and $m$ are the number of elements in the data stream and $pattern$ respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(1)" }, { "problem_id": 3024, "explanations": { "1": "First, we sort the array, and then we can classify and discuss according to the definition of a triangle.\n\n- If the sum of the smallest two numbers is less than or equal to the largest number, then it cannot form a triangle, return \"none\".\n- If the smallest number is equal to the largest number, then it is an equilateral triangle, return \"equilateral\".\n- If the smallest number is equal to the middle number or the middle number is equal to the largest number, then it is an isosceles triangle, return \"isosceles\".\n- Otherwise, return \"scalene\".\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 3025, "explanations": { "1": "First, we sort the array. Then, we can classify the results based on the properties of a triangle.\n\n- If the sum of the two smaller numbers is less than or equal to the largest number, it cannot form a triangle. Return \"Invalid\".\n- If the three numbers are equal, it is an equilateral triangle. Return \"Equilateral\".\n- If two numbers are equal, it is an isosceles triangle. Return \"Isosceles\".\n- If none of the above conditions are met, it is a scalene triangle. Return \"Scalene\".\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 3026, "explanations": { "1": "We use a hash table $p$ to record the sum $s$ of the prefix array $nums[0..i-1]$ for $nums[i]$. If there are multiple identical $nums[i]$, we only keep the smallest $s$. Initially, we set $p[nums[0]]$ to $0$. In addition, we use a variable $s$ to record the current prefix sum, initially $s = 0$. Initialize the answer $ans$ to $-\\infty$.\n\nNext, we enumerate $nums[i]$, and maintain a variable $s$ to represent the sum of $nums[0..i]$. If $nums[i] - k$ is in $p$, then we have found a good subarray, and update the answer to $ans = \\max(ans, s - p[nums[i] - k])$. Similarly, if $nums[i] + k$ is in $p$, then we have also found a good subarray, and update the answer to $ans = \\max(ans, s - p[nums[i] + k])$. Then, if $i + 1 \\lt n$ and $nums[i + 1]$ is not in $p$, or $p[nums[i + 1]] \\gt s$, we set $p[nums[i + 1]]$ to $s$.\n\nFinally, if $ans = -\\infty$, then we return $0$, otherwise return $ans$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3027, "explanations": { "1": "First, we sort the array. Then, we can classify the results based on the properties of a triangle.\n\n- If the sum of the two smaller numbers is less than or equal to the largest number, it cannot form a triangle. Return \"Invalid\".\n- If the three numbers are equal, it is an equilateral triangle. Return \"Equilateral\".\n- If two numbers are equal, it is an isosceles triangle. Return \"Isosceles\".\n- If none of the above conditions are met, it is a scalene triangle. Return \"Scalene\".\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 3028, "explanations": { "1": "Based on the problem description, we only need to calculate how many zeros are in all prefix sums of `nums`.\n\nThe time complexity is $O(n)$, where $n$ is the length of `nums`. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3029, "explanations": { "1": "Let's assume that if we can restore `word` to its initial state with only one operation, it means that `word[k:]` is a prefix of `word`, i.e., `word[k:] == word[:n-k]`.\n\nIf there are multiple operations, let's assume $i$ is the number of operations, then it means that `word[k*i:]` is a prefix of `word`, i.e., `word[k*i:] == word[:n-k*i]`.\n\nTherefore, we can enumerate the number of operations and check whether `word[k*i:]` is a prefix of `word`. If it is, then return $i$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ is the length of `word`.", "2": "Based on Solution 1, we can also use string hashing to determine whether two strings are equal.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of `word`." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 3030, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3031, "explanations": { "1": "我们不妨假设,如果只操作一次,就能使得 `word` 恢复到初始状态,那么意味着 `word[k:]` 是 `word` 的前缀,即 `word[k:] == word[:n-k]`。\n\n如果有多次操作,不妨设 $i$ 为操作次数,那么意味着 `word[k*i:]` 是 `word` 的前缀,即 `word[k*i:] == word[:n-k*i]`。\n\n因此,我们可以枚举操作次数,利用字符串哈希来判断两个字符串是否相等。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为 `word` 的长度。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3032, "explanations": { "1": "The problem asks to count how many numbers in the range $[a, b]$ have unique digits. We can solve this problem using state compression and digit DP.\n\nWe can use a function $f(n)$ to count how many numbers in the range $[1, n]$ have unique digits. Then the answer is $f(b) - f(a - 1)$.\n\nIn addition, we can use a binary number to record the digits that have appeared in the number. For example, if the digits $1, 3, 5$ have appeared in the number, we can use $10101$ to represent this state.\n\nNext, we use memoization search to implement digit DP. We search from the starting point to the bottom layer to get the number of schemes, return the answer layer by layer and accumulate it, and finally get the final answer from the search starting point.\n\nThe basic steps are as follows:\n\n1. We convert the number $n$ into a string $num$, where $num[0]$ is the highest digit and $num[len - 1]$ is the lowest digit.\n2. Based on the problem information, we design a function $dfs(pos, mask, limit)$, where $pos$ represents the current processing position, $mask$ represents the digits that have appeared in the current number, and $limit$ represents whether there is a limit at the current position. If $limit$ is true, then the digit at the current position cannot exceed $num[pos]$.\n\nThe answer is $dfs(0, 0, true)$.\n\nThe time complexity is $O(m \\times 2^{10} \\times 10)$, and the space complexity is $O(m \\times 2^{10})$. Where $m$ is the number of digits in $b$.", "2": "" }, "is_english": true, "time_complexity": "O(m \\times 2^{10} \\times 10)", "space_complexity": "O(m \\times 2^{10})" }, { "problem_id": 3033, "explanations": { "1": "We can follow the problem description, traverse each column, find the maximum value of each column, and then traverse each column again, replacing the elements with a value of -1 with the maximum value of that column.\n\nThe time complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns of the matrix, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(1)" }, { "problem_id": 3034, "explanations": { "1": "We can enumerate all subarrays of array `nums` with a length of $m + 1$, and then check whether they match the pattern array `pattern`. If they do, we increment the answer by one.\n\nThe time complexity is $O(n \\times m)$, where $n$ and $m$ are the lengths of the arrays `nums` and `pattern` respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times m)", "space_complexity": "O(1)" }, { "problem_id": 3035, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3036, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3037, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3038, "explanations": { "1": "First, we calculate the sum of the first two elements, denoted as $s$. Then we traverse the array, taking two elements at a time. If their sum is not equal to $s$, we stop the traversal. Finally, we return the number of operations performed.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3039, "explanations": { "1": "We use a hash table or array $cnt$ to record the occurrence times of each character in string $s$, and use another hash table or array $last$ to record the last occurrence position of each character in string $s$. The maximum occurrence times of characters in string $s$ is denoted as $mx$.\n\nThen we traverse the string $s$. If the occurrence times of the current character equals $mx$ and the position of the current character equals the last occurrence position of this character, then we add the current character to the answer.\n\nAfter the traversal, we return the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(|\\Sigma|)$, where $n$ is the length of string $s$, and $\\Sigma$ is the character set. In this problem, $\\Sigma$ is the set of lowercase English letters." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 3040, "explanations": { "1": "There are three possible values for the score $s$, which are $s = nums[0] + nums[1]$, $s = nums[0] + nums[n-1]$, and $s = nums[n-1] + nums[n-2]$. We can perform memorization search for these three cases separately.\n\nWe design a function $dfs(i, j)$, which represents the maximum number of operations from index $i$ to index $j$ when the score is $s$. The execution process of function $dfs(i, j)$ is as follows:\n\n- If $j - i < 1$, it means that the length of the interval $[i, j]$ is less than $2$, and no operation can be performed, so return $0$.\n- If $nums[i] + nums[i+1] = s$, it means that the elements at index $i$ and index $i+1$ can be deleted. In this case, the maximum number of operations is $1 + dfs(i+2, j)$.\n- If $nums[i] + nums[j] = s$, it means that the elements at index $i$ and index $j$ can be deleted. In this case, the maximum number of operations is $1 + dfs(i+1, j-1)$.\n- If $nums[j-1] + nums[j] = s$, it means that the elements at index $j-1$ and index $j$ can be deleted. In this case, the maximum number of operations is $1 + dfs(i, j-2)$.\n- Return the maximum of the above values.\n\nFinally, we calculate the maximum number of operations for the three cases separately, and return the maximum value.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 3041, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3042, "explanations": { "1": "We can enumerate all index pairs $(i, j)$, where $i < j$, and then determine whether `words[i]` is a prefix or suffix of `words[j]`. If it is, we increment the count.\n\nThe time complexity is $O(n^2 \\times m)$, where $n$ and $m$ are the length of `words` and the maximum length of the strings, respectively.", "2": "We can treat each string $s$ in the string array as a list of character pairs, where each character pair $(s[i], s[m - i - 1])$ represents the $i$th character pair of the prefix and suffix of string $s$.\n\nWe can use a trie to store all the character pairs, and then for each string $s$, we search for all the character pairs $(s[i], s[m - i - 1])$ in the trie, and add their counts to the answer.\n\nThe time complexity is $O(n \\times m)$, and the space complexity is $O(n \\times m)$. Here, $n$ and $m$ are the lengths of `words` and the maximum length of the strings, respectively." }, "is_english": true, "time_complexity": "O(n^2 \\times m)", "space_complexity": "O(n \\times m)" }, { "problem_id": 3043, "explanations": { "1": "We can use a hash table to store all the prefixes of the numbers in `arr1`. Then, we traverse all the numbers $x$ in `arr2`. For each number $x$, we start from the highest bit and gradually decrease, checking whether it exists in the hash table. If it does, we have found a common prefix, and we can update the answer accordingly.\n\nThe time complexity is $O(m \\times \\log M + n \\times \\log N)$, and the space complexity is $O(m \\times \\log M)$. Here, $m$ and $n$ are the lengths of `arr1` and `arr2` respectively, and $M$ and $N$ are the maximum values in `arr1` and `arr2` respectively." }, "is_english": true, "time_complexity": "O(m \\times \\log M + n \\times \\log N)", "space_complexity": "O(m \\times \\log M)" }, { "problem_id": 3044, "explanations": { "1": "We can use a hash table to count the frequency of each prime number greater than 10.\n\nFor each cell, we can start from it, generate a number along one of the 8 directions, and then determine whether the generated number is a prime number greater than 10. If it is, we add it to the hash table.\n\nFinally, we traverse the hash table to find the prime number with the highest frequency. If there are multiple prime numbers with the highest frequency, we return the largest one.\n\nThe time complexity is $O(m \\times n \\times \\max(m, n) \\times {10}^{\\frac{\\max(m, n)}{2}})$, and the space complexity is $O(m \\times n \\times \\max(m, n))$. Here, $m$ and $n$ are the number of rows and columns of `mat`, respectively." }, "is_english": true, "time_complexity": "O(m \\times n \\times \\max(m, n) \\times {10}^{\\frac{\\max(m, n)}{2}})", "space_complexity": "O(m \\times n \\times \\max(m, n))" }, { "problem_id": 3045, "explanations": { "1": "We can treat each string $s$ in the string array as a list of character pairs, where each character pair $(s[i], s[m - i - 1])$ represents the $i$th character pair of the prefix and suffix of string $s$.\n\nWe can use a trie to store all the character pairs, and then for each string $s$, we search for all the character pairs $(s[i], s[m - i - 1])$ in the trie, and add their counts to the answer.\n\nThe time complexity is $O(n \\times m)$, and the space complexity is $O(n \\times m)$. Here, $n$ and $m$ are the lengths of `words` and the maximum length of the strings, respectively." }, "is_english": true, "time_complexity": "O(n \\times m)", "space_complexity": "O(n \\times m)" }, { "problem_id": 3046, "explanations": { "1": "According to the problem, we need to divide the array into two parts, and the elements in each part are all distinct. Therefore, we can count the occurrence of each element in the array. If an element appears three or more times, it cannot satisfy the problem's requirements. Otherwise, we can divide the array into two parts.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3047, "explanations": { "1": "We can enumerate two rectangles, where the coordinates of the bottom left and top right corners of rectangle 1 are $(x_1, y_1)$ and $(x_2, y_2)$ respectively, and the coordinates of the bottom left and top right corners of rectangle 2 are $(x_3, y_3)$ and $(x_4, y_4)$ respectively.\n\nIf rectangle 1 and rectangle 2 intersect, then the coordinates of the intersection are:\n\n- The x-coordinate of the bottom left corner is the maximum of the x-coordinates of the bottom left corners of the two rectangles, i.e., $\\max(x_1, x_3)$;\n- The y-coordinate of the bottom left corner is the maximum of the y-coordinates of the bottom left corners of the two rectangles, i.e., $\\max(y_1, y_3)$;\n- The x-coordinate of the top right corner is the minimum of the x-coordinates of the top right corners of the two rectangles, i.e., $\\min(x_2, x_4)$;\n- The y-coordinate of the top right corner is the minimum of the y-coordinates of the top right corners of the two rectangles, i.e., $\\min(y_2, y_4)$.\n\nThen the width and height of the intersection are $w = \\min(x_2, x_4) - \\max(x_1, x_3)$ and $h = \\min(y_2, y_4) - \\max(y_1, y_3)$ respectively. We take the minimum of the two as the side length, i.e., $e = \\min(w, h)$. If $e > 0$, then we can get a square with an area of $e^2$. We take the maximum area of all squares.\n\nThe time complexity is $O(n^2)$, where $n$ is the number of rectangles. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(1)" }, { "problem_id": 3048, "explanations": { "1": "We notice that if we can mark all indices within $t$ seconds, then we can also mark all indices within $t' \\geq t$ seconds. Therefore, we can use binary search to find the earliest seconds.\n\nWe define the left and right boundaries of binary search as $l = 1$ and $r = m + 1$, where $m$ is the length of the array `changeIndices`. For each $t = \\frac{l + r}{2}$, we check whether we can mark all indices within $t$ seconds. If we can, we move the right boundary to $t$, otherwise we move the left boundary to $t + 1$. Finally, we judge whether the left boundary is greater than $m$, if it is, return $-1$, otherwise return the left boundary.\n\nThe key to the problem is how to judge whether we can mark all indices within $t$ seconds. We can use an array $last$ to record the latest time each index needs to be marked, use a variable $decrement$ to record the current number of times that can be reduced, and use a variable $marked$ to record the number of indices that have been marked.\n\nWe traverse the first $t$ elements of the array `changeIndices`, for each element $i$, if $last[i] = s$, then we need to check whether $decrement$ is greater than or equal to $nums[i - 1]$, if it is, we subtract $nums[i - 1]$ from $decrement$, and add one to $marked$; otherwise, we return `False`. If $last[i] \\neq s$, then we can temporarily not mark the index, so we add one to $decrement$. Finally, we check whether $marked$ is equal to $n$, if it is, we return `True`, otherwise return `False`.\n\nThe time complexity is $O(m \\times \\log m)$, and the space complexity is $O(n)$. Where $n$ and $m$ are the lengths of `nums` and `changeIndices` respectively." }, "is_english": true, "time_complexity": "O(m \\times \\log m)", "space_complexity": "O(n)" }, { "problem_id": 3049, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3050, "explanations": { "1": "First, we use a window function to sort the table by the `topping_name` field and add a `rk` field to each row, representing the ranking of the current row.\n\nThen we use conditional join to join the table `T` three times, named as `t1`, `t2`, `t3` respectively. The join conditions are `t1.rk < t2.rk` and `t2.rk < t3.rk`. After that, we calculate the total price of the three toppings, sort by total price in descending order, and then sort by topping name in ascending order." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3051, "explanations": { "1": "First, we filter out candidates who have the skills `Python`, `Tableau`, and `PostgreSQL`. Then, we group by `candidate_id` and count the number of skills each candidate has. Finally, we filter out candidates who have these three skills and sort them in ascending order by `candidate_id`." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3052, "explanations": { "1": "First, we calculate the total area of all items of type `prime_eligible` and record it in the `s` field of table `T`.\n\nNext, we calculate the number of items of type `prime_eligible` and `not_prime` respectively. For items of type `prime_eligible`, the number of portions we can store is $\\lfloor \\frac{500000}{s} \\rfloor$. For items of type `not_prime`, the number of portions we can store is $\\lfloor \\frac{500000 \\mod s}{\\sum \\textit{s1}} \\rfloor$. Where $\\sum \\textit{s1}$ is the total area of all items of type `not_prime`. Multiplying by the number of items of type `prime_eligible` and `not_prime` respectively gives us our result." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3053, "explanations": { "1": "We can use the `CASE WHEN` statement to determine the type of the triangle.\n\nFirst, we need to determine whether the three sides can form a triangle. If not, we return `Not A Triangle`.\n\nThen, we check if the lengths of the three sides are equal. If they are, we return `Equilateral`.\n\nNext, we check if there are two sides with equal length. If there are, we return `Isosceles`.\n\nOtherwise, it means that the lengths of the three sides are all different, so we return `Scalene`." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3054, "explanations": { "1": "If a node's parent is null, then it is a root node; if a node is not the parent of any node, then it is a leaf node; otherwise, it is an internal node.\n\nTherefore, we use left join to join the `Tree` table twice, with the join condition being `t1.N = t2.P`. If `t1.P` is null, then `t1.N` is a root node; if `t2.P` is null, then `t1.N` is a leaf node; otherwise, `t1.N` is an internal node." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3055, "explanations": { "1": "We can use the `RANK()` window function to calculate the ranking of fraud scores for each state, then filter out the records with a rank of 1, and sort them as required by the problem." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3056, "explanations": { "1": "We can perform an equi-join to connect the `Activities` table and the `Age` table based on `user_id`. Then, group by `age_bucket` and finally calculate the percentage of sends and opens for each age group." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3057, "explanations": { "1": "First, we join the `Project` table and the `Employees` table based on `employee_id`, then group by `team` to calculate the average workload of each team, and record it in the temporary table `T`.\n\nThen, we join the `Project` table and the `Employees` table again, and also join the `T` table, to find employees whose workload is greater than the average workload of the team. Finally, we sort by `employee_id` and `project_id`." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3058, "explanations": { "1": "First, we list all the friend relationships and record them in table `T`. Then we find the pairs of friends who do not have common friends.\n\nNext, we can use a subquery to find pairs of friends who do not have common friends, i.e., this pair of friends does not belong to any other person's friends." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3059, "explanations": { "1": "First, we filter out all emails ending with `.com`, then use the `SUBSTRING_INDEX` function to extract the domain name of the email. Finally, we use `GROUP BY` to count the number of each domain." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3060, "explanations": { "1": "First, we use the `LAG` window function to find the end time of the previous session of the same type for each user, denoted as `prev_session_end`. Then we use the `TIMESTAMPDIFF` function to calculate the time difference between the start time of the current session and the end time of the previous session. If the time difference is less than or equal to 12 hours, then this user meets the requirements of the problem." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3061, "explanations": { "1": "We use the window function `MAX(height) OVER (ORDER BY id)` to calculate the maximum height for each position and its left side, and use `MAX(height) OVER (ORDER BY id DESC)` to calculate the maximum height for each position and its right side, denoted as `l` and `r` respectively. Then, the amount of water stored at each position is `min(l, r) - height`. Finally, we sum them up." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3062, "explanations": { "1": "Traverse the linked list, each time taking out two nodes, compare their values, and then update the scores of odd and even numbers based on the comparison results. Finally, compare the scores of odd and even numbers and return the result.\n\nThe time complexity is $O(n)$, where $n$ is the length of the linked list. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3063, "explanations": { "1": "We use a hash table `cnt` to record the occurrence times of each element value in the linked list, then traverse the values of the hash table to construct a new linked list.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the linked list." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3064, "explanations": { "1": "We can enumerate the powers of 2, and then call the `commonSetBits` method. If the return value is greater than 0, it means that the corresponding bit in the binary representation of `n` is 1.\n\nThe time complexity is $O(\\log n)$, where $n \\le 2^{30}$ in this problem. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 3065, "explanations": { "1": "We only need to traverse the array once, counting the number of elements less than $k$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3066, "explanations": { "1": "We can use a priority queue (min heap) to simulate this process.\n\nSpecifically, we first add the elements in the array to the priority queue `pq`. Then we continuously take out the two smallest elements `x` and `y` from the priority queue, and put `min(x, y) * 2 + max(x, y)` back into the priority queue. After each operation, we increase the operation count by one. We stop the operation when the number of elements in the queue is less than 2 or the smallest element in the queue is greater than or equal to `k`.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3067, "explanations": { "1": "First, we construct an adjacency list `g` based on the edges given in the problem, where `g[a]` represents all the neighbor nodes of node `a` and their corresponding edge weights.\n\nThen, we can enumerate each node `a` as the connecting intermediate node, and calculate the number of nodes `t` that start from the neighbor node `b` of `a` and whose distance to node `a` can be divided by `signalSpeed` through depth-first search. Then, the number of connectable node pairs of node `a` increases by `s * t`, where `s` represents the cumulative number of nodes that start from the neighbor node `b` of `a` and whose distance to node `a` cannot be divided by `signalSpeed`. Then we update `s` to `s + t`.\n\nAfter enumerating all nodes `a`, we can get the number of connectable node pairs for all nodes.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$, where $n$ is the number of nodes." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 3068, "explanations": { "1": "For any number $x$, its value remains unchanged after being XORed with $k$ an even number of times. Therefore, for any path in a tree, if we perform the operation on all edges in the path, the values of all nodes on the path except the start and end nodes will not change.\n\nAdditionally, no matter how many operations are performed, there will always be an even number of elements XORed with $k$, and the remaining elements will remain unchanged.\n\nThus, the problem is transformed into: for the array $\\textit{nums}$, select an even number of elements to XOR with $k$ to maximize the sum.\n\nWe can use dynamic programming to solve this problem. Let $f_0$ represent the maximum sum when an even number of elements have been XORed with $k$, and $f_1$ represent the maximum sum when an odd number of elements have been XORed with $k$. The state transition equations are:\n\n$$\n\\begin{aligned}\nf_0 &= \\max(f_0 + x, f_1 + (x \\oplus k)) \\\\\nf_1 &= \\max(f_1 + x, f_0 + (x \\oplus k))\n\\end{aligned}\n$$\n\nwhere $x$ represents the current element's value.\n\nWe traverse the array $\\textit{nums}$ and update $f_0$ and $f_1$ according to the above state transition equations. Finally, we return $f_0$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3069, "explanations": { "1": "We create two arrays $\\textit{arr1}$ and $\\textit{arr2}$ to store the elements of $\\textit{nums}$. Initially, $\\textit{arr1}$ contains only $\\textit{nums[0]}$, and $\\textit{arr2}$ contains only $\\textit{nums[1]}$.\n\nThen we iterate over the elements of $\\textit{nums}$ starting from index $2$. If the last element of $\\textit{arr1}$ is greater than the last element of $\\textit{arr2}$, we append the current element to $\\textit{arr1}$; otherwise, we append it to $\\textit{arr2}$.\n\nFinally, we append the elements of $\\textit{arr2}$ to $\\textit{arr1}$ and return $\\textit{arr1}$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3070, "explanations": { "1": "The problem is actually asking for the number of prefix submatrices in a two-dimensional matrix whose sum is less than or equal to $k$.\n\nThe calculation formula for the two-dimensional prefix sum is:\n\n$$\ns[i][j] = s[i-1][j] + s[i][j-1] - s[i-1][j-1] + x\n$$\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns of the matrix, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 3071, "explanations": { "1": "We use two arrays of length 3, `cnt1` and `cnt2`, to record the counts of cell values that belong to `Y` and do not belong to `Y`, respectively. Then we enumerate `i` and `j`, which represent the values of cells that belong to `Y` and do not belong to `Y`, respectively, to calculate the minimum number of operations.\n\nThe time complexity is $O(n^2)$, where $n$ is the size of the matrix. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(1)" }, { "problem_id": 3072, "explanations": { "1": "We can use two binary indexed trees `tree1` and `tree2` to maintain the number of elements in `arr1` and `arr2` that are less than or equal to a certain number. Each time, we query the number of elements that are less than or equal to the current number in the binary indexed tree, then the number of elements that are greater than the current number is the length of the current array minus the query result. Then we can decide which array to add the current number to based on this difference.\n\nSince the range of numbers given in the problem is very large, we need to discretize these numbers. We can sort these numbers and remove duplicates, then use binary search to find the position of each number in the sorted array.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$, where $n$ is the length of the array `nums`." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3073, "explanations": { "1": "We can consider enumerating $nums[j]$. Then, we need to find the largest $nums[i]$ on the left of $j$ such that $nums[i] < nums[j]$, and find the largest $nums[k]$ on the right of $j$ such that $nums[k] > nums[j]$.\n\nTherefore, we can preprocess an array $right$, where $right[i]$ represents the maximum value to the right of $nums[i]$. Then, we can use an ordered set to maintain the values on the left of $nums[j]$, so that we can find the largest $nums[i]$ less than $nums[j]$ in $O(\\log n)$ time.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3074, "explanations": { "1": "To minimize the number of boxes needed, we should prioritize using boxes with larger capacities. Therefore, we can sort the boxes in descending order of capacity, and then use the boxes one by one until all the apples are packed. We return the number of boxes used at this point.\n\nThe time complexity is $O(m \\times \\log m + n)$ and the space complexity is $O(\\log m)$, where $m$ and $n$ are the lengths of the arrays $\\textit{capacity}$ and $\\textit{apple}$ respectively." }, "is_english": true, "time_complexity": "O(m \\times \\log m + n)", "space_complexity": "O(\\log m)" }, { "problem_id": 3075, "explanations": { "1": "To maximize the sum of happiness values, we should prioritize selecting children with higher happiness values. Therefore, we can sort the children in descending order by happiness value, and then select $k$ children in sequence. For the current $i$-th child, the happiness value obtained is $\\max(\\textit{happiness}[i] - i, 0)$. Finally, return the sum of happiness values of these $k$ children.\n\nThe time complexity is $O(n \\times \\log n + k)$, and the space complexity is $O(\\log n)$, where $n$ is the length of the array $\\textit{happiness}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n + k)", "space_complexity": "O(\\log n)" }, { "problem_id": 3076, "explanations": { "1": "Given the small data scale, we can directly enumerate all substrings of each string and then determine whether it is a substring of other strings.\n\nSpecifically, we first enumerate each string `arr[i]`, then enumerate the length $j$ of each substring from small to large, and then enumerate the starting position $l$ of each substring. We can get the current substring as `sub = arr[i][l:l+j]`. Then we determine whether `sub` is a substring of other strings. If it is, we skip the current substring; otherwise, we update the answer.\n\nThe time complexity is $O(n^2 \\times m^4)$, and the space complexity is $O(m)$. Where $n$ is the length of the string array `arr`, and $m$ is the maximum length of the string. In this problem, $m \\le 20$." }, "is_english": true, "time_complexity": "O(n^2 \\times m^4)", "space_complexity": "O(m)" }, { "problem_id": 3077, "explanations": { "1": "For the $i$th number $nums[i - 1]$, if it is selected and is in the $j$th subarray, then its contribution to the answer is $nums[i - 1] \\times (k - j + 1) \\times (-1)^{j+1}$. We denote $(-1)^{j+1}$ as $sign$, so its contribution to the answer is $sign \\times nums[i - 1] \\times (k - j + 1)$.\n\nWe define $f[i][j][0]$ as the maximum energy value when selecting $j$ subarrays from the first $i$ numbers, and the $i$th number is not selected. We define $f[i][j][1]$ as the maximum energy value when selecting $j$ subarrays from the first $i$ numbers, and the $i$th number is selected. Initially, $f[0][0][1] = 0$, and the rest of the values are $-\\infty$.\n\nWhen $i > 0$, we consider how $f[i][j]$ transitions.\n\nIf the $i$th number is not selected, then the $i-1$th number can either be selected or not selected, so $f[i][j][0] = \\max(f[i-1][j][0], f[i-1][j][1])$.\n\nIf the $i$th number is selected, if the $i-1$th number and the $i$th number are in the same subarray, then $f[i][j][1] = \\max(f[i][j][1], f[i-1][j][1] + sign \\times nums[i-1] \\times (k - j + 1))$, otherwise $f[i][j][1] = \\max(f[i][j][1], \\max(f[i-1][j-1][0], f[i-1][j-1][1]) + sign \\times nums[i-1] \\times (k - j + 1))$.\n\nThe final answer is $\\max(f[n][k][0], f[n][k][1])$.\n\nThe time complexity is $O(n \\times k)$, and the space complexity is $O(n \\times k)$. Where $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n \\times k)", "space_complexity": "O(n \\times k)" }, { "problem_id": 3078, "explanations": { "1": "Let's denote $m$ and $n$ as the number of rows and columns in the matrix `board`, and $r$ and $c$ as the number of rows and columns in the matrix `pattern`.\n\nWe can enumerate each possible sub-matrix's top-left position $(i, j)$ in the `board` from small to large, and then determine whether the $r \\times c$ sub-matrix with $(i, j)$ as the top-left corner matches `pattern`. If we find a matching sub-matrix, we return $(i, j)$. Otherwise, we return $(-1, -1)$.\n\nThe time complexity is $O(m \\times n \\times r \\times c)$, where $m$ and $n$ are the number of rows and columns in the matrix `board`, and $r$ and $c$ are the number of rows and columns in the matrix `pattern`. The space complexity is $O(|\\Sigma|)$, where $\\Sigma$ is the character set. In this problem, $\\Sigma$ includes numbers and lowercase letters, so $|\\Sigma| \\leq 36$." }, "is_english": true, "time_complexity": "O(m \\times n \\times r \\times c)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 3079, "explanations": { "1": "We directly simulate the encryption process by defining a function $encrypt(x)$, which replaces each digit in an integer $x$ with the maximum digit in $x$. The implementation of the function is as follows:\n\nWe can obtain each digit of $x$ by continuously taking the modulus and integer division of $x$ by $10$, and find the maximum digit, denoted as $mx$. During the loop, we can also use a variable $p$ to record the base number of $mx$, i.e., $p = 1, 11, 111, \\cdots$. Finally, return $mx \\times p$.\n\nThe time complexity is $O(n \\times \\log M)$, where $n$ is the length of the array, and $M$ is the maximum value in the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(1)" }, { "problem_id": 3080, "explanations": { "1": "First, we calculate the sum $s$ of the array $nums$. We define an array $mark$ to indicate whether the elements in the array have been marked, initializing all elements as unmarked.\n\nThen, we create an array $arr$, where each element is a tuple $(x, i)$, indicating that the $i$-th element in the array has a value of $x$. We sort the array $arr$ by the value of the elements. If the values are equal, we sort them in ascending order of the index.\n\nNext, we traverse the array $queries$. For each query $[index, k]$, we first check whether the element at index $index$ has been marked. If it has not been marked, we mark it and subtract the value of the element at index $index$ from $s$. Then, we traverse the array $arr$. For each element $(x, i)$, if element $i$ has not been marked, we mark it and subtract the value $x$ corresponding to element $i$ from $s$, until $k$ is $0$ or the array $arr$ is fully traversed. Then, we add $s$ to the answer array.\n\nAfter traversing all the queries, we get the answer array.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3081, "explanations": { "1": "According to the problem, we can find that if a letter $c$ appears $v$ times, then the score it contributes to the answer is $1 + 2 + \\cdots + (v - 1) = \\frac{v \\times (v - 1)}{2}$. To make the answer as small as possible, we should replace the question marks with those letters that appear less frequently.\n\nTherefore, we can use a priority queue to maintain the occurrence times of each letter, take out the letter with the least occurrence times each time, record it in the array $t$, then increase its occurrence times by one, and put it back into the priority queue. Finally, we sort the array $t$, and then traverse the string $s$, replacing each question mark with the letters in the array $t$ in turn.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3082, "explanations": { "1": "The problem requires us to find all subsequences $\\textit{S}$ in the given array $\\textit{nums}$, and then calculate the number of ways for each subsequence $\\textit{T}$ such that the sum of $\\textit{T}$ equals $\\textit{k}$.\n\nWe define $f[i][j]$ to represent the number of ways to form subsequences with the first $i$ numbers such that the sum of each subsequence equals $j$. Initially, $f[0][0] = 1$, and all other positions are $0$.\n\nFor the $i$-th number $x$, there are three cases:\n\n1. Not in the subsequence $\\textit{S}$, in which case $f[i][j] = f[i-1][j]$;\n2. In the subsequence $\\textit{S}$, but not in the subsequence $\\textit{T}$, in which case $f[i][j] = f[i-1][j]$;\n3. In the subsequence $\\textit{S}$, and in the subsequence $\\textit{T}$, in which case $f[i][j] = f[i-1][j-x]$.\n\nIn summary, the state transition equation is:\n\n$$\nf[i][j] = f[i-1][j] \\times 2 + f[i-1][j-x]\n$$\n\nThe final answer is $f[n][k]$.\n\nThe time complexity is $O(n \\times k)$, and the space complexity is $O(n \\times k)$. Here, $n$ is the length of the array $\\textit{nums}$, and $k$ is the given positive integer.", "2": "In the state transition equation from Solution 1, the value of $f[i][j]$ only depends on $f[i-1][j]$ and $f[i-1][j-x]$. Therefore, we can optimize the first dimension of the space, reducing the space complexity to $O(k)$.\n\nTime complexity is $O(n \\times k)$, and space complexity is $O(k)$. Here, $n$ is the length of the array $\\textit{nums}$, and $k$ is the given positive integer." }, "is_english": true, "time_complexity": "O(n \\times k)", "space_complexity": "O(n \\times k)" }, { "problem_id": 3083, "explanations": { "1": "We can use a hash table or a two-dimensional array $st$ to store all substrings of length $2$ of the reversed string $s$.\n\nThen we traverse the string $s$. For each substring of length $2$, we check whether it has appeared in $st$. If it has, we return `true`. Otherwise, we return `false` after the traversal.\n\nThe time complexity is $O(n)$ and the space complexity is $O(|\\Sigma|^2)$. Here, $n$ is the length of the string $s$, and $\\Sigma$ is the character set of the string $s$. In this problem, $\\Sigma$ consists of lowercase English letters, so $|\\Sigma| = 26$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(|\\Sigma|^2)" }, { "problem_id": 3084, "explanations": { "1": "First, we can count the number of character $c$ in string $s$, denoted as $cnt$.\n\nEach character $c$ can form a substring on its own, so there are $cnt$ substrings that meet the condition. Each character $c$ can form a substring with other $c$ characters, so there are $\\frac{cnt \\times (cnt - 1)}{2}$ substrings that meet the condition.\n\nTherefore, the answer is $cnt + \\frac{cnt \\times (cnt - 1)}{2}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3085, "explanations": { "1": "First, we can count the occurrence of each character in the string and put all the counts into an array $nums$. Since the string only contains lowercase letters, the length of the array $nums$ will not exceed $26$.\n\nNext, we can enumerate the minimum frequency $v$ of characters in the $K$ special strings within the range $[0,..n]$, and then use a function $f(v)$ to calculate the minimum number of deletions to adjust the frequency of all characters to $v$. The minimum value of all $f(v)$ is the answer.\n\nThe calculation method of function $f(v)$ is as follows:\n\nTraverse each element $x$ in the array $nums$. If $x < v$, it means that we need to delete all characters with a frequency of $x$, and the number of deletions is $x$. If $x > v + k$, it means that we need to adjust all characters with a frequency of $x$ to $v + k$, and the number of deletions is $x - v - k$. The sum of all deletion counts is the value of $f(v)$.\n\nThe time complexity is $O(n \\times |\\Sigma|)$, and the space complexity is $O(|\\Sigma|)$. Here, $n$ is the length of the string, and $|\\Sigma|$ is the size of the character set. In this problem, $|\\Sigma| = 26$." }, "is_english": true, "time_complexity": "O(n \\times |\\Sigma|)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 3086, "explanations": { "1": "We consider enumerating Alice's standing position $i$. For each $i$, we follow the strategy below:\n\n- First, if the number at position $i$ is $1$, we can directly pick up a $1$ without needing any moves.\n- Then, we pick up the number $1$ from both sides of position $i$, which is action $2$, i.e., move the $1$ from position $i-1$ to position $i$, then pick it up; move the $1$ from position $i+1$ to position $i$, then pick it up. Each pick up of a $1$ requires $1$ move.\n- Next, we maximize the conversion of $0$s at positions $i-1$ or $i+1$ to $1$s using action $1$, then move them to position $i$ using action $2$ to pick them up. This continues until the number of $1$s picked up reaches $k$ or the number of times action $1$ is used reaches $\\textit{maxChanges}$. Assuming the number of times action $1$ is used is $c$, then a total of $2c$ moves are needed.\n- After utilizing action $1$, if the number of $1$s picked up has not reached $k$, we need to continue considering moving $1$s to position $i$ from the intervals $[1,..i-2]$ and $[i+2,..n]$ using action $2$ to pick them up. We can use binary search to determine the size of this interval so that the number of $1$s picked up reaches $k$. Specifically, we binary search for an interval size $d$, then within the intervals $[i-d,..i-2]$ and $[i+2,..i+d]$, we perform action $2$ to move $1$s to position $i$ for pickup. If the number of $1$s picked up reaches $k$, we update the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3087, "explanations": { "1": "We can query all tweets from February 2024, use the `SUBSTRING_INDEX` function to extract Hashtags, then use the `GROUP BY` and `COUNT` functions to count the occurrences of each Hashtag. Finally, we sort by the number of occurrences in descending order and by Hashtag in descending order, and take the top three popular Hashtags." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3088, "explanations": { "1": "The problem asks us to transform the string $s$ into the lexicographically smallest non-palindrome string. We might as well sort the string $s$ first.\n\nNext, we only need to compare whether the two middle characters $s[m]$ and $s[m-1]$ are equal. If they are equal, we find the first character $s[i]$ in the second half that is not equal to $s[m]$, use a pointer $j$ to point to $m$, and then swap $s[i]$ and $s[j]$. If we can't find such a character $s[i]$, it means that the string $s$ cannot be transformed into a non-palindrome string, return `\"1\"`. Otherwise, perform the swap operation, move $i$ and $j$ to the right, compare whether $s[j]$ and $s[n-j-1]$ are equal, if they are equal, continue to perform the swap operation until $i$ exceeds the length of the string.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3089, "explanations": { "1": "We can use self-join to connect the `Posts` table with itself. The connection condition is `p1.user_id = p2.user_id` and `p2.post_date` is between `p1.post_date` and 6 days after `p1.post_date`. Then we group the connection results by `p1.user_id` and `p1.post_id` to count the number of posts for each user within 7 days of each day. We save this result in table `P`.\n\nNext, we count the average number of posts per week for each user in February 2024 and save it in table `T`. Note that we need to find records where `post_date` is between `2024-02-01` and `2024-02-28`, group the records by `user_id`, then count the number of posts for each user, and finally divide by `4` to get the average number of posts per week. We save this result in table `T`.\n\nFinally, we connect tables `P` and `T` with the condition `P.user_id = T.user_id`, then group by `user_id` to count the maximum number of posts within 7 days for each user. We then filter out records that meet the condition `max_7day_posts >= avg_weekly_posts * 2` to get the result. Note that we need to sort in ascending order by `user_id`." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3090, "explanations": { "1": "We use two pointers $i$ and $j$ to maintain a sliding window, and an array $cnt$ to record the occurrence times of each character in the window.\n\nIn each iteration, we add the character $c$ at the pointer $j$ into the window, then check if $cnt[c]$ is greater than $2$. If it is, we move the pointer $i$ to the right until $cnt[c]$ is less than or equal to $2$. At this point, we update the answer $ans = \\max(ans, j - i + 1)$.\n\nFinally, we return the answer $ans$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(|\\Sigma|)$, where $\\Sigma$ is the character set, and in this problem, $\\Sigma = 26$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 3091, "explanations": { "1": "We should put the copy operation (i.e., operation $2$) at the end to reduce the number of operations.\n\nTherefore, we enumerate the number of times $a$ for operation $1$ in the range $[0, k]$, then the number of times $b$ for operation $2$ is $\\left\\lceil \\frac{k}{a+1} \\right\\rceil - 1$. We take the minimum of $a+b$.\n\nThe time complexity is $O(k)$, where $k$ is the input positive integer $k$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(k)", "space_complexity": "O(1)" }, { "problem_id": 3092, "explanations": { "1": "We use a hash table $cnt$ to record the occurrence times of each ID, a hash table $lazy$ to record the number of times each occurrence needs to be deleted, and a priority queue $pq$ to maintain the maximum occurrence times.\n\nFor each operation $(x, f)$, we need to update the occurrence times $cnt[x]$ of $x$, which means the value of $cnt[x]$ in $lazy$ needs to increase by $1$, indicating that the number of times this occurrence needs to be deleted increases by $1$. Then we update the value of $cnt[x]$, adding $f$ to $cnt[x]$. Then we add the updated value of $cnt[x]$ to the priority queue $pq$. Then we check the top element of the priority queue $pq$. If the number of times the corresponding occurrence needs to be deleted in $lazy$ is greater than $0$, we pop the top element. Finally, we judge whether the priority queue is empty. If it is not empty, the top element is the maximum occurrence times, and we add it to the answer array.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3093, "explanations": { "1": "The problem requires us to find the longest common suffix, so we can consider using a Trie.\n\nWe define the structure of the Trie node as follows:\n\n- `children`: An array of length 26, used to store child nodes.\n- `length`: The length of the shortest string at the current node.\n- `idx`: The index of the string at the current node.\n\nWe traverse the string array `wordsContainer`, and insert each string in reverse order into the Trie. During the insertion process, we update the `length` and `idx` of each node.\n\nNext, we traverse the string array `wordsQuery`. For each string, we search for the index of the longest common suffix string from the Trie. During the search process, if we encounter a null node, it means that there is no common suffix afterwards, and we can directly return the `idx` of the current node.\n\nThe time complexity is $(L_1 \\times |\\Sigma| + L_2)$, and the space complexity is $O(L_1 \\times |\\Sigma|)$. Here, $L_1$ and $L_2$ are the sum of the lengths of the strings in `wordsContainer` and `wordsQuery` respectively; and $\\Sigma$ is the size of the character set, in this problem $\\Sigma = 26$." }, "is_english": true, "time_complexity": "O(L_1 \\times |\\Sigma|)", "space_complexity": "O(L_1 \\times |\\Sigma|)" }, { "problem_id": 3094, "explanations": { "1": "Based on the problem description, we observe that:\n\n- If we call the `commonBits` function twice with the same number, the value of $n$ will not change.\n- If we call `commonBits(1 << i)`, the $i$-th bit of $n$ will be flipped, i.e., if the $i$-th bit of $n$ is $1$, it will become $0$ after the call, and vice versa.\n\nTherefore, for each bit $i$, we can call `commonBits(1 << i)` twice, denoted as `count1` and `count2` respectively. If `count1 > count2`, it means the $i$-th bit of $n$ is $1$, otherwise it is $0$.\n\nThe time complexity is $O(\\log n)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 3095, "explanations": { "1": "We can observe that if we fix the left endpoint of the subarray, as the right endpoint moves to the right, the bitwise OR value of the subarray will only increase, not decrease. Therefore, we can use the double pointers method to maintain a subarray that meets the conditions.\n\nSpecifically, we use two pointers $i$ and $j$ to represent the left and right endpoints of the subarray, respectively. Initially, both pointers are at the first element of the array. We use a variable $s$ to represent the bitwise OR value of the subarray, and initially, the value of $s$ is $0$. We also need to maintain an array $cnt$ of length $32$, which represents the occurrence times of each bit in the binary representation of each element in the subarray.\n\nIn each step, we move $j$ to the right by one position, and update $s$ and $cnt$. If the value of $s$ is greater than or equal to $k$, we continuously update the minimum length of the subarray and move $i$ to the right by one position until the value of $s$ is less than $k$. In this process, we also need to update $s$ and $cnt$.\n\nFinally, we return the minimum length. If there is no subarray that meets the conditions, we return $-1$.\n\nThe time complexity is $O(n \\times \\log M)$ and the space complexity is $O(\\log M)$, where $n$ and $M$ are the length of the array and the maximum value of the elements in the array, respectively." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(\\log M)" }, { "problem_id": 3096, "explanations": { "1": "First, we calculate the sum of the scores that both players can get, denoted as $s$.\n\nThen, we enumerate the number of levels that player 1 can complete, denoted as $i$, in ascending order. We calculate the sum of the scores that player 1 gets, denoted as $t$. If $t > s - t$, then the number of levels that player 1 needs to complete is $i$.\n\nIf we have enumerated the first $n - 1$ levels and have not found a satisfying $i$, then we return $-1$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3097, "explanations": { "1": "We can observe that if we fix the left endpoint of the subarray, as the right endpoint moves to the right, the bitwise OR value of the subarray will only increase, not decrease. Therefore, we can use the double pointers method to maintain a subarray that meets the conditions.\n\nSpecifically, we use two pointers $i$ and $j$ to represent the left and right endpoints of the subarray, respectively. Initially, both pointers are at the first element of the array. We use a variable $s$ to represent the bitwise OR value of the subarray, and initially, the value of $s$ is $0$. We also need to maintain an array $cnt$ of length $32$, which represents the occurrence times of each bit in the binary representation of each element in the subarray.\n\nIn each step, we move $j$ to the right by one position, and update $s$ and $cnt$. If the value of $s$ is greater than or equal to $k$, we continuously update the minimum length of the subarray and move $i$ to the right by one position until the value of $s$ is less than $k$. In this process, we also need to update $s$ and $cnt$.\n\nFinally, we return the minimum length. If there is no subarray that meets the conditions, we return $-1$.\n\nThe time complexity is $O(n \\times \\log M)$ and the space complexity is $O(\\log M)$, where $n$ and $M$ are the length of the array and the maximum value of the elements in the array, respectively.\n\nSimilar Problems:\n\n- [3171. Find Subarray With Bitwise AND Closest to K](https://github.com/doocs/leetcode/blob/main/solution/3100-3199/3171.Find%20Subarray%20With%20Bitwise%20AND%20Closest%20to%20K/README_EN.md)" }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(\\log M)" }, { "problem_id": 3098, "explanations": { "1": "Given the problem involves the minimum difference between elements of a subsequence, we might as well sort the array $\\textit{nums}$, which facilitates the calculation of the minimum difference between subsequence elements.\n\nNext, we design a function $dfs(i, j, k, mi)$, representing the value of the energy sum when processing the $i$-th element, the last selected element is the $j$-th element, $k$ more elements need to be selected, and the current minimum difference is $mi$. Therefore, the answer is $dfs(0, n, k, +\\infty)$ (If the last selected element is the $n$-th element, it indicates that no element has been selected before).\n\nThe execution process of the function $dfs(i, j, k, mi)$ is as follows:\n\n- If $i \\geq n$, it means all elements have been processed. If $k = 0$, return $mi$; otherwise, return $0$.\n- If the remaining number of elements $n - i$ is less than $k$, return $0$.\n- Otherwise, we can choose not to select the $i$-th element, and the energy sum obtained is $dfs(i + 1, j, k, mi)$.\n- We can also choose to select the $i$-th element. If $j = n$, it means no element has been selected before, then the energy sum obtained is $dfs(i + 1, i, k - 1, mi)$; otherwise, the energy sum obtained is $dfs(i + 1, i, k - 1, \\min(mi, \\textit{nums}[i] - \\textit{nums}[j]))$.\n- We add up the above results and return the result modulo $10^9 + 7$.\n\nTo avoid repeated calculations, we can use memoization, saving the results that have already been calculated.\n\nThe time complexity is $O(n^4 \\times k)$, and the space complexity is $O(n^4 \\times k)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n^4 \\times k)", "space_complexity": "O(n^4 \\times k)" }, { "problem_id": 3099, "explanations": { "1": "We can calculate the sum of the digits of $x$, denoted as $s$, by simulation. If $x$ can be divided evenly by $s$, then we return $s$, otherwise, we return $-1$.\n\nThe time complexity is $O(\\log x)$, where $x$ is the input integer. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log x)", "space_complexity": "O(1)" }, { "problem_id": 3100, "explanations": { "1": "We can drink all the full water bottles at the beginning, so initially the amount of water we drink is $\\textit{numBottles}$. Then, we repeatedly perform the following operations:\n\n- If we currently have $\\textit{numExchange}$ empty bottles, we can exchange them for one full bottle. After the exchange, the value of $\\textit{numExchange}$ increases by $1$. Then, we drink this bottle, increasing the total amount of water drunk by $1$, and the number of empty bottles increases by $1$.\n- If we do not have $\\textit{numExchange}$ empty bottles, we cannot exchange for more water and should stop.\n\nWe repeat the above process until we can no longer exchange bottles. The total amount of water drunk is the answer.\n\nThe time complexity is $O(\\sqrt{n})$, where $n$ is the initial number of full bottles. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\sqrt{n})", "space_complexity": "O(1)" }, { "problem_id": 3101, "explanations": { "1": "We can enumerate the subarrays ending at each position, calculate the number of subarrays that meet the conditions, and sum up the number of subarrays that meet the conditions at all positions.\n\nSpecifically, we define a variable $s$ to represent the number of subarrays that meet the conditions and end with the element $nums[i]$. Initially, we set $s$ to $1$, which means the number of subarrays that meet the conditions and end with the first element is $1$.\n\nNext, we start to traverse the array from the second element. For each position $i$, we update the value of $s$ based on the relationship between $nums[i]$ and $nums[i-1]$:\n\n- If $nums[i] \\neq nums[i-1]$, the value of $s$ increases by $1$, that is, $s = s + 1$;\n- If $nums[i] = nums[i-1]$, the value of $s$ is reset to $1$, that is, $s = 1$.\n\nThen, we add the value of $s$ to the answer and continue to traverse the next position of the array until the entire array is traversed.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3102, "explanations": { "1": "For two points $(x_1, y_1)$ and $(x_2, y_2)$, their Manhattan distance is $|x_1 - x_2| + |y_1 - y_2|$. We can transform it into $\\max(x_1 - x_2, x_2 - x_1) + \\max(y_1 - y_2, y_2 - y_1)$, which is:\n\n$$\n|x_1 - x_2| + |y_1 - y_2| = \\max \\begin{cases}\nx_1 - x_2 + y_1 - y_2 \\\\\nx_2 - x_1 + y_2 - y_1 \\\\\nx_1 - x_2 + y_2 - y_1 \\\\\nx_2 - x_1 + y_1 - y_2\n\\end{cases}\n$$\n\nThis can be simplified to:\n\n$$\n|x_1 - x_2| + |y_1 - y_2| = \\max \\begin{cases}\n(x_1 + y_1) - (x_2 + y_2) \\\\\n(x_2 + y_2) - (x_1 + y_1) \\\\\n(x_1 - y_1) - (x_2 - y_2) \\\\\n(x_2 - y_2) - (x_1 - y_1)\n\\end{cases}\n$$\n\nHere, the first two cases can be represented as $\\max(\\max(x_1 + y_1, x_2 + y_2) - \\min(x_1 + y_1, x_2 + y_2))$, and the last two cases can be represented as $\\max(\\max(x_1 - y_1, x_2 - y_2) - \\min(x_1 - y_1, x_2 - y_2))$.\n\nTherefore, we can store all points according to the values of $x + y$ and $x - y$ in two ordered sets, respectively. Then, for each point, we remove it, update the values in the ordered sets, calculate the difference between the maximum and minimum values, and take the minimum value.\n\nThe time complexity is $O(n \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the number of points." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3103, "explanations": { "1": "We can use regular expressions to match all tags in each tweet, and then count the occurrence of each tag. Finally, we can sort the tags in descending order by the number of occurrences. If the number of occurrences is the same, we sort them in descending order by the tag name, and return the top three tags." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3104, "explanations": { "1": "We notice that the start of a substring that meets the conditions must be the position where a character appears for the first time.\n\nTherefore, we can use two arrays or hash tables `first` and `last` to record the positions where each character appears for the first time and the last time, respectively.\n\nNext, we enumerate each character `c`. Suppose the position where `c` first appears is $i$, and the position where it last appears is $mx$. Then we can start traversing from $i$. For each position $j$, we find the position $a$ where $s[j]$ first appears and the position $b$ where it last appears. If $a < i$, it means that $s[j]$ is on the left of $c$, which does not meet the enumeration conditions, and we can exit the loop directly. Otherwise, we update $mx = \\max(mx, b)$. If $mx = j$ and $j - i + 1 < n$, we update the answer to $ans = \\max(ans, j - i + 1)$.\n\nFinally, return the answer.\n\nThe time complexity is $O(n \\times |\\Sigma|)$, and the space complexity is $O(|\\Sigma|)$. Where $n$ is the length of the string $s$; and $|\\Sigma|$ is the size of the character set. In this problem, the character set is lowercase letters, so $|\\Sigma| = 26$." }, "is_english": true, "time_complexity": "O(n \\times |\\Sigma|)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 3105, "explanations": { "1": "We first perform a pass to find the length of the longest strictly increasing subarray, and update the answer. Then we perform another pass to find the length of the longest strictly decreasing subarray, and update the answer again.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3106, "explanations": { "1": "We can traverse each position of the string $s$. For each position, we enumerate all characters less than the current character, calculate the cost $d$ to change to this character. If $d \\leq k$, we change the current character to this character, subtract $d$ from $k$, end the enumeration, and continue to the next position.\n\nAfter the traversal, we get a string that meets the conditions.\n\nThe time complexity is $O(n \\times |\\Sigma|)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $s$, and $|\\Sigma|$ is the size of the character set. In this problem, $|\\Sigma| \\leq 26$." }, "is_english": true, "time_complexity": "O(n \\times |\\Sigma|)", "space_complexity": "O(n)" }, { "problem_id": 3107, "explanations": { "1": "First, we sort the array $nums$ and find the position $m$ of the median. The initial number of operations we need is $|nums[m] - k|$.\n\nNext, we discuss in two cases:\n\n- If $nums[m] > k$, then all elements to the right of $m$ are greater than or equal to $k$. We only need to reduce the elements greater than $k$ on the left of $m$ to $k$.\n- If $nums[m] \\le k$, then all elements to the left of $m$ are less than or equal to $k$. We only need to increase the elements less than $k$ on the right of $m$ to $k$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 3108, "explanations": { "1": "We note that a positive integer performing bitwise AND operation with several other positive integers will only get smaller. Therefore, to minimize the cost of the journey, we should perform bitwise AND operation on the weights of all edges in the same connected component, and then perform the query.\n\nSo, the problem is transformed into how to find all the edges in the same connected component and perform bitwise AND operation.\n\nWe can use a union-find set to maintain the connected components.\n\nSpecifically, we traverse each edge $(u, v, w)$ and merge $u$ and $v$. Then, we traverse each edge $(u, v, w)$ again, find the root node $root$ of the connected component where $u$ and $v$ are located, and use an array $g$ to record the result of the bitwise AND operation of the weights of all edges in each connected component.\n\nFinally, for each query $(s, t)$, we first judge whether $s$ equals $t$. If they are equal, the answer is $0$. Otherwise, we judge whether $s$ and $t$ are in the same connected component. If they are in the same connected component, the answer is the $g$ value of the root node of the connected component of this query. Otherwise, the answer is $-1$.\n\nThe time complexity is $O((n + m + q) \\times \\alpha(n))$, and the space complexity is $O(n)$. Here, $n$, $m$, and $q$ represent the number of nodes, edges, and queries, respectively, and $\\alpha(n)$ represents the inverse function of the Ackermann function." }, "is_english": true, "time_complexity": "O((n + m + q) \\times \\alpha(n))", "space_complexity": "O(n)" }, { "problem_id": 3109, "explanations": { "1": "According to the problem requirements, we need to find out how many permutations are lexicographically smaller than the given permutation.\n\nWe consider how to calculate the number of permutations that are lexicographically smaller than the given permutation. There are two situations:\n\n- The first element of the permutation is less than $perm[0]$, there are $(perm[0] - 1) \\times (n-1)!$ permutations.\n- The first element of the permutation is equal to $perm[0]$, we need to continue to consider the second element, and so on.\n- The sum of all situations is the answer.\n\nWe can use a binary indexed tree to maintain the number of elements that are smaller than the current element in the traversed elements. For the $i$-th element of the given permutation, the number of remaining elements that are smaller than it is $perm[i] - 1 - tree.query(perm[i])$, and the number of permutation types is $(perm[i] - 1 - tree.query(perm[i])) \\times (n-i-1)!$, which is added to the answer. Then we update the binary indexed tree and add the current element to the binary indexed tree. Continue to traverse the next element until all elements are traversed.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the permutation." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3110, "explanations": { "1": "We directly traverse the string $s$, calculating the sum of the absolute differences of the ASCII codes of adjacent characters.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3111, "explanations": { "1": "According to the problem description, we do not need to consider the height of the rectangles, only the width.\n\nWe can sort all the points by their x-coordinates and use a variable $x_1$ to record the rightmost x-coordinate that the current rectangle can cover. Initially, $x_1 = -1$.\n\nNext, we iterate through all the points. If the current point's x-coordinate $x$ is greater than $x_1$, it means the existing rectangle cannot cover the current point. We need to add a new rectangle, increment the answer by one, and update $x_1 = x + w$.\n\nAfter completing the iteration, we obtain the minimum number of rectangles needed.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the number of points." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 3112, "explanations": { "1": "First, we create an adjacency list $\\textit{g}$ to store the edges of the graph. Then, we create an array $\\textit{dist}$ to store the shortest distances from node $0$ to other nodes. Initialize $\\textit{dist}[0] = 0$, and the distances for the rest of the nodes are initialized to infinity.\n\nNext, we use the Dijkstra algorithm to calculate the shortest distances from node $0$ to other nodes. The specific steps are as follows:\n\n1. Create a priority queue $\\textit{pq}$ to store the distances and node numbers. Initially, add node $0$ to the queue with a distance of $0$.\n2. Remove a node $u$ from the queue. If the distance $du$ of $u$ is greater than $\\textit{dist}[u]$, it means $u$ has already been updated, so we skip it directly.\n3. Iterate through all neighbor nodes $v$ of node $u$. If $\\textit{dist}[v] > \\textit{dist}[u] + w$ and $\\textit{dist}[u] + w < \\textit{disappear}[v]$, then update $\\textit{dist}[v] = \\textit{dist}[u] + w$ and add node $v$ to the queue.\n4. Repeat steps 2 and 3 until the queue is empty.\n\nFinally, we iterate through the $\\textit{dist}$ array. If $\\textit{dist}[i] < \\textit{disappear}[i]$, then $\\textit{answer}[i] = \\textit{dist}[i]$; otherwise, $\\textit{answer}[i] = -1$.\n\nThe time complexity is $O(m \\times \\log m)$, and the space complexity is $O(m)$. Here, $m$ is the number of edges." }, "is_english": true, "time_complexity": "O(m \\times \\log m)", "space_complexity": "O(m)" }, { "problem_id": 3113, "explanations": { "1": "We consider each element $x$ in the array $nums$ as the boundary element and the maximum value of the subarray.\n\nEach subarray of length $1$ meets the condition, and for subarrays with length greater than $1$, all elements in the subarray cannot be greater than the boundary element $x$. We can implement this with a monotonic stack.\n\nWe maintain a stack that decreases monotonically from the bottom to the top. Each element in the monotonic stack is a pair $[x, cnt]$, representing the element $x$ and the count $cnt$ of subarrays with $x$ as the boundary element and the maximum value.\n\nWe traverse the array $nums$ from left to right. For each element $x$, we continuously pop the top element of the stack until the stack is empty or the first element of the top element of the stack is greater than or equal to $x$. If the stack is empty, or the first element of the top element of the stack is greater than $x$, it means that we have encountered the first subarray with $x$ as the boundary element and the maximum value, and the length of this subarray is $1$, so we push $[x, 1]$ into the stack. If the first element of the top element of the stack is equal to $x$, it means that we have encountered a subarray with $x$ as the boundary element and the maximum value, and we add $1$ to the second element of the top element of the stack. Then, we add the second element of the top element of the stack to the answer.\n\nAfter the traversal, we return the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3114, "explanations": { "1": "We can enumerate all times from large to small, where the hour $h$ ranges from $11$ to $0$, and the minute $m$ ranges from $59$ to $0$. For each time $t$, we check whether each digit of $t$ matches the corresponding digit in $s$ (if the corresponding digit in $s$ is not \"?\"). If it does, then we have found the answer and return $t$.\n\nThe time complexity is $O(h \\times m)$, where $h = 12$ and $m = 60$. The space complexity is $O(1)$.", "2": "We can judge each digit of $s$ one by one. If it is \"?\", we determine the value of this digit based on the characters before and after it. Specifically, we have the following rules:\n\n- If $s[0]$ is \"?\", then the value of $s[0]$ should be \"1\" or \"0\", depending on the value of $s[1]$. If $s[1]$ is \"?\" or $s[1]$ is less than \"2\", then the value of $s[0]$ should be \"1\", otherwise the value of $s[0]$ should be \"0\".\n- If $s[1]$ is \"?\", then the value of $s[1]$ should be \"1\" or \"9\", depending on the value of $s[0]$. If $s[0]$ is \"1\", then the value of $s[1]$ should be \"1\", otherwise the value of $s[1]$ should be \"9\".\n- If $s[3]$ is \"?\", then the value of $s[3]$ should be \"5\".\n- If $s[4]$ is \"?\", then the value of $s[4]$ should be \"9\".\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(h \\times m)", "space_complexity": "O(1)" }, { "problem_id": 3115, "explanations": { "1": "According to the problem description, we need to find the index $i$ of the first prime number, then find the index $j$ of the last prime number, and return $j - i$ as the answer.\n\nTherefore, we can traverse the array from left to right to find the index $i$ of the first prime number, then traverse the array from right to left to find the index $j$ of the last prime number. The answer is $j - i$.\n\nThe time complexity is $O(n \\times \\sqrt{M})$, where $n$ and $M$ are the length of the array $nums$ and the maximum value in the array, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\sqrt{M})", "space_complexity": "O(1)" }, { "problem_id": 3116, "explanations": { "1": "We can transform the problem into: find the smallest positive integer $x$ such that the number of numbers less than or equal to $x$ and satisfying the condition is exactly $k$. If $x$ satisfies the condition, then for any $x' > x$, $x'$ also satisfies the condition. This shows monotonicity, so we can use binary search to find the smallest $x$ that satisfies the condition.\n\nWe define a function `check(x)` to determine whether the number of numbers less than or equal to $x$ and satisfying the condition is greater than or equal to $k$. We need to calculate how many numbers can be obtained from the array $coins$.\n\nSuppose $coins = [a, b]$, according to the inclusion-exclusion principle, the number of numbers less than or equal to $x$ and satisfying the condition is:\n\n$$\n\\left\\lfloor \\frac{x}{a} \\right\\rfloor + \\left\\lfloor \\frac{x}{b} \\right\\rfloor - \\left\\lfloor \\frac{x}{lcm(a, b)} \\right\\rfloor\n$$\n\nIf $coins = [a, b, c]$, the number of numbers less than or equal to $x$ and satisfying the condition is:\n\n$$\n\\left\\lfloor \\frac{x}{a} \\right\\rfloor + \\left\\lfloor \\frac{x}{b} \\right\\rfloor + \\left\\lfloor \\frac{x}{c} \\right\\rfloor - \\left\\lfloor \\frac{x}{lcm(a, b)} \\right\\rfloor - \\left\\lfloor \\frac{x}{lcm(a, c)} \\right\\rfloor - \\left\\lfloor \\frac{x}{lcm(b, c)} \\right\\rfloor + \\left\\lfloor \\frac{x}{lcm(a, b, c)} \\right\\rfloor\n$$\n\nAs you can see, we need to add all cases with an odd number of elements and subtract all cases with an even number of elements.\n\nSince $n \\leq 15$, we can use binary enumeration to enumerate all subsets and calculate the number of numbers that satisfy the condition, denoted as $cnt$. If $cnt \\geq k$, then we need to find the smallest $x$ such that `check(x)` is true.\n\nAt the start of the binary search, we define the left boundary $l=1$ and the right boundary $r={10}^{11}$. Then we continuously substitute the middle value $mid$ into the `check` function. If `check(mid)` is true, then we update the right boundary $r$ to $mid$, otherwise we update the left boundary $l$ to $mid+1$. Finally, we return $l$.\n\nThe time complexity is $O(n \\times 2^n \\times \\log (k \\times M))$, where $n$ is the length of the array $coins$, and $M$ is the maximum value in the array." }, "is_english": true, "time_complexity": "O(n \\times 2^n \\times \\log (k \\times M))", "space_complexity": null }, { "problem_id": 3117, "explanations": { "1": "We design a function $dfs(i, j, a)$, which represents the possible minimum sum of subarray values that can be obtained starting from the $i$-th element, with $j$ subarrays already divided, and the bitwise AND result of the current subarray to be divided is $a$. The answer is $dfs(0, 0, -1)$.\n\nThe execution process of the function $dfs(i, j, a)$ is as follows:\n\n- If $n - i < m - j$, it means that the remaining elements are not enough to divide into $m - j$ subarrays, return $+\\infty$.\n- If $j = m$, it means that $m$ subarrays have been divided. At this time, check whether $i = n$ holds. If it holds, return $0$, otherwise return $+\\infty$.\n- Otherwise, we perform a bitwise AND operation on $a$ and $nums[i]$ to get a new $a$. If $a < andValues[j]$, it means that the bitwise AND result of the current subarray to be divided does not meet the requirements, return $+\\infty$. Otherwise, we have two choices:\n - Do not divide the current element, i.e., $dfs(i + 1, j, a)$.\n - Divide the current element, i.e., $dfs(i + 1, j + 1, -1) + nums[i]$.\n- Return the minimum of the above two choices.\n\nTo avoid repeated calculations, we use the method of memoization search and store the result of $dfs(i, j, a)$ in a hash table.\n\nThe time complexity is $O(n \\times m \\times \\log M)$, and the space complexity is $O(n \\times m \\times \\log M)$. Where $n$ and $m$ are the lengths of the arrays $nums$ and $andValues$ respectively; and $M$ is the maximum value in the array $nums$, in this problem $M \\leq 10^5$." }, "is_english": true, "time_complexity": "O(n \\times m \\times \\log M)", "space_complexity": "O(n \\times m \\times \\log M)" }, { "problem_id": 3118, "explanations": { "1": "First, we create a recursive table `T` that includes a `week_of_month` column, representing the week of the month. Then we create a table `M` that includes a `membership` column, representing the type of membership, with values `'Premium'` and `'VIP'`.\n\nNext, we create a table `P` that includes `week_of_month`, `membership`, and `amount_spend` columns, filtering out the amount spent by each member on Fridays of each week of the month. Finally, we join tables `T` and `M`, then left join table `P`, and group by `week_of_month` and `membership` columns to calculate the total spending of each type of member each week." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3119, "explanations": { "1": "First, we count the number of each continuous pothole, recorded in the array $cnt$, i.e., $cnt[k]$ represents there are $cnt[k]$ continuous potholes of length $k$.\n\nSince we want to repair as many potholes as possible, and for a continuous pothole of length $k$, we need to spend a cost of $k + 1$, we should prioritize repairing longer potholes to minimize the cost.\n\nTherefore, we start repairing from the longest pothole. For a pothole of length $k$, the maximum number we can repair is $t = \\min(\\textit{budget} / (k + 1), \\textit{cnt}[k])$. We add the number of repairs multiplied by the length $k$ to the answer, then update the remaining budget. For the remaining $cnt[k] - t$ potholes of length $k$, we merge them into the potholes of length $k - 1$. Continue this process until all potholes are traversed.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the string $road$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3120, "explanations": { "1": "We use a hash table or array $s$ to record the characters that appear in the string $word$. Then we traverse the 26 letters. If both the lowercase and uppercase letters appear in $s$, the count of special characters is incremented by one.\n\nFinally, return the count of special characters.\n\nThe time complexity is $O(n + |\\Sigma|)$, and the space complexity is $O(|\\Sigma|)$. Where $n$ is the length of the string $word$, and $|\\Sigma|$ is the size of the character set. In this problem, $|\\Sigma| \\leq 128$." }, "is_english": true, "time_complexity": "O(n + |\\Sigma|)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 3121, "explanations": { "1": "We define two hash tables or arrays `first` and `last` to store the positions where each letter first appears and last appears respectively.\n\nThen we traverse the string `word`, updating `first` and `last`.\n\nFinally, we traverse all lowercase and uppercase letters. If `last[a]` exists and `first[b]` exists and `last[a] < first[b]`, it means that the letter `a` is a special letter, and we increment the answer by one.\n\nThe time complexity is $O(n + |\\Sigma|)$, and the space complexity is $O(|\\Sigma|)$. Where $n$ is the length of the string `word`, and $|\\Sigma|$ is the size of the character set. In this problem, $|\\Sigma| \\leq 128$." }, "is_english": true, "time_complexity": "O(n + |\\Sigma|)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 3122, "explanations": { "1": "We notice that the values in the cells of the matrix only have 10 possibilities. The problem requires us to find the minimum number of operations for each column to have the same number, and the numbers in adjacent columns are different. Therefore, we only need to consider the case of modifying the number to 0 to 9.\n\nWe define the state $f[i][j]$ to represent the minimum number of operations for the numbers in the first $[0,..i]$ columns, and the number in the $i$-th column is $j$. Then we can get the state transition equation:\n\n$$\nf[i][j] = \\min_{k \\neq j} (f[i-1][k] + m - \\textit{cnt}[j])\n$$\n\nWhere $\\textit{cnt}[j]$ represents the number of cells in the $i$-th column that are $j$.\n\nFinally, we only need to find the minimum value of $f[n-1][j]$.\n\nThe time complexity is $O(n \\times (m + C^2))$, and the space complexity is $O(n \\times C)$. Where $m$ and $n$ represent the number of rows and columns in the matrix respectively; and $C$ represents the number of types of numbers, here $C = 10$." }, "is_english": true, "time_complexity": "O(n \\times (m + C^2))", "space_complexity": "O(n \\times C)" }, { "problem_id": 3123, "explanations": { "1": "First, we create an adjacency list $g$ to store the edges of the graph. Then we create an array $dist$ to store the shortest distance from node $0$ to other nodes. We initialize $dist[0] = 0$, and the distance of other nodes is initialized to infinity.\n\nThen, we use the Dijkstra algorithm to calculate the shortest distance from node $0$ to other nodes. The specific steps are as follows:\n\n1. Create a priority queue $q$ to store the distance and node number of the nodes. Initially, add node $0$ to the queue with a distance of $0$.\n2. Take a node $a$ from the queue. If the distance $da$ of $a$ is greater than $dist[a]$, it means that $a$ has been updated, so skip it directly.\n3. Traverse all neighbor nodes $b$ of node $a$. If $dist[b] > dist[a] + w$, update $dist[b] = dist[a] + w$, and add node $b$ to the queue.\n4. Repeat steps 2 and 3 until the queue is empty.\n\nNext, we create an answer array $ans$ of length $m$, initially all elements are $false$. If $dist[n - 1]$ is infinity, it means that node $0$ cannot reach node $n - 1$, return $ans$ directly. Otherwise, we start from node $n - 1$, traverse all edges, if the edge $(a, b, i)$ satisfies $dist[a] = dist[b] + w$, set $ans[i]$ to $true$, and add node $b$ to the queue.\n\nFinally, return the answer.\n\nThe time complexity is $O(m \\times \\log m)$, and the space complexity is $O(n + m)$, where $n$ and $m$ are the number of nodes and edges respectively." }, "is_english": true, "time_complexity": "O(m \\times \\log m)", "space_complexity": "O(n + m)" }, { "problem_id": 3124, "explanations": { "1": "We can use equi-join to connect the two tables, and then use the window function `RANK()` to calculate the ranking of each type of phone. Finally, we just need to filter out the top three phones." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3125, "explanations": { "1": "We can find the highest bit of $1$ in the binary representation of $n$. The maximum $x$ must be less than $n$ and this bit is $0$, and all other lower bits are $1$, i.e., $x = 2^{\\textit{number of the highest bit}} - 1$. This is because $x \\textit{ and } (x + 1) = 0$ must hold.\n\nThe time complexity is $O(\\log n)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 3126, "explanations": { "1": "We can use the window function `LEAD` to get the time of the next status for each server. The time difference between two statuses is the running time of the server. Finally, we add up the running time of all servers, then divide by the number of seconds in a day to get the total running days of the servers." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3127, "explanations": { "1": "We can enumerate each $2 \\times 2$ square, count the number of black and white cells. If the counts are not equal, then we can construct a square of the same color, and return `true`.\n\nOtherwise, return `false` after the traversal.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 3128, "explanations": { "1": "First, we can count the number of $1$s in each row and each column, and record them in the arrays $rows$ and $cols$.\n\nThen, we enumerate each $1$. Suppose the current $1$ is in the $i$-th row and the $j$-th column. If we take this $1$ as the right angle of a right triangle, the other two right angles are in the $i$-th row and the $j$-th column. Therefore, the number of right triangles is $(rows[i] - 1) \\times (cols[j] - 1)$. We add this to the total count.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m + n)$. Where $m$ and $n$ are the number of rows and columns in the matrix, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m + n)" }, { "problem_id": 3129, "explanations": { "1": "We define a function $\\textit{dfs}(i, j, k)$ to represent the number of stable binary arrays that satisfy the problem conditions when there are $i$ zeros and $j$ ones remaining to place, and the next digit to fill is $k$. Then the answer is $\\textit{dfs}(\\textit{zero}, \\textit{one}, 0) + \\textit{dfs}(\\textit{zero}, \\textit{one}, 1)$.\n\nThe computation process of $\\textit{dfs}(i, j, k)$ is as follows:\n\n- If $i \\lt 0$ or $j \\lt 0$, return $0$.\n- If $i = 0$, then return $1$ when $k = 1$ and $j \\leq \\textit{limit}$; otherwise return $0$.\n- If $j = 0$, then return $1$ when $k = 0$ and $i \\leq \\textit{limit}$; otherwise return $0$.\n- If $k = 0$, we consider the case where the previous digit is $0$, i.e., $\\textit{dfs}(i - 1, j, 0)$, and the case where the previous digit is $1$, i.e., $\\textit{dfs}(i - 1, j, 1)$. If the previous digit is $0$, there may be more than $\\textit{limit}$ zeros in a subarray, which means the case where the $(\\textit{limit} + 1)$-th digit from the end is $1$ is invalid, so we subtract this case: $\\textit{dfs}(i - \\textit{limit} - 1, j, 1)$.\n- If $k = 1$, we consider the case where the previous digit is $0$, i.e., $\\textit{dfs}(i, j - 1, 0)$, and the case where the previous digit is $1$, i.e., $\\textit{dfs}(i, j - 1, 1)$. If the previous digit is $1$, there may be more than $\\textit{limit}$ ones in a subarray, which means the case where the $(\\textit{limit} + 1)$-th digit from the end is $0$ is invalid, so we subtract this case: $\\textit{dfs}(i, j - \\textit{limit} - 1, 0)$.\n\nTo avoid repeated computation, we use memoized search.\n\nThe time complexity is $O(\\textit{zero} \\times \\textit{one})$, and the space complexity is $O(\\textit{zero} \\times \\textit{one})$.", "2": "We can also convert the memoized search in Solution 1 into dynamic programming.\n\nWe define $f[i][j][k]$ as the number of stable binary arrays that use $i$ zeros and $j$ ones, with the last digit being $k$. Then the answer is $f[zero][one][0] + f[zero][one][1]$.\n\nInitially, we have $f[i][0][0] = 1$, where $1 \\leq i \\leq \\min(\\textit{limit}, \\textit{zero})$; and $f[0][j][1] = 1$, where $1 \\leq j \\leq \\min(\\textit{limit}, \\textit{one})$.\n\nThe state transition equations are as follows:\n\n- $f[i][j][0] = f[i - 1][j][0] + f[i - 1][j][1] - f[i - \\textit{limit} - 1][j][1]$.\n- $f[i][j][1] = f[i][j - 1][0] + f[i][j - 1][1] - f[i][j - \\textit{limit} - 1][0]$.\n\nThe time complexity is $O(\\textit{zero} \\times \\textit{one})$, and the space complexity is $O(\\textit{zero} \\times \\textit{one})$." }, "is_english": true, "time_complexity": "O(\\textit{zero} \\times \\textit{one})", "space_complexity": "O(\\textit{zero} \\times \\textit{one})" }, { "problem_id": 3130, "explanations": { "1": "We design a function $dfs(i, j, k)$ to represent the number of stable binary arrays that satisfy the problem conditions when there are $i$ $0$s and $j$ $1$s left, and the next number to be filled is $k$. The answer is $dfs(zero, one, 0) + dfs(zero, one, 1)$.\n\nThe calculation process of the function $dfs(i, j, k)$ is as follows:\n\n- If $i < 0$ or $j < 0$, return $0$.\n- If $i = 0$, return $1$ when $k = 1$ and $j \\leq \\textit{limit}$, otherwise return $0$.\n- If $j = 0$, return $1$ when $k = 0$ and $i \\leq \\textit{limit}$, otherwise return $0$.\n- If $k = 0$, we consider the case where the previous number is $0$, $dfs(i - 1, j, 0)$, and the case where the previous number is $1$, $dfs(i - 1, j, 1)$. If the previous number is $0$, it may cause more than $\\textit{limit}$ $0$s in the subarray, i.e., the situation where the $\\textit{limit} + 1$", "2": "We can also convert the memoization search of Solution 1 into dynamic programming.\n\nWe define $f[i][j][k]$ as the number of stable binary arrays using $i$ $0$s and $j$ $1$s, and the last number is $k$. So the answer is $f[zero][one][0] + f[zero][one][1]$.\n\nInitially, we have $f[i][0][0] = 1$, where $1 \\leq i \\leq \\min(\\textit{limit}, \\textit{zero})$; and $f[0][j][1] = 1$, where $1 \\leq j \\leq \\min(\\textit{limit}, \\textit{one})$.\n\nThe state transition equation is as follows:\n\n- $f[i][j][0] = f[i - 1][j][0] + f[i - 1][j][1] - f[i - \\textit{limit} - 1][j][1]$.\n- $f[i][j][1] = f[i][j - 1][0] + f[i][j - 1][1] - f[i][j - \\textit{limit} - 1][0]$.\n\nThe time complexity is $O(zero \\times one)$, and the space complexity is $O(zero \\times one)$." }, "is_english": true, "time_complexity": "O(zero \\times one)", "space_complexity": "O(zero \\times one)" }, { "problem_id": 3131, "explanations": { "1": "We can find the minimum value of each array, then return the difference between the two minimum values.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3132, "explanations": { "1": "First, we sort the arrays $nums1$ and $nums2$. Since we need to remove two elements from $nums1$, we only need to consider the first three elements of $nums1$, denoted as $a_1, a_2, a_3$. We can enumerate the first element $b_1$ of $nums2$, then we can get $x = b_1 - a_i$, where $i \\in \\{1, 2, 3\\}$. Then we can use the two pointers method to determine whether there exists an integer $x$ that makes $nums1$ and $nums2$ equal, and take the smallest $x$ that satisfies the condition.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 3133, "explanations": { "1": "According to the problem description, to make the last element of the array as small as possible and the bitwise AND result of the elements in the array is $x$, the first element of the array must be $x$.\n\nAssume the binary representation of $x$ is $\\underline{1}00\\underline{1}00$, then the array sequence is $\\underline{1}00\\underline{1}00$, $\\underline{1}00\\underline{1}01$, $\\underline{1}00\\underline{1}10$, $\\underline{1}00\\underline{1}11$...\n\nIf we ignore the underlined part, then the array sequence is $0000$, $0001$, $0010$, $0011$..., the first item is $0$, then the $n$-th item is $n-1$.\n\nTherefore, the answer is to fill each bit of the binary of $n-1$ into the $0$ bit of the binary of $x$ based on $x$.\n\nThe time complexity is $O(\\log x)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log x)", "space_complexity": "O(1)" }, { "problem_id": 3134, "explanations": { "1": "Let the length of the array $\\textit{nums}$ be $n$. The length of the uniqueness array is $m = \\frac{(1 + n) \\times n}{2}$, and the median of the uniqueness array is the $\\frac{m + 1}{2}$-th smallest number among these $m$ numbers.\n\nConsider how many numbers in the uniqueness array are less than or equal to $x$. As $x$ increases, there will be more and more numbers less than or equal to $x$. This property is monotonic, so we can use binary search to enumerate $x$ and find the first $x$ such that the number of elements in the uniqueness array less than or equal to $x$ is greater than or equal to $\\frac{m + 1}{2}$. This $x$ is the median of the uniqueness array.\n\nWe define the left boundary of the binary search as $l = 0$ and the right boundary as $r = n$. Then we perform binary search. For each $\\textit{mid}$, we check whether the number of elements in the uniqueness array less than or equal to $\\textit{mid}$ is greater than or equal to $\\frac{m + 1}{2}$. We achieve this through the function $\\text{check}(mx)$.\n\nThe implementation idea of the function $\\text{check}(mx)$ is as follows:\n\nSince the longer the subarray, the more different elements it contains, we can use two pointers to maintain a sliding window such that the number of different elements in the window does not exceed $mx$. Specifically, we maintain a hash table $\\textit{cnt}$, where $\\textit{cnt}[x]$ represents the number of occurrences of element $x$ in the window. We use two pointers $l$ and $r$, where $l$ represents the left boundary of the window and $r$ represents the right boundary. Initially, $l = r = 0$.\n\nWe enumerate $r$. For each $r$, we add $\\textit{nums}[r]$ to the window and update $\\textit{cnt}[\\textit{nums}[r]]$. If the number of different elements in the window exceeds $mx$, we need to move $l$ to the right until the number of different elements in the window does not exceed $mx$. At this point, the subarrays with the right endpoint $r$ and left endpoints in the range $[l, .., r]$ all meet the condition, and there are $r - l + 1$ such subarrays. We accumulate this count into $k$. If $k$ is greater than or equal to $\\frac{m + 1}{2}$, it means that the number of elements in the uniqueness array less than or equal to $\\textit{mid}$ is greater than or equal to $\\frac{m + 1}{2}$, and we return $\\text{true}$; otherwise, we return $\\text{false}$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3135, "explanations": { "1": "Let's assume that the lengths of the strings `initial` and `target` are $m$ and $n$, respectively.\n\nAccording to the problem description, we only need to find the length $mx$ of the longest common substring of `initial` and `target`. Then, we can delete $m - mx$ characters from `initial` and add $n - mx$ characters to transform `initial` into `target`. Therefore, the answer is $m + n - 2 \\times mx$.\n\nWe can use dynamic programming to find the length $mx$ of the longest common substring of `initial` and `target`. We define a two-dimensional array $f$, where $f[i][j]$ represents the length of the longest common substring ending with `initial[i - 1]` and `target[j - 1]`. Then, we can get the state transition equation:\n\n$$\nf[i][j] = \\begin{cases}\nf[i - 1][j - 1] + 1, & \\textit{if } \\textit{initial}[i - 1] = \\textit{target}[j - 1], \\\\\n0, & \\textit{otherwise}.\n\\end{cases}\n$$\n\nThen $mx = \\max f[i][j]$, and the final answer is $m + n - 2 \\times mx$.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Where $m$ and $n$ are the lengths of the strings `initial` and `target`, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 3136, "explanations": { "1": "First, we check if the length of the string is less than 3. If it is, we return `false`.\n\nNext, we iterate through the string, checking if each character is a letter or a number. If it's not, we return `false`. Otherwise, we check if the character is a vowel. If it is, we set `has_vowel` to `true`. If it's not, we set `has_consonant` to `true`.\n\nFinally, if both `has_vowel` and `has_consonant` are `true`, we return `true`. Otherwise, we return `false`.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$. Where $n$ is the length of the string." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3137, "explanations": { "1": "We can divide the string `word` into substrings of length $k$, then count the occurrence of each substring, and finally return $n/k$ minus the count of the most frequently occurring substring.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string `word`." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3138, "explanations": { "1": "Based on the problem description, the length of string $\\textit{t}$ must be a factor of the length of string $\\textit{s}$. We can enumerate the length $k$ of string $\\textit{t}$ from small to large, and then check if it meets the requirements of the problem. If it does, we return. Thus, the problem is transformed into how to check whether the length $k$ of string $\\textit{t}$ meets the requirements.\n\nFirst, we count the occurrence of each character in string $\\textit{s}$ and record it in an array or hash table $\\textit{cnt}$.\n\nNext, we define a function $\\textit{check}(k)$ to check whether the length $k$ of string $\\textit{t}$ meets the requirements. We can traverse string $\\textit{s}$, taking a substring of length $k$ each time, and then count the occurrence of each character. If the occurrence of each character multiplied by $\\frac{n}{k}$ does not equal the value in $\\textit{cnt}$, then return $\\textit{false}$. If all checks pass by the end of the traversal, return $\\textit{true}$.\n\nThe time complexity is $O(n \\times A)$, where $n$ is the length of string $\\textit{s}$, and $A$ is the number of factors of $n$. The space complexity is $O(|\\Sigma|)$, where $\\Sigma$ is the character set, which in this case is the set of lowercase letters." }, "is_english": true, "time_complexity": "O(n \\times A)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 3139, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3140, "explanations": { "1": "First, we find all the vacant seats, and then group the seats. The grouping is based on the seat number minus its ranking. In this way, consecutive vacant seats will be grouped together. Then we find the minimum seat number, maximum seat number, and length of consecutive seats in each group. Finally, we find the group with the longest length of consecutive seats, and output the minimum seat number, maximum seat number, and length of consecutive seats in this group." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3141, "explanations": { "1": "The problem requires us to find the maximum Hamming distance between each element and other elements in the array. We can think in reverse: for each element, we take its complement and find the minimum Hamming distance to other elements in the array. Then, the maximum Hamming distance we are looking for is $m$ minus this minimum Hamming distance.\n\nWe can use Breadth-First Search (BFS) to find the minimum Hamming distance from each complemented element to other elements.\n\nThe specific steps are as follows:\n\n1. Initialize an array $\\textit{dist}$ with a length of $2^m$ to record the minimum Hamming distance from each complemented element to other elements. Initially, all are set to $-1$.\n2. Traverse the array $\\textit{nums}$, set the complement of each element to $0$, and add it to the queue $\\textit{q}$.\n3. Starting from $k = 1$, continuously traverse the queue $\\textit{q}$. Each time, take out the elements in the queue, perform $m$ complement operations on them, add the complemented elements to the queue $\\textit{t}$, and set the minimum Hamming distance to the original element to $k$.\n4. Repeat step 3 until the queue is empty.\n\nFinally, we traverse the array $\\textit{nums}$, take the complement of each element as the index, and take out the corresponding minimum Hamming distance from the $\\textit{dist}$ array. Then, $m$ minus this value is the maximum Hamming distance we are looking for.\n\nThe time complexity is $O(2^m)$, and the space complexity is $O(2^m)$, where $m$ is the integer given in the problem." }, "is_english": true, "time_complexity": "O(2^m)", "space_complexity": "O(2^m)" }, { "problem_id": 3142, "explanations": { "1": "We can iterate through each cell and determine whether it meets the conditions specified in the problem. If there is a cell that does not meet the conditions, we return `false`, otherwise, we return `true`.\n\nThe time complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns of the matrix `grid` respectively. The space complexity is $O(1)`." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(1)" }, { "problem_id": 3143, "explanations": { "1": "For a point $(x, y)$, we can map it to the first quadrant with the origin as the center, i.e., $(\\max(|x|, |y|), \\max(|x|, |y|))$. In this way, we can map all points to the first quadrant and then sort them according to the distance from the point to the origin.\n\nWe can use a hash table $g$ to store the distance from all points to the origin, and then sort them according to the distance. For each distance $d$, we put all points with a distance of $d$ together, and then traverse these points. If there are two points with the same label, then this square is illegal, and we directly return the answer. Otherwise, we add these points to the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$, where $n$ is the number of points." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3144, "explanations": { "1": "We design a function $\\textit{dfs}(i)$, which represents the minimum number of substrings starting from $s[i]$. The answer is $\\textit{dfs}(0)$.\n\nThe calculation process of the function $\\textit{dfs}(i)$ is as follows:\n\nIf $i \\geq n$, it means all characters have been processed, so return $0$.\n\nOtherwise, we maintain a hash table $\\textit{cnt}$ to represent the frequency of each character in the current substring. Additionally, we maintain a hash table $\\textit{freq}$ to represent the frequency of each character's occurrence count.\n\nThen we enumerate $j$ from $i$ to $n-1$, representing the end position of the current substring. For each $j$, we update $\\textit{cnt}$ and $\\textit{freq}$, then check if the size of $\\textit{freq}$ is $1$. If it is, we can split from $j+1$, and the answer is $1 + \\textit{dfs}(j+1)$. We take the minimum answer among all $j$ as the return value of the function.\n\nTo avoid repeated calculations, we use memoized search.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n \\times |\\Sigma|)$. Here, $n$ is the length of the string $s$, and $|\\Sigma|$ represents the size of the character set, which is $26$ in this problem.", "2": "We can optimize Solution 1 by not maintaining the $\\textit{freq}$ hash table. Instead, we only need to maintain a hash table $\\textit{cnt}$, which represents the frequency of each character in the current substring. Additionally, we maintain two variables $k$ and $m$ to represent the number of distinct characters in the current substring and the maximum frequency of any character, respectively. For a substring $s[i..j]$, if $j-i+1 = m \\times k$, then this substring is a balanced substring.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n \\times |\\Sigma|)$. Here, $n$ is the length of the string $s$, and $|\\Sigma|$ represents the size of the character set, which is $26$ in this problem.", "3": "We can convert the memoized search into dynamic programming. Define the state $f[i]$ as the minimum number of substrings required to partition the first $i$ characters. Initially, $f[0] = 0$, and the rest $f[i] = +\\infty$ or $f[i] = n$.\n\nNext, we enumerate $i$ from $0$ to $n-1$. For each $i$, we maintain a hash table $\\textit{cnt}$ to represent the frequency of each character in the current substring. Additionally, we maintain two variables $k$ and $m$ to represent the number of distinct characters in the current substring and the maximum frequency of any character, respectively. For a substring $s[j..i]$, if $i-j+1 = m \\times k$, then this substring is a balanced substring. At this point, we can partition from $j$, so $f[i+1] = \\min(f[i+1], f[j] + 1)$.\n\nThe final answer is $f[n]$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n + |\\Sigma|)$. Here, $n$ is the length of the string $s$, and $|\\Sigma|$ represents the size of the character set, which is $26$ in this problem." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n \\times |\\Sigma|)" }, { "problem_id": 3145, "explanations": { "1": "The continuous positive integer numbers correspond to the strong integer array, forming the array $\\textit{bignums}$. The problem requires us to find the result of the product of the subarray $\\textit{bignums}[\\textit{left}..\\textit{right}]$ modulo $\\textit{mod}$ for each query $[\\textit{left}, \\textit{right}, \\textit{mod}]$. Since each element of the subarray is a power of 2, this is equivalent to finding the sum of the powers $\\textit{power}$ of the subarray, and then calculating $2^{\\textit{power}} \\bmod \\textit{mod}$. For example, for the subarray $[1, 4, 8]$, i.e., $[2^0, 2^2, 2^3]$, the sum of the powers is $0 + 2 + 3 = 5$, so $2^5 \\bmod \\textit{mod}$ is the result we need.\n\nTherefore, we can convert $\\textit{bignums}$ into an array of powers. For example, for the subarray $[1, 4, 8]$, we convert it to $[0, 2, 3]$. Thus, the problem is transformed into finding the sum of the subarray of powers, i.e., $\\textit{power} = \\textit{f}(\\textit{right} + 1) - \\textit{f}(\\textit{left})$, where $\\textit{f}(i)$ represents the sum of the powers of $\\textit{bignums}[0..i)$, which is the prefix sum.\n\nNext, we calculate the value of $\\textit{f}(i)$ based on the index $i$. We can use binary search to find the largest number whose strong array length is less than $i$, and then calculate the sum of the powers of the remaining numbers.\n\nAccording to the problem description, we list the strong integers for numbers $0..14$:\n\n| $\\textit{nums}$ | 8($2^3$) | 4($2^2$) | 2($2^1$) | ($2^0$) |\n| --------------- | ------------------------------------- | ------------------------------------- | ------------------------------------- | ------------------------------------- |\n| 0 | 0 | 0 | 0 | 0 |\n| 1 | 0 | 0 | 0 | 1 |\n| 2 | 0 | 0 | 1 | 0 |\n| 3 | 0 | 0 | 1 | 1 |\n| 4 | 0 | 1 | 0 | 0 |\n| 5 | 0 | 1 | 0 | 1 |\n| 6 | 0 | 1 | 1 | 0 |\n| 7 | 0 | 1 | 1 | 1 |\n| 8 | 1 | 0 | 0 | 0 |\n| 9 | 1 | 0 | 0 | 1 |\n| 10 | 1 | 0 | 1 | 0 |\n| 11 | 1 | 0 | 1 | 1 |\n| 12 | 1 | 1 | 0 | 0 |\n| 13 | 1 | 1 | 0 | 1 |\n| 14 | 1 | 1 | 1 | 0 |\n\nBy dividing the numbers into different colors according to the interval $[2^i, 2^{i+1}-1]$, we can see that the numbers in the interval $[2^i, 2^{i+1}-1]$ are equivalent to adding $2^i$ to each number in the interval $[0, 2^i-1]$. Based on this pattern, we can calculate the total number of strong arrays $\\textit{cnt}[i]$ and the sum of powers $\\textit{s}[i]$ for the first $i$ groups of numbers in $\\textit{bignums}$.\n\nNext, for any number, we consider how to calculate the number of strong arrays and the sum of powers. We can use the binary method, calculating from the highest bit. For example, for the number $13 = 2^3 + 2^2 + 2^0$, the result of the first $2^3$ numbers can be obtained from $\\textit{cnt}[3]$ and $\\textit{s}[3]$, and the result of the remaining $[2^3, 13]$ is equivalent to adding $3$ to all numbers in $[0, 13-2^3]$, i.e., $[0, 5]$. The problem is transformed into calculating the number of strong arrays and the sum of powers for $[0, 5]$. In this way, we can calculate the number of strong arrays and the sum of powers for any number.\n\nFinally, based on the value of $\\textit{power}$, we use the fast exponentiation method to calculate the result of $2^{\\textit{power}} \\bmod \\textit{mod}$.\n\nThe time complexity is $O(q \\times \\log M)$, and the space complexity is $O(\\log M)$. Here, $q$ is the number of queries, and $M$ is the upper bound of the number, with $M \\le 10^{15}$ in this problem." }, "is_english": true, "time_complexity": "O(q \\times \\log M)", "space_complexity": "O(\\log M)" }, { "problem_id": 3146, "explanations": { "1": "We can use a hash table or an array of length $26$, denoted as $\\textit{d}$, to store the positions of each character in the string $\\textit{s}$.\n\nThen, we traverse the string $\\textit{t}$ and calculate the sum of the absolute differences between the positions of each character in the string $\\textit{t}$ and the positions in the string $\\textit{s}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $\\textit{s}$. The space complexity is $O(|\\Sigma|)$, where $\\Sigma$ is the character set. Here, it is lowercase English letters, so $|\\Sigma| \\leq 26$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 3147, "explanations": { "1": "We can enumerate the endpoints within the range $[n - k, n)$, then traverse backwards from each endpoint, accumulating the energy values of wizards at intervals of $k$, and update the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of array $\\textit{energy}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3148, "explanations": { "1": "According to the problem description, if the values of the cells we pass through are $c_1, c_2, \\cdots, c_k$, then our score is $c_2 - c_1 + c_3 - c_2 + \\cdots + c_k - c_{k-1} = c_k - c_1$. Therefore, the problem is transformed into: for each cell $(i, j)$ of the matrix, if we take it as the endpoint, what is the minimum value of the starting point.\n\nWe can use dynamic programming to solve this problem. We define $f[i][j]$ as the minimum value of the path with $(i, j)$ as the endpoint. Then we can get the state transition equation:\n\n$$\nf[i][j] = \\min(f[i-1][j], f[i][j-1], grid[i][j])\n$$\n\nSo the answer is the maximum value of $\\textit{grid}[i][j] - \\min(f[i-1][j], f[i][j-1])$.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Where $m$ and $n$ are the number of rows and columns of the matrix, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 3149, "explanations": { "1": "We notice that for any permutation $\\textit{perm}$, if we cyclically shift it to the left any number of times, the score of the permutation remains the same. Since the problem requires returning the lexicographically smallest permutation, we can determine that the first element of the permutation must be $0$.\n\nAlso, since the data range of the problem does not exceed $14$, we can consider using the method of state compression to represent the set of numbers selected in the current permutation. We use a binary number $\\textit{mask}$ of length $n$ to represent the set of numbers selected in the current permutation, where the $i$-th bit of $\\textit{mask}$ is $1$ indicates that the number $i$ has been selected, and $0$ indicates that the number $i$ has not been selected yet.\n\nWe design a function $\\textit{dfs}(\\textit{mask}, \\textit{pre})$, which represents the minimum score of the permutation obtained when the set of numbers selected in the current permutation is $\\textit{mask}$ and the last selected number is $\\textit{pre}$. Initially, we add the number $0$ to the permutation.\n\nThe calculation process of the function $\\textit{dfs}(\\textit{mask}, \\textit{pre})$ is as follows:\n\n- If the number of $1$s in the binary representation of $\\textit{mask}$ is $n$, that is, $\\textit{mask} = 2^n - 1$, it means that all numbers have been selected, then return $|\\textit{pre} - \\textit{nums}[0]|$;\n- Otherwise, we enumerate the next selected number $\\textit{cur}$. If the number $\\textit{cur}$ has not been selected yet, then we can add the number $\\textit{cur}$ to the permutation. At this time, the score of the permutation is $|\\textit{pre} - \\textit{nums}[\\textit{cur}]| + \\textit{dfs}(\\textit{mask} \\, | \\, 1 << \\textit{cur}, \\textit{cur})$. We need to take the minimum score among all $\\textit{cur}$.\n\nFinally, we use a function $\\textit{g}(\\textit{mask}, \\textit{pre})$ to construct the permutation that gets the minimum score. We first add the number $\\textit{pre}$ to the permutation, and then enumerate the next selected number $\\textit{cur}$. If the number $\\textit{cur}$ has not been selected yet, and it satisfies that the value of $|\\textit{pre} - \\textit{nums}[\\textit{cur}]| + \\textit{dfs}(\\textit{mask} \\, | \\, 1 << \\textit{cur}, \\textit{cur})$ is equal to $\\textit{dfs}(\\textit{mask}, \\textit{pre})$, then we can add the number $\\textit{cur}$ to the permutation.\n\nThe time complexity is $(n^2 \\times 2^n)$, and the space complexity is $O(n \\times 2^n)$. Where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times 2^n)", "space_complexity": "O(n \\times 2^n)" }, { "problem_id": 3150, "explanations": { "1": "We can use the `LENGTH()` function to calculate the length of the string, calculate the length after excluding `@` or `#`, then use the `OR` operator to connect these three conditions, filter out the corresponding tweet_id, and sort by tweet_id in ascending order." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3151, "explanations": { "1": "We traverse the array from left to right. For each pair of adjacent elements, if their parity is the same, then the array is not a special array, return `false`; otherwise, the array is a special array, return `true`.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)`." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3152, "explanations": { "1": "We can define an array $d$ to record the leftmost special array position for each position, initially $d[i] = i$. Then we traverse the array $nums$ from left to right. If $nums[i]$ and $nums[i - 1]$ have different parities, then $d[i] = d[i - 1]$.\n\nFinally, we traverse each query and check whether $d[to] <= from$ holds.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3153, "explanations": { "1": "First, we get the number of digits $m$ in the array. Then for each digit, we count the occurrence of each number at this digit in the array `nums`, denoted as `cnt`. Therefore, the sum of the digit differences of all number pairs at this digit is:\n\n$$\n\\sum_{v \\in \\textit{cnt}} v \\times (n - v)\n$$\n\nwhere $n$ is the length of the array. We add up the digit differences of all digits and divide by $2$ to get the answer.\n\nThe time complexity is $O(n \\times m)$, and the space complexity is $O(C)$, where $n$ and $m$ are the length of the array and the number of digits in the numbers, respectively; and $C$ is a constant, in this problem $C = 10$." }, "is_english": true, "time_complexity": "O(n \\times m)", "space_complexity": "O(C)" }, { "problem_id": 3154, "explanations": { "1": "We design a function `dfs(i, j, jump)`, which represents the number of ways to reach the $k$th step when currently at the $i$th step, having performed $j$ operation 1's and `jump` operation 2's. The answer is `dfs(1, 0, 0)`.\n\nThe calculation process of the function `dfs(i, j, jump)` is as follows:\n\n- If $i > k + 1$, since we cannot go down twice in a row, we cannot reach the $k$th step again, so return $0$;\n- If $i = k$, it means that we have reached the $k$th step. The answer is initialized to $1$, and then continue to calculate;\n- If $i > 0$ and $j = 0$, it means that we can go down, recursively calculate `dfs(i - 1, 1, jump)`;\n- Recursively calculate `dfs(i + 2^{jump}, 0, jump + 1)`, and add it to the answer.\n\nTo avoid repeated calculations, we use memoization search to save the calculated states.\n\nThe time complexity is $O(\\log^2 k)$, and the space complexity is $O(\\log^2 k)$." }, "is_english": true, "time_complexity": "O(\\log^2 k)", "space_complexity": "O(\\log^2 k)" }, { "problem_id": 3155, "explanations": { "1": "For each data center, we assume that we can upgrade $x$ servers, then $x \\times \\textit{upgrade[i]} \\leq \\textit{count[i]} \\times \\textit{sell[i]} + \\textit{money[i]}$. That is, $x \\leq \\frac{\\textit{count[i]} \\times \\textit{sell[i]} + \\textit{money[i]}}{\\textit{upgrade[i]} + \\textit{sell[i]}}$. Also, $x \\leq \\textit{count[i]}$, so we can take the minimum of the two.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. Ignoring the space consumption of the answer array, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3156, "explanations": { "1": "First, we merge the `start_time` and `end_time` for each `employee_id` into a new table `T`. Then, using the `LEAD` function, we calculate the start time of the next task for each employee. Next, we join table `T` with the `Tasks` table to compute the concurrent task count for each employee. Finally, we group by `employee_id` to calculate the total task duration and the maximum concurrent tasks for each employee.\n\nSimilar Problem:\n\n- [3268. Find Overlapping Shifts II 🔒](https://github.com/doocs/leetcode/blob/main/solution/3200-3299/3268.Find%20Overlapping%20Shifts%20II/README_EN.md)" }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3157, "explanations": { "1": "We can use Breadth-First Search (BFS) to traverse the binary tree level by level, record the sum of the node values at each level, and find the level with the smallest sum of node values, then return the level number.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3158, "explanations": { "1": "We define an array or hash table `cnt` to record the occurrence of each number.\n\nNext, we traverse the array `nums`. When a number appears twice, we perform an XOR operation with the answer.\n\nFinally, we return the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(M)$. Where $n$ is the length of the array `nums`, and $M$ is the maximum value in the array `nums` or the number of distinct numbers in the array `nums`.", "2": "Since the given number range in the problem is $1 \\leq \\textit{nums}[i] \\leq 50$, we can use a $64$-bit integer to store the occurrence of each number.\n\nWe define an integer $\\textit{mask}$ to record whether each number has appeared.\n\nNext, we traverse the array $\\textit{nums}$. When a number appears twice, i.e., the $x$-th bit in the binary representation of $\\textit{mask}$ is $1$, we perform an XOR operation with the answer. Otherwise, we set the $x$-th bit of $\\textit{mask}$ to $1$.\n\nFinally, we return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(M)" }, { "problem_id": 3159, "explanations": { "1": "According to the problem description, we can first traverse the array `nums` to find the indices of all elements with a value of $x$, and record them in the array `ids`.\n\nNext, we traverse the array `queries`. For each query $i$, if $i - 1$ is less than the length of `ids`, then the answer is `ids[i - 1]`, otherwise, the answer is $-1$.\n\nThe time complexity is $O(n + m)$, and the space complexity is $O(n + m)$. Where $n$ and $m$ are the lengths of the arrays `nums` and `queries` respectively." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(n + m)" }, { "problem_id": 3160, "explanations": { "1": "We use a hash table `g` to record the color of each ball, and another hash table `cnt` to record the count of each color.\n\nNext, we traverse the array `queries`. For each query $(x, y)$, we increase the count of color $y$ by $1$, then check whether ball $x$ has been colored. If it has, we decrease the count of the color of ball $x$ by $1$. If the count drops to $0$, we remove it from the hash table `cnt`. Then, we update the color of ball $x$ to $y$, and add the current size of the hash table `cnt` to the answer array.\n\nAfter the traversal, we return the answer array.\n\nThe time complexity is $O(m)$, and the space complexity is $O(m)$, where $m$ is the length of the array `queries`." }, "is_english": true, "time_complexity": "O(m)", "space_complexity": "O(m)" }, { "problem_id": 3161, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3162, "explanations": { "1": "We directly enumerate all digit pairs $(x, y)$ and check whether $x \\bmod (y \\times k) = 0$. If it satisfies the condition, increment the answer by one.\n\nAfter the enumeration is complete, return the answer.\n\nThe time complexity is $O(m \\times n)$, where $m$ and $n$ are the lengths of arrays $\\textit{nums1}$ and $\\textit{nums2}$, respectively. The space complexity is $O(1)$.", "2": "We use a hash table `cnt1` to record the occurrence times of each number divided by $k$ in array `nums1`, and a hash table `cnt2` to record the occurrence times of each number in array `nums2`.\n\nNext, we enumerate each number $x$ in array `nums2`. For each number $x$, we enumerate its multiples $y$, where the range of $y$ is $[x, \\textit{mx}]$, where `mx` is the maximum key value in `cnt1`. Then we count the sum of `cnt1[y]`, denoted as $s$. Finally, we add $s \\times v$ to the answer, where $v$ is `cnt2[x]`.\n\nThe time complexity is $O(n + m + (M / k) \\times \\log m)$, and the space complexity is $O(n + m)$. Where $n$ and $m$ are the lengths of arrays `nums1` and `nums2` respectively, and $M$ is the maximum value in array `nums1`." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(1)" }, { "problem_id": 3163, "explanations": { "1": "We can use two pointers to count the consecutive occurrences of each character. Suppose the current character $c$ appears consecutively $k$ times, then we divide $k$ into several $x$, each $x$ is at most $9$, then we concatenate $x$ and $c$, and append each $x$ and $c$ to the result.\n\nFinally, return the result.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the", "2": "", "3": "" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3164, "explanations": { "1": "We use a hash table `cnt1` to record the occurrence times of each number divided by $k$ in array `nums1`, and a hash table `cnt2` to record the occurrence times of each number in array `nums2`.\n\nNext, we enumerate each number $x$ in array `nums2`. For each number $x$, we enumerate its multiples $y$, where the range of $y$ is $[x, \\textit{mx}]$, where `mx` is the maximum key value in `cnt1`. Then we count the sum of `cnt1[y]`, denoted as $s$. Finally, we add $s \\times v$ to the answer, where $v$ is `cnt2[x]`.\n\nThe time complexity is $O(n + m + (M / k) \\times \\log m)$, and the space complexity is $O(n + m)$. Where $n$ and $m$ are the lengths of arrays `nums1` and `nums2` respectively, and $M$ is the maximum value in array `nums1`." }, "is_english": true, "time_complexity": "O(n + m + (M / k) \\times \\log m)", "space_complexity": "O(n + m)" }, { "problem_id": 3165, "explanations": { "1": "According to the problem description, we need to perform multiple point updates and range queries. In this scenario, we consider using a segment tree to solve the problem.\n\nFirst, we define a $\\textit{Node}$ class to store the information of the segment tree nodes, including the left and right endpoints $l$ and $r$, as well as four state values $s_{00}$, $s_{01}$, $s_{10}$, and $s_{11}$. Specifically:\n\n- $s_{00}$ represents the maximum sum of the subsequence that does not include the left and right endpoints of the current node;\n- $s_{01}$ represents the maximum sum of the subsequence that does not include the left endpoint of the current node;\n- $s_{10}$ represents the maximum sum of the subsequence that does not include the right endpoint of the current node;\n- $s_{11}$ represents the maximum sum of the subsequence that includes the left and right endpoints of the current node.\n\nNext, we define a $\\textit{SegmentTree}$ class to construct the segment tree. During the construction of the segment tree, we need to recursively build the left and right subtrees and update the state values of the current node based on the state values of the left and right subtrees.\n\nIn the main function, we first construct the segment tree based on the given array $\\textit{nums}$ and process each query. For each query, we first perform a point update, then query the state values of the entire range, and accumulate the result into the answer.\n\nThe time complexity is $O((n + q) \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ represents the length of the array $\\textit{nums}$, and $q$ represents the number of queries." }, "is_english": true, "time_complexity": "O((n + q) \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3166, "explanations": { "1": "We can first group by `car_id` and `lot_id` to calculate the parking duration for each car in each parking lot. Then, we use the `RANK()` function to rank the parking duration of each car in each parking lot to find the parking lot where each car has the longest parking duration.\n\nFinally, we can group by `car_id` to calculate the total parking fee, average hourly fee, and the parking lot with the longest parking duration for each car." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3167, "explanations": { "1": "We can use a hash table to count the frequency of each character, and then use two pointers to traverse the `compressed` string, adding the frequency of each character to the hash table. Finally, we concatenate the characters and frequencies into a string in alphabetical order.\n\nThe time complexity is $O(n + |\\Sigma| \\log |\\Sigma|)$, and the space complexity is $O(|\\Sigma|)$. Where $n$ is the length of the string `compressed`, and $|\\Sigma|$ is the size of the character set. Here, the character set is lowercase letters, so $|\\Sigma| = 26$." }, "is_english": true, "time_complexity": "O(n + |\\Sigma| \\log |\\Sigma|)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 3168, "explanations": { "1": "We use a variable `cnt` to record the current number of chairs needed, and a variable `left` to record the current number of remaining empty chairs. We traverse the string `s`. If the current character is 'E', then if there are remaining empty chairs, we directly use one empty chair, otherwise we need to add a chair; if the current character is 'L', then the number of remaining empty chairs increases by one.\n\nAfter the traversal, we return `cnt`.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string `s`. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3169, "explanations": { "1": "We can sort all the meetings by their start time, and use a variable `last` to record the latest end time of the previous meetings.\n\nThen we traverse all the meetings. For each meeting $(st, ed)$, if `last < st`, it means that the time period from `last` to `st` is a time period when employees can work and no meetings are scheduled. We add this time period to the answer. Then we update `last = max(last, ed)`.\n\nFinally, if `last < days`, it means that there is a time period after the end of the last meeting when employees can work and no meetings are scheduled. We add this time period to the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Where $n$ is the number of meetings." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 3170, "explanations": { "1": "We define an array $g$ to record the index list of each character, and a boolean array $rem$ of length $n$ to record whether each character needs to be deleted.\n\nWe traverse the string $s$:\n\nIf the current character is an asterisk, we need to delete it, so we mark $rem[i]$ as deleted. At the same time, we need to delete the character with the smallest lexicographical order and the largest index at this time. We traverse the 26 lowercase letters in ascending order. If $g[a]$ is not empty, we delete the last index in $g[a]$ and set the corresponding index in $rem$ as deleted.\n\nIf the current character is not an asterisk, we add the index of the current character to $g$.\n\nFinally, we traverse $s$ and concatenate the undeleted characters.\n\nThe time complexity is $O(n \\times |\\Sigma|)$, and the space complexity is $O(n)$. Where $n$ is the length of the string $s$, and $|\\Sigma|$ is the size of the character set. In this problem, $|\\Sigma| = 26$." }, "is_english": true, "time_complexity": "O(n \\times |\\Sigma|)", "space_complexity": "O(n)" }, { "problem_id": 3171, "explanations": { "1": "According to the problem description, we need to calculate the result of the bitwise OR operation of elements from index $l$ to $r$ in the array $\\textit{nums}$, that is, $\\textit{nums}[l] \\lor \\textit{nums}[l + 1] \\lor \\cdots \\lor \\textit{nums}[r]$, where $\\lor$ represents the bitwise OR operation.\n\nIf we fix the right endpoint $r$, then the range of the left endpoint $l$ is $[0, r]$. Each time we move the right endpoint $r$, the result of the bitwise OR operation will only increase. We use a variable $s$ to record the current result of the bitwise OR operation. If $s$ is greater than $k$, we move the left endpoint $l$ to the right until $s$ is less than or equal to $k$. During the process of moving the left endpoint $l$, we need to maintain an array $cnt$ to record the number of $0$s on each binary digit in the current interval. When $cnt[h] = 0$, it means that all elements in the current interval have a $0$ on the $h^{th}$ bit, and we can set the $h^{th}$ bit of $s$ to $0$.\n\nThe time complexity is $O(n \\times \\log M)$, and the space complexity is $O(\\log M)$. Here, $n$ and $M$ respectively represent the length of the array $\\textit{nums}$ and the maximum value in the array $\\textit{nums}$.\n\nSimilar Problems:\n\n- [3097. Shortest Subarray With OR at Least K II](https://github.com/doocs/leetcode/blob/main/solution/3000-3099/3097.Shortest%20Subarray%20With%20OR%20at%20Least%20K%20II/README_EN.md)", "2": "According to the problem description, we need to calculate the result of the bitwise OR operation of elements from index $l$ to $r$ in the array $nums$, that is, $nums[l] \\lor nums[l + 1] \\lor \\cdots \\lor nums[r]$. Here, $\\lor$ represents the bitwise OR operation.\n\nIf we fix the right endpoint $r$, then the range of the left endpoint $l$ is $[0, r]$. Since the sum of bitwise OR increases monotonically as $l$ decreases, and the value of $\\textit{nums}[i]$ does not exceed $10^9$, the interval $[0, r]$ can have at most $30$ different values. Therefore, we can use a set to maintain all the values of $nums[l] \\lor nums[l + 1] \\lor \\cdots \\lor nums[r]$. When we traverse from $r$ to $r+1$, the values with $r+1$ as the right endpoint are the values obtained by performing the bitwise OR operation of each value in the set with $nums[r + 1]$, plus $nums[r + 1]$ itself. Therefore, we only need to enumerate each value in the set and perform the bitwise OR operation with $nums[r]$, to get all the values for $r$ as the right endpoint. Then, we take the absolute difference of each value with $k$, and the minimum of these differences is the answer.\n\nThe time complexity is $O(n \\times \\log M)$, and the space complexity is $O(\\log M)$. Here, $n$ and $M$ respectively represent the length of the array $nums$ and the maximum value in the array $nums$.\n\nSimilar Problems:\n\n- [1521. Find a Value of a Mysterious Function Closest to Target](https://github.com/doocs/leetcode/blob/main/solution/1500-1599/1521.Find%20a%20Value%20of%20a%20Mysterious%20Function%20Closest%20to%20Target/README_EN.md)" }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(\\log M)" }, { "problem_id": 3172, "explanations": { "1": "We can join the two tables and then use the `DATEDIFF` function to calculate whether the difference between the registration date and the operation date is equal to 1, and whether the registration operation is `Verified`, to filter out the user IDs that meet the conditions." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3173, "explanations": { "1": "We iterate through the first $n - 1$ elements of the array. For each element, we calculate the bitwise OR value of it and its next element, and store the result in the answer array.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. Ignoring the space consumption of the answer array, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3174, "explanations": { "1": "We use a stack `stk` to simulate this process. We traverse the string `s`. If the current character is a digit, we pop the top element from the stack. Otherwise, we push the current character into the stack.\n\nFinally, we concatenate the elements in the stack into a string and return it.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string `s`." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3175, "explanations": { "1": "We notice that each time the first two elements of the array are compared, regardless of the result, the next comparison will always be between the next element in the array and the current winner. Therefore, if we have looped $n-1$ times, the final winner must be the maximum element in the array. Otherwise, if an element has won consecutively $k$ times, then this element is the final winner.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$.\n\nSimilar problems:\n\n- [1535. Find the Winner of an Array Game](https://github.com/doocs/leetcode/blob/main/solution/1500-1599/1535.Find%20the%20Winner%20of%20an%20Array%20Game/README_EN.md)" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3176, "explanations": { "1": "We define $f[i][h]$ as the length of the longest good subsequence ending with $nums[i]$ and having no more than $h$ indices satisfying the condition. Initially, $f[i][h] = 1$. The answer is $\\max(f[i][k])$, where $0 \\le i < n$.\n\nWe consider how to calculate $f[i][h]$. We can enumerate $0 \\le j < i$, if $nums[i] = nums[j]$, then $f[i][h] = \\max(f[i][h], f[j][h] + 1)$; otherwise, if $h > 0$, then $f[i][h] = \\max(f[i][h], f[j][h - 1] + 1)$. That is:\n\n$$\nf[i][h]=\n\\begin{cases}\n\\max(f[i][h], f[j][h] + 1), & \\textit{if } nums[i] = nums[j], \\\\\n\\max(f[i][h], f[j][h - 1] + 1), & \\textit{if } h > 0.\n\\end{cases}\n$$\n\nThe final answer is $\\max(f[i][k])$, where $0 \\le i < n$.\n\nThe time complexity is $O(n^2 \\times k)$, and the space complexity is $O(n \\times k)$. Where $n$ is the length of the array `nums`.", "2": "According to the state transition equation in Solution 1, if $nums[i] = nums[j]$, then we only need to get the maximum value of $f[j][h]$. We can maintain this with an array $mp$ of length $k + 1$. If $nums[i] \\neq nums[j]$, we need to record the maximum value of $f[j][h - 1]$ corresponding to $nums[j]$, the maximum value and the second maximum value. We can maintain these with an array $g$ of length $k + 1$.\n\nThe time complexity is $O(n \\times k)$, and the space complexity is $O(n \\times k)$. Where $n$ is the length of the array `nums`." }, "is_english": true, "time_complexity": "O(n^2 \\times k)", "space_complexity": "O(n \\times k)" }, { "problem_id": 3177, "explanations": { "1": "We define $f[i][h]$ as the length of the longest good subsequence ending with $nums[i]$ and having no more than $h$ indices satisfying the condition. Initially, $f[i][h] = 1$. The answer is $\\max(f[i][k])$, where $0 \\le i < n$.\n\nWe consider how to calculate $f[i][h]$. We can enumerate $0 \\le j < i$, if $nums[i] = nums[j]$, then $f[i][h] = \\max(f[i][h], f[j][h] + 1)$; otherwise, if $h > 0$, then $f[i][h] = \\max(f[i][h], f[j][h - 1] + 1)$. That is:\n\n$$\nf[i][h]=\n\\begin{cases}\n\\max(f[i][h], f[j][h] + 1), & \\textit{if } nums[i] = nums[j], \\\\\n\\max(f[i][h], f[j][h - 1] + 1), & \\textit{if } h > 0.\n\\end{cases}\n$$\n\nThe final answer is $\\max(f[i][k])$, where $0 \\le i < n$.\n\nThe time complexity is $O(n^2 \\times k)$, and the space complexity is $O(n \\times k)$. Where $n$ is the length of the array `nums`.\n\nDue to the large data range of this problem, the above solution will time out and needs to be optimized.\n\nAccording to the state transition equation, if $nums[i] = nums[j]$, then we only need to get the maximum value of $f[j][h]$, we can maintain it with an array $mp$ of length $k + 1$. If $nums[i] \\neq nums[j]$, we need to record the maximum value of $f[j][h - 1]$ corresponding to $nums[j]$, the maximum value and the second maximum value, we can maintain it with an array $g$ of length $k + 1$.\n\nThe time complexity is $O(n \\times k)$, and the space complexity is $O(n \\times k)$. Where $n$ is the length of the array `nums`." }, "is_english": true, "time_complexity": "O(n^2 \\times k)", "space_complexity": "O(n \\times k)" }, { "problem_id": 3178, "explanations": { "1": "We notice that there are $n - 1$ passes in each round. Therefore, we can take $k$ modulo $n - 1$ to get the number of passes $mod$ in the current round. Then we divide $k$ by $n - 1$ to get the current round number $k$.\n\nNext, we judge the current round number $k$:\n\n- If $k$ is odd, then the current passing direction is from the end of the queue to the head, so it will be passed to the person with the number $n - mod - 1$.\n- If $k$ is even, then the current passing direction is from the head of the queue to the end, so it will be passed to the person with the number $mod$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 3179, "explanations": { "1": "We notice that the range of the integer $n$ is $1 \\leq n \\leq 1000$, so we can directly simulate this process.\n\nWe define an array $a$ of length $n$ and initialize all elements to $1$. Then we simulate the process for $k$ seconds, updating the elements of array $a$ every second until $k$ seconds have passed.\n\nFinally, we return $a[n - 1]$.\n\nThe time complexity is $O(n \\times k)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $a$." }, "is_english": true, "time_complexity": "O(n \\times k)", "space_complexity": "O(n)" }, { "problem_id": 3180, "explanations": { "1": "We can sort the `rewardValues` array and then use memoization to solve for the maximum total reward.\n\nWe define a function $\\textit{dfs}(x)$, representing the maximum total reward that can be obtained when the current total reward is $x$. Thus, the answer is $\\textit{dfs}(0)$.\n\nThe execution process of the function $\\textit{dfs}(x)$ is as follows:\n\n1. Perform a binary search in the `rewardValues` array for the index $i$ of the first element greater than $x$;\n2. Iterate over the elements in the `rewardValues` array starting from index $i$, and for each element $v$, calculate the maximum value of $v + \\textit{dfs}(x + v)$.\n3. Return the result.\n\nTo avoid repeated calculations, we use a memoization array `f` to record the results that have already been computed.\n\nThe time complexity is $O(n \\times (\\log n + M))$, and the space complexity is $O(M)$. Where $n$ is the length of the `rewardValues` array, and $M$ is twice the maximum value in the `rewardValues` array.", "2": "We define $f[i][j]$ as whether it is possible to obtain a total reward of $j$ using the first $i$ reward values. Initially, $f[0][0] = \\textit{True}$, and all other values are $\\textit{False}$.\n\nWe consider the $i$-th reward value $v$. If we do not choose it, then $f[i][j] = f[i - 1][j]$. If we choose it, then $f[i][j] = f[i - 1][j - v]$, where $0 \\leq j - v < v$. Thus, the state transition equation is:\n\n$$\nf[i][j] = f[i - 1][j] \\vee f[i - 1][j - v]\n$$\n\nThe final answer is $\\max\\{j \\mid f[n][j] = \\textit{True}\\}$.\n\nSince $f[i][j]$ only depends on $f[i - 1][j]$ and $f[i - 1][j - v]$, we can optimize away the first dimension and use only a one-dimensional array for state transitions.\n\nThe time complexity is $O(n \\times M)$, and the space complexity is $O(M)$. Where $n$ is the length of the `rewardValues` array, and $M$ is twice the maximum value in the `rewardValues` array.", "3": "We can optimize Solution 2 by defining a binary number $f$ to save the current state, where the $i$-th bit of $f$ being $1$ indicates that a total reward of $i$ is reachable.\n\nObserving the state transition equation from Solution 2, $f[j] = f[j] \\vee f[j - v]$, this is equivalent to taking the lower $v$ bits of $f$, shifting them left by $v$ bits, and then performing an OR operation with the original $f$.\n\nThus, the answer is the position of the highest bit in $f$.\n\nThe time complexity is $O(n \\times M / w)$, and the space complexity is $O(n + M / w)$. Where $n$ is the length of the `rewardValues` array, $M$ is twice the maximum value in the `rewardValues` array, and the integer $w = 32$ or $64$." }, "is_english": true, "time_complexity": "O(n \\times (\\log n + M))", "space_complexity": "O(M)" }, { "problem_id": 3181, "explanations": { "1": "We define $f[i][j]$ as whether it is possible to obtain a total reward of $j$ using the first $i$ reward values. Initially, $f[0][0] = \\textit{True}$, and all other values are $\\textit{False}$.\n\nWe consider the $i$-th reward value $v$. If we do not choose it, then $f[i][j] = f[i - 1][j]$; if we choose it, then $f[i][j] = f[i - 1][j - v]$, where $0 \\leq j - v < v$. Thus, the state transition equation is:\n\n$$\nf[i][j] = f[i - 1][j] \\vee f[i - 1][j - v]\n$$\n\nThe final answer is $\\max\\{j \\mid f[n][j] = \\textit{True}\\}$.\n\nSince $f[i][j]$ only depends on $f[i - 1][j]$ and $f[i - 1][j - v]$, we can optimize away the first dimension and use only a one-dimensional array for state transitions. Additionally, due to the large data range of this problem, we need to use bit manipulation to optimize the efficiency of state transitions.\n\nWe define a binary number $f$ to save the current state, where the $i$-th bit of $f$ being $1$ indicates that a total reward of $i$ is reachable.\n\nObserving the state transition equation $f[j] = f[j] \\vee f[j - v]$, this is equivalent to taking the lower $v$ bits of $f$, shifting them left by $v$ bits, and then performing an OR operation with the original $f$.\n\nThus, the answer is the position of the highest bit in $f$.\n\nThe time complexity is $O(n \\times M / w)$, and the space complexity is $O(n + M / w)$. Where $n$ is the length of the `rewardValues` array, $M$ is twice the maximum value in the `rewardValues` array, and the integer $w = 32$ or $64$." }, "is_english": true, "time_complexity": "O(n \\times M / w)", "space_complexity": "O(n + M / w)" }, { "problem_id": 3182, "explanations": { "1": "We can join the `students` table and `courses` table based on the `major` field, then left join the `enrollments` table to the resulting table, and finally group by `student_id` to filter out the students who meet the conditions." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3183, "explanations": { "1": "We can start by ignoring coin $4$, defining the coin array `coins = [1, 2, 6]`, and then using the idea of the complete knapsack problem. We define $f[j]$ as the number of ways to make up amount $j$ using the first $i$ types of coins, initially $f[0] = 1$. Then, we iterate through the coin array `coins`, and for each coin $x$, we iterate through amounts from $x$ to $n$, updating $f[j] = f[j] + f[j - x]$.\n\nFinally, $f[n]$ is the number of ways to make up amount $n$ using coins $1, 2, 6$. Then, if $n \\geq 4$, we consider choosing one coin $4$, so the number of ways becomes $f[n] + f[n - 4]$, and if $n \\geq 8$, we consider choosing two coins $4$, so the number of ways becomes $f[n] + f[n - 4] + f[n - 8]$.\n\nNote the modulus operation for the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the amount.", "2": "We can start by preprocessing the number of ways to make up every amount from $1$ to $10^5$, and then return the corresponding number of ways based on the value of $n$:\n\n- If $n < 4$, directly return $f[n]$;\n- If $4 \\leq n < 8$, return $f[n] + f[n - 4]$;\n- If $n \\geq 8$, return $f[n] + f[n - 4] + f[n - 8]$.\n\nNote the modulus operation for the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the amount." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3184, "explanations": { "1": "We can use a hash table or an array $\\textit{cnt}$ of length $24$ to record the occurrence count of each hour modulo $24$.\n\nIterate through the array $\\textit{hours}$. For each hour $x$, we can find the number that, when added to $x$, results in a multiple of $24$, and after modulo $24$, this number is $(24 - x \\bmod 24) \\bmod 24$. We then accumulate the occurrence count of this number from the hash table or array. After that, we increment the occurrence count of $x$ modulo $24$ by one.\n\nAfter iterating through the array $\\textit{hours}$, we can obtain the number of index pairs that meet the problem requirements.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{hours}$. The space complexity is $O(C)$, where $C=24$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(C)" }, { "problem_id": 3185, "explanations": { "1": "We can use a hash table or an array $\\textit{cnt}$ of length $24$ to record the occurrence count of each hour modulo $24$.\n\nIterate through the array $\\textit{hours}$. For each hour $x$, we can find the number that, when added to $x$, results in a multiple of $24$, and after modulo $24$, this number is $(24 - x \\bmod 24) \\bmod 24$. We then accumulate the occurrence count of this number from the hash table or array. After that, we increment the occurrence count of $x$ modulo $24$ by one.\n\nAfter iterating through the array $\\textit{hours}$, we can obtain the number of index pairs that meet the problem requirements.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{hours}$. The space complexity is $O(C)$, where $C=24$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(C)" }, { "problem_id": 3186, "explanations": { "1": "We can first sort the array $\\textit{power}$, use a hash table $\\textit{cnt}$ to record the occurrence count of each damage value, and then iterate through the array $\\textit{power}$. For each damage value $x$, we can determine the index of the next damage value that can be used when using a spell with damage value $x$, which is the index of the first damage value greater than $x + 2$. We can use binary search to find this index and record it in the array $\\textit{nxt}$.\n\nNext, we define a function $\\textit{dfs}$ to calculate the maximum damage value that can be obtained starting from the $i$-th damage value.\n\nIn the $\\textit{dfs}$ function, we can choose to skip the current damage value, so we can skip all the same damage values of the current one and directly jump to $i + \\textit{cnt}[x]$, obtaining a damage value of $\\textit{dfs}(i + \\textit{cnt}[x])$; or we can choose to use the current damage value, so we can use all the same damage values of the current one and then jump to the index of the next damage value, obtaining a damage value of $x \\times \\textit{cnt}[x] + \\textit{dfs}(\\textit{nxt}[i])$, where $\\textit{nxt}[i]$ represents the index of the first damage value greater than $x + 2$. We take the maximum of these two cases as the return value of the function.\n\nTo avoid repeated calculations, we can use memoization, storing the results that have already been calculated in an array $\\textit{f}$. Thus, when calculating $\\textit{dfs}(i)$, if $\\textit{f}[i]$ is not $0$, we directly return $\\textit{f}[i]$.\n\nThe answer is $\\textit{dfs}(0)$.\n\nThe time complexity is $O(n \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{power}$." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3187, "explanations": { "1": "According to the problem description, for $0 < i < n - 1$, if it satisfies $nums[i - 1] < nums[i]$ and $nums[i] > nums[i + 1]$, we can consider $nums[i]$ as $1$, otherwise as $0$. Thus, for operation $1$, i.e., querying the number of peak elements in the subarray $nums[l..r]$, it is equivalent to querying the number of $1$s in the interval $[l + 1, r - 1]$. We can use a binary indexed tree to maintain the number of $1$s in the interval $[1, n - 1]$.\n\nFor operation $1$, i.e., updating $nums[idx]$ to $val$, it will only affect the values at positions $idx - 1$, $idx$, and $idx + 1$, so we only need to update these three positions. Specifically, we can first remove the peak elements at these three positions, then update the value of $nums[idx]$, and finally add back the peak elements at these three positions.\n\nThe time complexity is $O((n + q) \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ and $q$ are the lengths of the array `nums` and the query array `queries`, respectively." }, "is_english": true, "time_complexity": "O((n + q) \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3188, "explanations": { "1": "First, we filter out students with an average GPA greater than or equal to 2.5 and record them in table `T`.\n\nNext, we join the `T` table with the `students` table based on `student_id`, then join with the `courses` table based on `major`, and finally perform a left join with the `enrollments` table based on `student_id` and `course_id`.\n\nAfter that, we group by student ID, use the `HAVING` clause to filter out students who meet the conditions, and finally sort by student ID." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3189, "explanations": { "1": "We can sort all the cars by their x-coordinates, and then allocate the cars to each row in order, calculating the sum of distances from each car to its target position. Then, sort all the cars by their y-coordinates and use the same method to calculate the sum of distances from each car to its target position. Finally, the sum of these two distances is the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the number of cars." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 3190, "explanations": { "1": "We directly iterate through the array $\\textit{nums}$. For each element $x$, if $x \\bmod 3 \\neq 0$, there are two cases:\n\n- If $x \\bmod 3 = 1$, we can decrease $x$ by $1$ to make it $x - 1$, which is divisible by $3$.\n- If $x \\bmod 3 = 2$, we can increase $x$ by $1$ to make it $x + 1$, which is divisible by $3$.\n\nTherefore, we only need to count the number of elements in the array that are not divisible by $3$ to get the minimum number of operations.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3191, "explanations": { "1": "We notice that the first position in the array that is $0$ must undergo a flip operation, otherwise, it cannot be turned into $1$. Therefore, we can sequentially traverse the array, and each time we encounter $0$, we flip the next two elements and accumulate one operation count.\n\nAfter the traversal, we return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3192, "explanations": { "1": "We notice that whenever we change an element at a certain position to 1, all the elements to its right are flipped. Therefore, we can use a variable $v$ to record whether the current position and all elements to its right have been flipped. If flipped, the value of $v$ is 1, otherwise, it is 0.\n\nWe iterate through the array $\\textit{nums}$. For each element $x$, we perform an XOR operation between $x$ and $v$. If $x$ is 0, then we need to change $x$ to 1, which requires a flip operation. We increment the answer by one and flip the value of $v$.\n\nAfter the iteration, we can obtain the minimum number of operations.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3193, "explanations": { "1": "We define $f[i][j]$ as the number of permutations of $[0..i]$ with $j$ inversions. Consider the relationship between the number $a_i$ at index $i$ and the previous $i$ numbers. If $a_i$ is smaller than $k$ of the previous numbers, then each of these $k$ numbers forms an inversion pair with $a_i$, contributing to $k$ inversions. Therefore, we can derive the state transition equation:\n\n$$\nf[i][j] = \\sum_{k=0}^{\\min(i, j)} f[i-1][j-k]\n$$\n\nSince the problem requires the number of inversions in $[0..\\textit{end}_i]$ to be $\\textit{cnt}_i$, when we calculate for $i = \\textit{end}_i$, we only need to compute $f[i][\\textit{cnt}_i]$. The rest of $f[i][..]$ will be $0$.\n\nThe time complexity is $O(n \\times m \\times \\min(n, m))$, and the space complexity is $O(n \\times m)$. Here, $m$ is the maximum number of inversions, and in this problem, $m \\le 400$." }, "is_english": true, "time_complexity": "O(n \\times m \\times \\min(n, m))", "space_complexity": "O(n \\times m)" }, { "problem_id": 3194, "explanations": { "1": "First, we sort the array $\\textit{nums}$. Then, we start taking elements from both ends of the array, calculating the sum of the two elements, and taking the minimum value. Finally, we return the minimum value divided by 2 as the answer.\n\nThe time complexity is $O(n \\log n)$, and the space complexity is $O(\\log n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 3195, "explanations": { "1": "We can traverse `grid`, finding the minimum boundary of all `1`s, denoted as $(x_1, y_1)$, and the maximum boundary, denoted as $(x_2, y_2)$. Then, the area of the minimum rectangle is $(x_2 - x_1 + 1) \\times (y_2 - y_1 + 1)$.\n\nThe time complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns in `grid`, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(1)" }, { "problem_id": 3196, "explanations": { "1": "Based on the problem description, if the current number has not been flipped, then the next one can either be flipped or not flipped; if the current number has been flipped, then the next one can only remain unflipped.\n\nTherefore, we define a function $\\textit{dfs}(i, j)$, which represents starting from the $i$-th number, whether the $i$-th number can be flipped, where $j$ indicates whether the $i$-th number is flipped. If $j = 0$, it means the $i$-th number cannot be flipped, otherwise, it can be flipped. The answer is $\\textit{dfs}(0, 0)$.\n\nThe execution process of the function $dfs(i, j)$ is as follows:\n\n- If $i \\geq \\textit{len}(nums)$, it means the array has been fully traversed, return $0$;\n- Otherwise, the $i$-th number can remain unflipped, in which case the answer is $nums[i] + \\textit{dfs}(i + 1, 1)$; if $j = 1$, it means the $i$-th number can be flipped, in which case the answer is $\\max(\\textit{dfs}(i + 1, 0) - nums[i])$. We take the maximum of the two.\n\nTo avoid repeated calculations, we can use memoization to save the results that have already been computed.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $nums$.", "2": "We can transform the memoization search from Solution 1 into dynamic programming.\n\nDefine $f$ and $g$ as two states, where $f$ represents the maximum value when the current number is not flipped, and $g$ represents the maximum value when the current number is flipped.\n\nTraverse the array $nums$, for the $i$-th number, we can update the values of $f$ and $g$ based on their states:\n\n- If the current number is not flipped, then the value of $f$ is $\\max(f, g) + x$, indicating that if the current number is not flipped, the previous number can be flipped or not flipped;\n- If the current number is flipped, then the value of $g$ is $f - x$, indicating that if the current number is flipped, the previous number cannot be flipped.\n\nThe final answer is $\\max(f, g)$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3197, "explanations": { "1": "According to the problem description, we can use two dividing lines to split the rectangle into three parts. We calculate the minimum rectangular area containing all $1$s for each part and then take the minimum sum of the areas of the three parts.\n\nWe can enumerate the positions of the two dividing lines, which have $6$ possibilities:\n\n1. Two horizontal splits\n2. Two vertical splits\n3. First perform a horizontal split, then a vertical split on the upper part\n4. First perform a horizontal split, then a vertical split on the lower part\n5. First perform a vertical split, then a horizontal split on the left part\n6. First perform a vertical split, then a horizontal split on the right part\n\nWe can use a function $\\textit{f}(i_1, j_1, i_2, j_2)$ to calculate the minimum rectangular area containing all $1$s from $(i_1, j_1)$ to $(i_2, j_2)$.\n\nThe time complexity is $O(m^2 \\times n^2)$, where $m$ and $n$ are the number of rows and columns of the rectangle, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m^2 \\times n^2)", "space_complexity": "O(1)" }, { "problem_id": 3198, "explanations": { "1": "We can first group by the `state` field, then sort the `city` field within each group, and finally use the `GROUP_CONCAT` function to concatenate the sorted city names into a comma-separated string." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3199, "explanations": { "1": "For two integers, the parity of the number of $1$s in the XOR result depends on the parity of the number of $1$s in the binary representations of the two integers.\n\nWe can use three arrays `cnt1`, `cnt2`, `cnt3` to record the parity of the number of $1$s in the binary representations of each number in arrays `a`, `b`, `c`, respectively.\n\nThen, we enumerate the parity of the number of $1$s in the binary representations of each number in the three arrays within the range $[0, 1]$. If the sum of the parity of the number of $1$s in the binary representations of three numbers is even, then the number of $1$s in the XOR result of these three numbers is also even. At this time, we multiply the combination of these three numbers and accumulate it into the answer.\n\nFinally, return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of arrays `a`, `b`, `c`. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3200, "explanations": { "1": "We can enumerate the color of the first row, then simulate the construction of the triangle, calculating the maximum height.\n\nThe time complexity is $O(\\sqrt{n})$, where $n$ is the number of red and blue balls. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\sqrt{n})", "space_complexity": "O(1)" }, { "problem_id": 3201, "explanations": { "1": "We set $k = 2$.\n\nBased on the problem description, we know that for a subsequence $a_1, a_2, a_3, \\cdots, a_x$, if it satisfies $(a_1 + a_2) \\bmod k = (a_2 + a_3) \\bmod k$. Then $a_1 \\bmod k = a_3 \\bmod k$. This means that the result of taking modulo $k$ for all odd-indexed elements is the same, and the result for all even-indexed elements is the same as well.\n\nWe can solve this problem using dynamic programming. Define the state $f[x][y]$ as the length of the longest valid subsequence where the last element modulo $k$ equals $x$, and the second to last element modulo $k$ equals $y$. Initially, $f[x][y] = 0$.\n\nIterate through the array $nums$, and for each number $x$, we get $x = x \\bmod k$. Then, we can enumerate the sequences where two consecutive numbers modulo $j$ yield the same result, where $j \\in [0, k)$. Thus, the previous number modulo $k$ would be $y = (j - x + k) \\bmod k$. At this point, $f[x][y] = f[y][x] + 1$.\n\nThe answer is the maximum value among all $f[x][y]$.\n\nThe time complexity is $O(n \\times k)$, and the space complexity is $O(k^2)$. Here, $n$ is the length of the array $\\textit{nums}$, and $k=2$." }, "is_english": true, "time_complexity": "O(n \\times k)", "space_complexity": "O(k^2)" }, { "problem_id": 3202, "explanations": { "1": "Based on the problem description, we know that for a subsequence $a_1, a_2, a_3, \\cdots, a_x$, if it satisfies $(a_1 + a_2) \\bmod k = (a_2 + a_3) \\bmod k$, then $a_1 \\bmod k = a_3 \\bmod k$. This means that the result of taking modulo $k$ for all odd-indexed elements is the same, and the result for all even-indexed elements is the same as well.\n\nWe can solve this problem using dynamic programming. Define the state $f[x][y]$ as the length of the longest valid subsequence where the last element modulo $k$ equals $x$, and the second to last element modulo $k$ equals $y$. Initially, $f[x][y] = 0$.\n\nIterate through the array $nums$, and for each number $x$, we get $x = x \\bmod k$. Then, we can enumerate the sequences where two consecutive numbers modulo $j$ yield the same result, where $j \\in [0, k)$. Thus, the previous number modulo $k$ would be $y = (j - x + k) \\bmod k$. At this point, $f[x][y] = f[y][x] + 1$.\n\nThe answer is the maximum value among all $f[x][y]$.\n\nThe time complexity is $O(n \\times k)$, and the space complexity is $O(k^2)$. Here, $n$ is the length of the array $\\textit{nums}$, and $k$ is the given positive integer." }, "is_english": true, "time_complexity": "O(n \\times k)", "space_complexity": "O(k^2)" }, { "problem_id": 3203, "explanations": { "1": "We denote $d_1$ and $d_2$ as the diameters of the two trees, respectively. Then, the diameter of the merged tree can be one of the following two cases:\n\n1. The diameter of the merged tree is the diameter of one of the original trees, i.e., $\\max(d_1, d_2)$;\n2. The diameter of the merged tree passes through both of the original trees. We calculate the radii of the original two trees as $r_1 = \\lceil \\frac{d_1}{2} \\rceil$ and $r_2 = \\lceil \\frac{d_2}{2} \\rceil$, respectively. Then, the diameter of the merged tree is $r_1 + r_2 + 1$.\n\nWe take the maximum of these two cases.\n\nWhen calculating the diameter of a tree, we can use two DFS passes. First, we arbitrarily select a node and start a DFS from this node to find the farthest node from it, denoted as node $a$. Then, we start another DFS from node $a$ to find the farthest node from node $a$, denoted as node $b$. It can be proven that the path between node $a$ and node $b$ is the diameter of the tree.\n\nThe time complexity is $O(n + m)$, and the space complexity is $O(n + m)$, where $n$ and $m$ are the number of nodes in the two trees, respectively." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(n + m)" }, { "problem_id": 3204, "explanations": { "1": "We can use the `BIT_AND` and `BIT_OR` functions to calculate `common_perms` and `any_perms`." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3205, "explanations": { "1": "We design a function $\\textit{dfs}(i)$, which represents the maximum score that can be obtained starting from index $i$. Therefore, the answer is $\\textit{dfs}(0)$.\n\nThe execution process of the function $\\textit{dfs}(i)$ is as follows:\n\nWe enumerate the next jump position $j$. Thus, the score that can be obtained starting from index $i$ is $(j - i) \\times \\textit{nums}[j]$, plus the maximum score that can be obtained starting from index $j$, making the total score $(j - i) \\times \\textit{nums}[j] + \\textit{dfs}(j)$. We enumerate all possible $j$ and take the maximum score.\n\nTo avoid redundant calculations, we use memoization search. We save the calculated value of $\\textit{dfs}(i)$, so it can be directly returned next time.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array.", "2": "We can transform the memoization search from Solution 1 into dynamic programming.\n\nDefine $f[j]$ as the maximum score that can be obtained starting from index $0$ and ending at index $j$. Therefore, the answer is $f[n - 1]$.\n\nThe state transition equation is:\n\n$$\nf[j] = \\max_{0 \\leq i < j} \\{ f[i] + (j - i) \\times \\textit{nums}[j] \\}\n$$\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array.", "3": "We observe that for the current position $i$, we should jump to the next position $j$ with the maximum value to obtain the maximum score.\n\nTherefore, we traverse the array $\\textit{nums}$, maintaining a stack $\\textit{stk}$ that is monotonically decreasing from the bottom to the top of the stack. For the current position $i$ being traversed, if the value corresponding to the top element of the stack is less than or equal to $\\textit{nums}[i]$, we continuously pop the top element of the stack until the stack is empty or the value corresponding to the top element of the stack is greater than $\\textit{nums}[i]$, and then push $i$ into the stack.\n\nNext, we initialize the answer $\\textit{ans}$ and the current position $i = 0$, traverse the elements in the stack, each time taking out the top element $j$, updating the answer $\\textit{ans} += \\textit{nums}[j] \\times (j - i)$, and then updating $i = j$.\n\nFinally, return the answer $\\textit{ans}$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 3206, "explanations": { "1": "We set $k = 3$, indicating that the length of the alternating group is $3$.\n\nFor convenience, we can unfold the ring into an array of length $2n$ and then traverse this array from left to right. We use a variable $\\textit{cnt}$ to record the current length of the alternating group. If we encounter the same color, we reset $\\textit{cnt}$ to $1$; otherwise, we increment $\\textit{cnt}$. If $\\textit{cnt} \\ge k$ and the current position $i$ is greater than or equal to $n$, then we have found an alternating group, and we increment the answer by one.\n\nAfter the traversal, we return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{colors}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3207, "explanations": { "1": "According to the problem description, we need to score by defeating enemies with the lowest energy value and increase our energy value by defeating enemies with the highest energy value and marking them.\n\nTherefore, we can sort the enemies by their energy values, then start from the enemy with the highest energy value, always choose the enemy with the lowest energy value to score and consume energy. Next, we add the energy value of the enemy with the highest energy to our current energy and mark that enemy. Repeat the above steps until all enemies are marked.\n\nThe time complexity is $O(n \\log n)$, and the space complexity is $O(\\log n)$, where $n$ is the number of enemies." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 3208, "explanations": { "1": "We can unfold the ring into an array of length $2n$ and then traverse this array from left to right. We use a variable $\\textit{cnt}$ to record the current length of the alternating group. If we encounter the same color, we reset $\\textit{cnt}$ to $1$; otherwise, we increment $\\textit{cnt}$. If $\\textit{cnt} \\ge k$ and the current position $i$ is greater than or equal to $n$, then we have found an alternating group, and we increment the answer by one.\n\nAfter the traversal, we return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{colors}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3209, "explanations": { "1": "According to the problem description, we need to find the result of the bitwise AND operation of elements from index $l$ to $r$ in the array $\\textit{nums}$, that is, $\\textit{nums}[l] \\land \\textit{nums}[l + 1] \\land \\cdots \\land \\textit{nums}[r]$, where $\\land$ represents the bitwise AND operation.\n\nIf we fix the right endpoint $r$, then the range of the left endpoint $l$ is $[0, r]$. Since the sum of bitwise AND decreases monotonically as $l$ decreases, and the value of $nums[i]$ does not exceed $10^9$, the interval $[0, r]$ can have at most $30$ different values. Therefore, we can use a set to maintain all the values of $\\textit{nums}[l] \\land \\textit{nums}[l + 1] \\land \\cdots \\land \\textit{nums}[r]$ and the number of times these values occur.\n\nWhen we traverse from $r$ to $r+1$, the values with $r+1$ as the right endpoint are the values obtained by performing the bitwise AND operation of each value in the set with $nums[r + 1]$, plus $\\textit{nums}[r + 1]$ itself.\n\nTherefore, we only need to enumerate each value in the set and perform the bitwise AND operation with $\\textit{nums[r]}$ to get all the values and their occurrences with $r$ as the right endpoint. Then, we need to add the occurrence count of $\\textit{nums[r]}$. At this point, we add the occurrence count of value $k$ to the answer. Continue traversing $r$ until the entire array is traversed.\n\nThe time complexity is $O(n \\times \\log M)$, and the space complexity is $O(\\log M)$. Here, $n$ and $M$ are the length of the array $\\textit{nums}$ and the maximum value in the array $\\textit{nums}$, respectively." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(\\log M)" }, { "problem_id": 3210, "explanations": { "1": "We can use the simulation method. For the $i^{th}$ character of the string, we replace it with the character at position $(i + k) \\bmod n$ of the string.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3211, "explanations": { "1": "We can enumerate each position $i$ of a binary string of length $n$, and for each position $i$, we can enumerate the possible value $j$ it can take. If $j$ is $0$, then we need to check if its previous position is $1$. If it is $1$, we can continue to recurse further; otherwise, it is invalid. If $j$ is $1$, then we directly recurse further.\n\nThe time complexity is $O(n \\times 2^n)$, where $n$ is the length of the string. Ignoring the space consumption of the answer array, the space complexity is $O(n)$." }, "is_english": true, "time_complexity": "O(n \\times 2^n)", "space_complexity": "O(n)" }, { "problem_id": 3212, "explanations": { "1": "According to the problem description, we only need to calculate the prefix sums $s[i][j][0]$ and $s[i][j][1]$ for each position $(i, j)$, which represent the number of characters `X` and `Y` in the submatrix from $(0, 0)$ to $(i, j)$, respectively. If $s[i][j][0] > 0$ and $s[i][j][0] = s[i][j][1]$, it means the condition is met, and we increment the answer by one.\n\nAfter traversing all positions, return the answer.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ represent the number of rows and columns of the matrix, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 3213, "explanations": { "1": "We define $f[i]$ as the minimum cost to construct the first $i$ characters of $\\textit{target}$, with the initial condition $f[0] = 0$ and all other values set to infinity. The answer is $f[n]$, where $n$ is the length of $\\textit{target}$.\n\nFor the current $f[i]$, consider enumerating the length $j$ of the word. If $j \\leq i$, then we can consider the hash value of the segment from $i - j + 1$ to $i$. If this hash value corresponds to an existing word, then we can transition from $f[i - j]$ to $f[i]$. The state transition equation is as follows:\n\n$$\nf[i] = \\min(f[i], f[i - j] + \\textit{cost}[k])\n$$\n\nwhere $\\textit{cost}[k]$ represents the minimum cost of a word of length $j$ whose hash value matches $\\textit{target}[i - j + 1, i]$.\n\nThe time complexity is $O(n \\times \\sqrt{L})$, and the space complexity is $O(n)$. Here, $n$ is the length of $\\textit{target}$, and $L$ is the sum of the lengths of all words in the array $\\textit{words}$." }, "is_english": true, "time_complexity": "O(n \\times \\sqrt{L})", "space_complexity": "O(n)" }, { "problem_id": 3214, "explanations": { "1": "We can first group by `product_id` and `year(transaction_date)` to perform the statistics, then use a left join to associate the statistics of the current year with those of the previous year, and finally calculate the year-on-year growth rate." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3215, "explanations": { "1": "For two integers, the parity of the number of $1$s in the XOR result depends on the parity of the number of $1$s in the binary representations of the two integers.\n\nWe can use three arrays `cnt1`, `cnt2`, `cnt3` to record the parity of the number of $1$s in the binary representations of each number in arrays `a`, `b`, `c`, respectively.\n\nThen, we enumerate the parity of the number of $1$s in the binary representations of each number in the three arrays within the range $[0, 1]$. If the sum of the parity of the number of $1$s in the binary representations of three numbers is even, then the number of $1$s in the XOR result of these three numbers is also even. At this time, we multiply the combination of these three numbers and accumulate it into the answer.\n\nFinally, return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of arrays `a`, `b`, `c`. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3216, "explanations": { "1": "We can traverse the string $\\textit{s}$ from left to right. For each pair of adjacent digits, if they have the same parity and the previous digit is greater than the next digit, then we swap these two digits to make the lexicographical order of the string $\\textit{s}$ smaller, and then return the swapped string.\n\nAfter the traversal, if no swappable pair of digits is found, it means the string $\\textit{s}$ is already in its smallest lexicographical order, and we can return it directly.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the string $\\textit{s}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3217, "explanations": { "1": "We can use a hash table $\\textit{s}$ to store all the elements in the array $\\textit{nums}$. Then, we define a dummy node $\\textit{dummy}$ and point it to the head node of the list $\\textit{head}$.\n\nNext, we traverse the list starting from the dummy node $\\textit{dummy}$. If the value of the next node of the current node is in the hash table $\\textit{s}$, we make the current node point to the next next node; otherwise, we move the current node pointer to the next node.\n\nFinally, we return the next node of the dummy node $\\textit{dummy}$.\n\nThe time complexity is $O(n + m)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$, and $m$ is the length of the list $\\textit{head}$." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(n)" }, { "problem_id": 3218, "explanations": { "1": "For a given position, the earlier you cut, the fewer cuts are needed, so it is clear that positions with higher costs should be cut earlier.\n\nTherefore, we can sort the arrays $\\textit{horizontalCut}$ and $\\textit{verticalCut}$ in descending order, and then use two pointers $i$ and $j$ to point to the costs in $\\textit{horizontalCut}$ and $\\textit{verticalCut}$, respectively. Each time, we choose the position with the larger cost to cut, while updating the corresponding number of rows and columns.\n\nEach time a horizontal cut is made, if the number of columns before the cut was $v$, then the cost of this cut is $\\textit{horizontalCut}[i] \\times v$, and then the number of rows $h$ is incremented by one; similarly, each time a vertical cut is made, if the number of rows before the cut was $h$, then the cost of this cut is $\\textit{verticalCut}[j] \\times h$, and then the number of columns $v$ is incremented by one.\n\nFinally, when both $i$ and $j$ reach the end, return the total cost.\n\nThe time complexity is $O(m \\times \\log m + n \\times \\log n)$, and the space complexity is $O(\\log m + \\log n)$. Here, $m$ and $n$ are the lengths of $\\textit{horizontalCut}$ and $\\textit{verticalCut}$, respectively." }, "is_english": true, "time_complexity": "O(m \\times \\log m + n \\times \\log n)", "space_complexity": "O(\\log m + \\log n)" }, { "problem_id": 3219, "explanations": { "1": "For a given position, the earlier you cut, the fewer cuts are needed, so it is clear that positions with higher costs should be cut earlier.\n\nTherefore, we can sort the arrays $\\textit{horizontalCut}$ and $\\textit{verticalCut}$ in descending order, and then use two pointers $i$ and $j$ to point to the costs in $\\textit{horizontalCut}$ and $\\textit{verticalCut}$, respectively. Each time, we choose the position with the larger cost to cut, while updating the corresponding number of rows and columns.\n\nEach time a horizontal cut is made, if the number of columns before the cut was $v$, then the cost of this cut is $\\textit{horizontalCut}[i] \\times v$, and then the number of rows $h$ is incremented by one; similarly, each time a vertical cut is made, if the number of rows before the cut was $h$, then the cost of this cut is $\\textit{verticalCut}[j] \\times h$, and then the number of columns $v$ is incremented by one.\n\nFinally, when both $i$ and $j$ reach the end, return the total cost.\n\nThe time complexity is $O(m \\times \\log m + n \\times \\log n)$, and the space complexity is $O(\\log m + \\log n)$. Here, $m$ and $n$ are the lengths of $\\textit{horizontalCut}$ and $\\textit{verticalCut}$, respectively." }, "is_english": true, "time_complexity": "O(m \\times \\log m + n \\times \\log n)", "space_complexity": "O(\\log m + \\log n)" }, { "problem_id": 3220, "explanations": { "1": "We can group the data by `transaction_date`, and then calculate the sum of transaction amounts for odd and even dates separately. Finally, sort by `transaction_date` in ascending order." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3221, "explanations": { "1": "We observe that for the current position $i$, we should jump to the next position $j$ with the maximum value to obtain the maximum score.\n\nTherefore, we traverse the array $\\textit{nums}$, maintaining a stack $\\textit{stk}$ that is monotonically decreasing from the bottom to the top of the stack. For the current position $i$ being traversed, if the value corresponding to the top element of the stack is less than or equal to $\\textit{nums}[i]$, we continuously pop the top element of the stack until the stack is empty or the value corresponding to the top element of the stack is greater than $\\textit{nums}[i]$, and then push $i$ into the stack.\n\nNext, we initialize the answer $\\textit{ans}$ and the current position $i = 0$, traverse the elements in the stack, each time taking out the top element $j$, updating the answer $\\textit{ans} += \\textit{nums}[j] \\times (j - i)$, and then updating $i = j$." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3222, "explanations": { "1": "Since each round of operation consumes $2$ coins valued at $75$ and $8$ coins valued at $10$, we can calculate the number of rounds $k = \\min(x / 2, y / 8)$, and then update the values of $x$ and $y$, where $x$ and $y$ are the remaining number of coins after $k$ rounds of operations.\n\nIf $x > 0$ and $y \\geq 4$, then Alice can continue the operation, and Bob loses, return \"Alice\"; otherwise, return \"Bob\".\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 3223, "explanations": { "1": "We can count the occurrences of each character in the string, and then iterate through the count array. If a character appears an odd number of times, then $1$ of that character remains in the end; if a character appears an even number of times, then $2$ of that character remain. We can sum the remaining counts of all characters to get the final length of the string.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(|\\Sigma|)$, where $|\\Sigma|$ is the size of the character set, which is $26$ in this problem." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 3224, "explanations": { "1": "Assume that in the final array, the difference between the pair $\\textit{nums}[i]$ and $\\textit{nums}[n-i-1]$ is $s$.\n\nLet's denote $x$ as the smaller value between $\\textit{nums}[i]$ and $\\textit{nums}[n-i-1]$, and $y$ as the larger value.\n\nFor each pair of numbers, we have the following scenarios:\n\n- If no change is needed, then $y - x = s$.\n- If one change is made, then $s \\le \\max(y, k - x)$, where the maximum value is achieved by changing $x$ to $0$, or changing $y$ to $k$.\n- If two changes are made, then $s > \\max(y, k - x)$.\n\nThat is:\n\n- In the range $[0, y-x-1]$, $1$ change is needed.\n- At $[y-x]$, no change is needed.\n- In the range $[y-x+1, \\max(y, k-x)]$, $1$ change is needed.\n- In the range $[\\max(y, k-x)+1, k]$, $2$ changes are needed.\n\nWe enumerate each pair of numbers and use a difference array to update the number of changes needed in different ranges for each pair.\n\nFinally, we find the minimum value among the prefix sums from the difference array, which is the minimum number of changes needed.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$.\n\nSimilar problems:\n\n- [1674. Minimum Moves to Make Array Complementary](https://github.com/doocs/leetcode/tree/main/solution/1600-1699/1674.Minimum%20Moves%20to%20Make%20Array%20Complementary/README_EN.md)" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3225, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3226, "explanations": { "1": "If the bitwise AND result of $n$ and $k$ is not equal to $k$, it indicates that there exists at least one bit where $k$ is $1$ and the corresponding bit in $n$ is $0$. In this case, it is impossible to modify a bit in $n$ to make $n$ equal to $k$, and we return $-1$. Otherwise, we count the number of $1$s in the binary representation of $n \\oplus k$.\n\nThe time complexity is $O(\\log n)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 3227, "explanations": { "1": "Let's denote the number of vowels in the string as $k$.\n\nIf $k = 0$, meaning there are no vowels in the string, then Little Red cannot remove any substring, and Little Ming wins directly.\n\nIf $k$ is odd, then Little Red can remove the entire string, resulting in a direct win for Little Red.\n\nIf $k$ is even, then Little Red can remove $k - 1$ vowels, leaving one vowel in the string. In this case, Little Ming cannot remove any substring, leading to a direct win for Little Red.\n\nIn conclusion, if the string contains vowels, then Little Red wins; otherwise, Little Ming wins.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3228, "explanations": { "1": "We use a variable $\\textit{ans}$ to record the answer and another variable $\\textit{cnt}$ to count the current number of $1$s.\n\nThen, we iterate through the string $s$. If the current character is $1$, then we increment $\\textit{cnt}$. Otherwise, if there is a previous character and the previous character is $1$, then the previous $\\textit{cnt}$ number of $1$s can be moved backward, and we add $\\textit{cnt}$ to the answer.\n\nFinally, we return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3229, "explanations": { "1": "We can first calculate the difference between the arrays $\\textit{nums}$ and $\\textit{target}$. For a difference array, we find continuous intervals where the signs of the differences are the same. For each interval, we add the absolute value of the first element to the result. For the subsequent elements, if the absolute value of the difference is greater than the absolute value of the previous difference, we add the difference of the absolute values to the result.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$.\n\nSimilar problems:\n\n- [1526. Minimum Number of Increments on Subarrays to Form a Target Array](https://github.com/doocs/leetcode/tree/main/solution/1500-1599/1526.Minimum%20Number%20of%20Increments%20on%20Subarrays%20to%20Form%20a%20Target%20Array/README_EN.md)" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3230, "explanations": { "1": "First, we join the `Transactions` table with the `Products` table, recording the result in a temporary table `T`.\n\nNext, we use the `T` table to calculate the transaction count and the most recent transaction date for each user in each category, saving the results in a temporary table `P`.\n\nThen, we use the `P` table to calculate the ranking of transaction counts for each user in each category, saving the results in a temporary table `R`.\n\nFinally, we use the `T` and `R` tables to calculate the total transaction amount, transaction count, unique category count, average transaction amount, most frequently purchased category, and loyalty score for each user, and return the results in descending order of loyalty score and ascending order of user ID." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3231, "explanations": { "1": "We traverse the array $\\textit{nums}$ from left to right. For each element $x$, we need to greedily append it after the last element of the preceding sequence that is smaller than $x$. If no such element is found, it means the current element $x$ is smaller than all elements in the preceding sequences, and we need to start a new sequence with $x$.\n\nFrom this analysis, we can observe that the last elements of the preceding sequences are in a monotonically decreasing order. Therefore, we can use binary search to find the position of the first element in the preceding sequences that is smaller than $x$, and then place $x$ in that position.\n\nFinally, we return the number of sequences.\n\nThe time complexity is $O(n \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3232, "explanations": { "1": "According to the problem description, as long as the sum of the units digits is not equal to the sum of the tens digits, Alice can always choose a larger sum to win.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3233, "explanations": { "1": "According to the problem description, we can observe that only the squares of prime numbers are special numbers. Therefore, we can first preprocess all prime numbers less than or equal to $\\sqrt{10^9}$, and then iterate through the interval $[\\lceil\\sqrt{l}\\rceil, \\lfloor\\sqrt{r}\\rfloor]$, counting the number of primes $\\textit{cnt}$ in the interval. Finally, we return $r - l + 1 - \\textit{cnt}$.\n\nThe time complexity is $O(\\sqrt{m})$, and the space complexity is $O(\\sqrt{m})$, where $m = 10^9$." }, "is_english": true, "time_complexity": "O(\\sqrt{m})", "space_complexity": "O(\\sqrt{m})" }, { "problem_id": 3234, "explanations": { "1": "According to the problem description, a dominant string satisfies $\\textit{cnt}_1 \\geq \\textit{cnt}_0^2$, which means the maximum value of $\\textit{cnt}_0$ does not exceed $\\sqrt{n}$, where $n$ is the length of the string. Therefore, we can enumerate the value of $\\textit{cnt}_0$ and then calculate the number of substrings that satisfy the condition.\n\nWe first preprocess the position of the first $0$ starting from each position in the string, storing it in the array $\\textit{nxt}$, where $\\textit{nxt}[i]$ represents the position of the first $0$ starting from position $i$, or $n$ if it doesn't exist.\n\nNext, we iterate through each position $i$ in the string as the starting position of the substring, initializing $\\textit{cnt}_0$ to $0$ or $1$ (depending on whether the current position is $0$). Then we use a pointer $j$ starting from position $i$, jumping step by step to the position of the next $0$, while updating the value of $\\textit{cnt}_0$.\n\nFor a substring starting at position $i$ and containing $\\textit{cnt}_0$ zeros, it can contain at most $\\textit{nxt}[j + 1] - i - \\textit{cnt}_0$ ones. If this quantity is greater than or equal to $\\textit{cnt}_0^2$, it means there exists a substring that satisfies the condition. At this point, we need to determine how many positions the right endpoint $\\textit{nxt}[j + 1] - 1$ can move left while still satisfying the condition. Specifically, the right endpoint has a total of $\\min(\\textit{nxt}[j + 1] - j, \\textit{cnt}_1 - \\textit{cnt}_0^2 + 1)$ possible choices. We accumulate these counts to the answer. Then we move pointer $j$ to the position of the next $0$ and continue enumerating the next value of $\\textit{cnt}_0$ until $\\textit{cnt}_0^2$ exceeds the string length.\n\nThe time complexity is $O(n \\times \\sqrt{n})$, and the space complexity is $O(n)$, where $n$ is the length of the string." }, "is_english": true, "time_complexity": "O(n \\times \\sqrt{n})", "space_complexity": "O(n)" }, { "problem_id": 3235, "explanations": { "1": "According to the problem description, we discuss the following cases:\n\nWhen there is only one circle in `circles`:\n\n1. If the starting point $(0, 0)$ is inside the circle (including the boundary), or the ending point $(\\textit{xCorner}, \\textit{yCorner})$ is inside the circle, then it is impossible to satisfy the condition of \"not touching the circle\".\n2. If the circle intersects with the left or top side of the rectangle and also intersects with the right or bottom side of the rectangle, then the circle will block the path from the bottom-left corner to the top-right corner of the rectangle, making it impossible to satisfy the condition of \"not touching the circle\".\n\nWhen there are multiple circles in `circles`:\n\n1. Similar to the above case, if the starting point or ending point is inside a circle, it is impossible to satisfy the condition of \"not touching the circle\".\n2. If there are multiple circles, they may intersect within the rectangle, forming a larger obstacle area. As long as this obstacle area intersects with the left or top side of the rectangle and also intersects with the right or bottom side of the rectangle, it is impossible to satisfy the condition of \"not touching the circle\". If the intersecting area is not inside the rectangle, it cannot be merged because the intersecting area cannot block the path inside the rectangle. Additionally, if part of the intersecting area is inside the rectangle and part is outside, these circles can be used as starting or ending points and can be merged or not. We only need to choose one of the intersecting points. If this point is inside the rectangle, we can merge these circles.\n\nBased on the above analysis, we traverse all circles. For the current circle, if the starting point or ending point is inside the circle, we directly return `false`. Otherwise, if this point has not been visited and the circle intersects with the left or top side of the rectangle, we start a depth-first search (DFS) from this circle. During the search, if we find a circle that intersects with the right or bottom side of the rectangle, it means the obstacle area formed by the circles blocks the path from the bottom-left corner to the top-right corner of the rectangle, and we return `false`.\n\nWe define $\\textit{dfs}(i)$ to represent starting a DFS from the $i$-th circle. If we find a circle that intersects with the right or bottom side of the rectangle, we return `true`; otherwise, we return `false`.\n\nThe execution process of the function $\\textit{dfs}(i)$ is as follows:\n\n1. If the current circle intersects with the right or bottom side of the rectangle, return `true`;\n2. Otherwise, mark the current circle as visited;\n3. Next, traverse all other circles. If circle $j$ has not been visited, and circle $i$ intersects with circle $j$, and one of the intersection points of these two circles is inside the rectangle, continue the DFS from circle $j$. If we find a circle that intersects with the right or bottom side of the rectangle, return `true`;\n4. If no such circle is found, return `false`.\n\nIn the above process, we need to determine whether two circles $O_1 = (x_1, y_1, r_1)$ and $O_2 = (x_2, y_2, r_2)$ intersect. If the distance between the centers of the two circles does not exceed the sum of their radii, i.e., $(x_1 - x_2)^2 + (y_1 - y_2)^2 \\le (r_1 + r_2)^2$, then they intersect.\n\nWe also need to find an intersection point of the two circles. We take a point $A = (x, y)$ such that $\\frac{O_1 A}{O_1 O_2} = \\frac{r_1}{r_1 + r_2}$. If the two circles intersect, point $A$ must be in the intersection. In this case, $\\frac{x - x_1}{x_2 - x_1} = \\frac{r_1}{r_1 + r_2}$, solving for $x = \\frac{x_1 r_2 + x_2 r_1}{r_1 + r_2}$. Similarly, $y = \\frac{y_1 r_2 + y_2 r_1}{r_1 + r_2}$. As long as this point is inside the rectangle, we can continue the DFS, satisfying:\n\n$$\n\\begin{cases}\nx_1 r_2 + x_2 r_1 < (r_1 + r_2) \\times \\textit{xCorner} \\\\\ny_1 r_2 + y_2 r_1 < (r_1 + r_2) \\times \\textit{yCorner}\n\\end{cases}\n$$\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ is the number of circles." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 3236, "explanations": { "1": "First, we use a recursive CTE to calculate the hierarchy level of each employee, where the CEO's level is $0$. We save `employee_id`, `employee_name`, `hierarchy_level`, `manager_id`, and `salary` into a temporary table `T`.\n\nThen, we query the CEO's salary and save it into a temporary table `P`.\n\nFinally, we join tables `T` and `P` to calculate the salary difference for each subordinate, and sort by `hierarchy_level` and `subordinate_id`." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3237, "explanations": { "1": "According to the problem description, the later the query, the earlier it appears in the result. Therefore, we can traverse the $\\textit{queries}$ array in reverse order, using a hash table $\\textit{s}$ to record the windows that have already appeared. For each query, if the current window is not in the hash table, we add it to the answer array and also add it to the hash table. Finally, we traverse the $\\textit{windows}$ array again, adding the windows that are not in the hash table to the answer array.\n\nThe time complexity is $O(n + m)$, and the space complexity is $O(m)$. Here, $n$ and $m$ are the lengths of the $\\textit{windows}$ and $\\textit{queries}$ arrays, respectively." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(m)" }, { "problem_id": 3238, "explanations": { "1": "We can use a 2D array $\\textit{cnt}$ to record the number of balls of each color obtained by each player, and a hash table $\\textit{s}$ to record the IDs of the winning players.\n\nTraverse the $\\textit{pick}$ array, for each element $[x, y]$, we increment $\\textit{cnt}[x][y]$ by one. If $\\textit{cnt}[x][y]$ is greater than $x$, we add $x$ to the hash table $\\textit{s}$.\n\nFinally, return the size of the hash table $\\textit{s}$.\n\nThe time complexity is $O(m + n \\times M)$, and the space complexity is $O(n \\times M)$. Here, $m$ is the length of the $\\textit{pick}$ array, and $n$ and $M$ are the number of players and the number of colors, respectively." }, "is_english": true, "time_complexity": "O(m + n \\times M)", "space_complexity": "O(n \\times M)" }, { "problem_id": 3239, "explanations": { "1": "We separately count the number of flips for rows and columns, denoted as $\\textit{cnt1}$ and $\\textit{cnt2}$, respectively. Finally, we take the minimum of the two.\n\nThe time complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns of the matrix $\\textit{grid}$, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": null }, { "problem_id": 3240, "explanations": { "1": "If both rows and columns are palindromic, then for any $i \\in [0, m / 2)$ and $j \\in [0, n / 2)$, it must satisfy $\\text{grid}[i][j] = \\text{grid}[m - i - 1][j] = \\text{grid}[i][n - j - 1] = \\text{grid}[m - i - 1][n - j - 1]$. They must either all become $0$ or all become $1$. The number of changes to $0$ is $c_0 = \\text{grid}[i][j] + \\text{grid}[m - i - 1][j] + \\text{grid}[i][n - j - 1] + \\text{grid}[m - i - 1][n - j - 1]$, and the number of changes to $1$ is $c_1 = 4 - c_0$. We take the minimum of the two and add it to the answer.\n\nNext, we discuss the parity of $m$ and $n$:\n\n- If both $m$ and $n$ are even, we directly return the answer.\n- If both $m$ and $n$ are odd, the center cell must be $0$ because the number of $1$s must be divisible by $4$.\n- If $m$ is odd and $n$ is even, we need to consider the middle row.\n- If $m$ is even and $n$ is odd, we need to consider the middle column.\n\nFor the latter two cases, we need to count the number of differing pairs of cells $\\text{diff}$ in the middle row or column, and the number of cells that are the same and equal to $1$ $\\text{cnt1}$. Then we discuss the following cases:\n\n- If $\\text{cnt1} \\bmod 4 = 0$, we only need to change the $\\text{diff}$ cells to $0$, and the number of operations is $\\text{diff }$.\n- Otherwise, if $\\text{cnt1} = 2$, if $\\text{diff} \\gt 0$, we can change one of the cells to $1$ to make $\\text{cnt1} = 4$, and then change the remaining $\\text{diff} - 1$ cells to $0$. The total number of operations is $\\text{diff}$.\n- Otherwise, if $\\text{diff} = 0$, we change the $2$ cells to $0$ to make $\\text{cnt1} \\bmod 4 = 0$, and the number of operations is $2$.\n\nWe add the number of operations to the answer and finally return the answer.\n\nThe time complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns of the matrix, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(1)" }, { "problem_id": 3241, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3242, "explanations": { "1": "We can use a hash table $\\textit{d}$ to store the coordinates of each element. Then, according to the problem description, we separately calculate the sum of adjacent elements and diagonally adjacent elements.\n\nIn terms of time complexity, initializing the hash table has a time complexity of $O(m \\times n)$, and calculating the sum of adjacent elements and diagonally adjacent elements has a time complexity of $O(1)$. The space complexity is $O(m \\times n)$." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 3243, "explanations": { "1": "We first build a directed graph $\\textit{g}$, where $\\textit{g}[i]$ represents the list of cities that can be reached from city $i$. Initially, each city $i$ has a one-way road to city $i + 1$.\n\nThen, for each query $[u, v]$, we add $v$ to the list of reachable cities from $u$, and then use BFS to find the shortest path length from city $0$ to city $n - 1$, adding the result to the answer array.\n\nFinally, we return the answer array.\n\nThe time complexity is $O(q \\times (n + q))$, and the space complexity is $O(n + q)$. Here, $n$ and $q$ are the number of cities and the number of queries, respectively." }, "is_english": true, "time_complexity": "O(q \\times (n + q))", "space_complexity": "O(n + q)" }, { "problem_id": 3244, "explanations": { "1": "We define an array $\\textit{nxt}$ of length $n - 1$, where $\\textit{nxt}[i]$ represents the next city that can be reached from city $i$. Initially, $\\textit{nxt}[i] = i + 1$.\n\nFor each query $[u, v]$, if $u'$ and $v'$ have already been connected before, and $u' \\leq u < v \\leq v'$, then we can skip this query. Otherwise, we need to set the next city number for cities from $\\textit{nxt}[u]$ to $\\textit{nxt}[v - 1]$ to $0$, and set $\\textit{nxt}[u]$ to $v$.\n\nDuring this process, we maintain a variable $\\textit{cnt}$, which represents the length of the shortest path from city $0$ to city $n - 1$. Initially, $\\textit{cnt} = n - 1$. Each time we set the next city number for cities in $[\\textit{nxt}[u], \\textit{v})$ to $0$, $\\textit{cnt}$ decreases by $1$.\n\nTime complexity is $O(n + q)$, and space complexity is $O(n)$. Here, $n$ and $q$ are the number of cities and the number of queries, respectively." }, "is_english": true, "time_complexity": "O(n + q)", "space_complexity": "O(n)" }, { "problem_id": 3245, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3246, "explanations": { "1": "We can use the `RANK()` window function to calculate the ranking of the teams, and then sort by score and team name." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3247, "explanations": { "1": "We define $f[0]$ to represent the number of subsequences with an even sum so far, and $f[1]$ to represent the number of subsequences with an odd sum so far. Initially, $f[0] = 0$ and $f[1] = 0$.\n\nTraverse the array $\\textit{nums}$, for each number $x$:\n\nIf $x$ is odd, the update rules for $f[0]$ and $f[1]$ are:\n\n$$\n\\begin{aligned}\nf[0] & = (f[0] + f[1]) \\bmod 10^9 + 7, \\\\\nf[1] & = (f[0] + f[1] + 1) \\bmod 10^9 + 7.\n\\end{aligned}\n$$\n\nThat is, the current number of subsequences with an even sum is equal to the previous number of subsequences with an even sum plus the number of subsequences with an odd sum concatenated with the current number $x$; the current number of subsequences with an odd sum is equal to the previous number of subsequences with an even sum concatenated with the current number $x$ plus the previous number of subsequences with an odd sum, plus one subsequence containing only the current number $x$.\n\nIf $x$ is even, the update rules for $f[0]$ and $f[1]$ are:\n\n$$\n\\begin{aligned}\nf[0] & = (f[0] + f[0] + 1) \\bmod 10^9 + 7, \\\\\nf[1] & = (f[1] + f[1]) \\bmod 10^9 + 7.\n\\end{aligned}\n$$\n\nThat is, the current number of subsequences with an even sum is equal to the previous number of subsequences with an even sum plus the number of subsequences with an even sum concatenated with the current number $x$, plus one subsequence containing only the current number $x$; the current number of subsequences with an odd sum is equal to the previous number of subsequences with an odd sum concatenated with the current number $x$ plus the previous number of subsequences with an odd sum.\n\nFinally, return $f[1]$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3248, "explanations": { "1": "We can use two variables $x$ and $y$ to represent the position of the snake. Initially, $x = y = 0$. Then, we traverse $\\textit{commands}$ and update the values of $x$ and $y$ based on the current command. Finally, we return $x \\times n + y$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{commands}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3249, "explanations": { "1": "First, we construct the adjacency list $\\textit{g}$ of the tree based on the given edges $\\textit{edges}$, where $\\textit{g}[a]$ represents all the neighboring nodes of node $a$.\n\nNext, we design a function $\\textit{dfs}(a, \\textit{fa})$ to calculate the number of nodes in the subtree rooted at node $a$ and to accumulate the count of good nodes. Here, $\\textit{fa}$ represents the parent node of node $a$.\n\nThe execution process of the function $\\textit{dfs}(a, \\textit{fa})$ is as follows:\n\n1. Initialize variables $\\textit{pre} = -1$, $\\textit{cnt} = 1$, $\\textit{ok} = 1$, representing the number of nodes in a subtree of node $a$, the total number of nodes in all subtrees of node $a$, and whether node $a$ is a good node, respectively.\n2. Traverse all neighboring nodes $b$ of node $a$. If $b$ is not equal to $\\textit{fa}$, recursively call $\\textit{dfs}(b, a)$, with the return value being $\\textit{cur}$, and add $\\textit{cur}$ to $\\textit{cnt}$. If $\\textit{pre} < 0$, assign $\\textit{cur}$ to $\\textit{pre}$; otherwise, if $\\textit{pre}$ is not equal to $\\textit{cur}$, it means the number of nodes in different subtrees of node $a$ is different, and set $\\textit{ok}$ to $0$.\n3. Finally, add $\\textit{ok}$ to the answer and return $\\textit{cnt}$.\n\nIn the main function, we call $\\textit{dfs}(0, -1)$ and return the final answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ represents the number of nodes." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3250, "explanations": { "1": "We define $f[i][j]$ to represent the number of monotonic array pairs for the subarray $[0, \\ldots, i]$ where $arr1[i] = j$. Initially, $f[i][j] = 0$, and the answer is $\\sum_{j=0}^{\\textit{nums}[n-1]} f[n-1][j]$.\n\nWhen $i = 0$, we have $f[0][j] = 1$ for $0 \\leq j \\leq \\textit{nums}[0]$.\n\nWhen $i > 0$, we can calculate $f[i][j]$ based on $f[i-1][j']$. Since $\\textit{arr1}$ is non-decreasing, $j' \\leq j$. Additionally, since $\\textit{arr2}$ is non-increasing, $\\textit{nums}[i] - j \\leq \\textit{nums}[i - 1] - j'$. Thus, $j' \\leq \\min(j, j + \\textit{nums}[i - 1] - \\textit{nums}[i])$.\n\nThe answer is $\\sum_{j=0}^{\\textit{nums}[n-1]} f[n-1][j]$.\n\nThe time complexity is $O(n \\times m)$, and the space complexity is $O(n \\times m)$. Here, $n$ represents the length of the array $\\textit{nums}$, and $m$ represents the maximum value in the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times m)", "space_complexity": "O(n \\times m)" }, { "problem_id": 3251, "explanations": { "1": "We define $f[i][j]$ to represent the number of monotonic array pairs for the subarray $[0, \\ldots, i]$ where $arr1[i] = j$. Initially, $f[i][j] = 0$, and the answer is $\\sum_{j=0}^{\\textit{nums}[n-1]} f[n-1][j]$.\n\nWhen $i = 0$, we have $f[0][j] = 1$ for $0 \\leq j \\leq \\textit{nums}[0]$.\n\nWhen $i > 0$, we can calculate $f[i][j]$ based on $f[i-1][j']$. Since $\\textit{arr1}$ is non-decreasing, $j' \\leq j$. Additionally, since $\\textit{arr2}$ is non-increasing, $\\textit{nums}[i] - j \\leq \\textit{nums}[i - 1] - j'$. Thus, $j' \\leq \\min(j, j + \\textit{nums}[i - 1] - \\textit{nums}[i])$.\n\nThe answer is $\\sum_{j=0}^{\\textit{nums}[n-1]} f[n-1][j]$.\n\nThe time complexity is $O(n \\times m)$, and the space complexity is $O(n \\times m)$. Here, $n$ represents the length of the array $\\textit{nums}$, and $m$ represents the maximum value in the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times m)", "space_complexity": "O(n \\times m)" }, { "problem_id": 3252, "explanations": { "1": "We can use the window function `RANK()` to calculate each team's points, ranking, and the total number of teams. Then, we can use the `CASE WHEN` statement to determine the grade of each team." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3253, "explanations": { "1": "We first create a Trie $\\textit{trie}$, where each node in the Trie contains an array $\\textit{children}$ of length $26$, and each element in the array is a pointer to the next node. Each node in the Trie also contains a $\\textit{cost}$ variable, which represents the minimum cost from the root node to the current node.\n\nWe traverse the $\\textit{words}$ array, inserting each word into the Trie while updating the $\\textit{cost}$ variable for each node.\n\nNext, we define a memoized search function $\\textit{dfs}(i)$, which represents the minimum cost to construct the string starting from $\\textit{target}[i]$. The answer is $\\textit{dfs}(0)$.\n\nThe calculation process of the function $\\textit{dfs}(i)$ is as follows:\n\n- If $i \\geq \\textit{len}(\\textit{target})$, it means the entire string has been constructed, so return $0$.\n- Otherwise, we start from the root node of the $\\textit{trie}$ and traverse all suffixes starting from $\\textit{target}[i]$, finding the minimum cost, which is the $\\textit{cost}$ variable in the $\\textit{trie}$, plus the result of $\\textit{dfs}(j+1)$, where $j$ is the ending position of the suffix starting from $\\textit{target}[i]$.\n\nFinally, if $\\textit{dfs}(0) < \\textit{inf}$, return $\\textit{dfs}(0)$; otherwise, return $-1$.\n\nThe time complexity is $O(n^2 + L)$, and the space complexity is $O(n + L)$. Here, $n$ is the length of $\\textit{target}$, and $L$ is the sum of the lengths of all words in the $\\textit{words}$ array." }, "is_english": true, "time_complexity": "O(n^2 + L)", "space_complexity": "O(n + L)" }, { "problem_id": 3254, "explanations": { "1": "We define an array $f$, where $f[i]$ represents the length of the continuous increasing subsequence ending at the $i$-th element. Initially, $f[i] = 1$.\n\nNext, we traverse the array $\\textit{nums}$ to calculate the values of the array $f$. If $nums[i] = nums[i - 1] + 1$, then $f[i] = f[i - 1] + 1$; otherwise, $f[i] = 1$.\n\nThen, we traverse the array $f$ in the range $[k - 1, n)$. If $f[i] \\ge k$, we add $\\textit{nums}[i]$ to the answer array; otherwise, we add $-1$.\n\nAfter the traversal, we return the answer array.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ represents the length of the array $\\textit{nums}$.", "2": "" }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3255, "explanations": { "1": "We define an array $f$, where $f[i]$ represents the length of the continuous increasing subsequence ending at the $i$-th element. Initially, $f[i] = 1$.\n\nNext, we traverse the array $\\textit{nums}$ to calculate the values of the array $f$. If $nums[i] = nums[i - 1] + 1$, then $f[i] = f[i - 1] + 1$; otherwise, $f[i] = 1$.\n\nThen, we traverse the array $f$ in the range $[k - 1, n)$. If $f[i] \\ge k$, we add $\\textit{nums}[i]$ to the answer array; otherwise, we add $-1$.\n\nAfter the traversal, we return the answer array.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ represents the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3256, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3257, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3258, "explanations": { "1": "We use two variables $\\textit{cnt0}$ and $\\textit{cnt1}$ to record the number of $0$s and $1$s in the current window, respectively. We use $\\textit{ans}$ to record the number of substrings that satisfy the $k$ constraint, and $l$ to record the left boundary of the window.\n\nWhen we move the window to the right, if the number of $0$s and $1$s in the window both exceed $k$, we need to move the window to the left until the number of $0$s and $1$s in the window are both no greater than $k$. At this point, all substrings in the window satisfy the $k$ constraint, and the number of such substrings is $r - l + 1$, where $r$ is the right boundary of the window. We add this count to $\\textit{ans}$.\n\nFinally, we return $\\textit{ans}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3259, "explanations": { "1": "We define $f[i][0]$ to represent the maximum boost energy obtained by choosing energy drink A at the $i$-th hour, and $f[i][1]$ to represent the maximum boost energy obtained by choosing energy drink B at the $i$-th hour. Initially, $f[0][0] = \\textit{energyDrinkA}[0]$, $f[0][1] = \\textit{energyDrinkB}[0]$. The answer is $\\max(f[n - 1][0], f[n - 1][1])$.\n\nFor $i > 0$, we have the following state transition equations:\n\n$$\n\\begin{aligned}\nf[i][0] & = \\max(f[i - 1][0] + \\textit{energyDrinkA}[i], f[i - 1][1]) \\\\\nf[i][1] & = \\max(f[i - 1][1] + \\textit{energyDrinkB}[i], f[i - 1][0])\n\\end{aligned}\n$$\n\nFinally, return $\\max(f[n - 1][0], f[n - 1][1])$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array.", "2": "We notice that the state $f[i]$ is only related to $f[i - 1]$ and not to $f[i - 2]$. Therefore, we can use only two variables $f$ and $g$ to maintain the state, thus optimizing the space complexity to $O(1)$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3260, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3261, "explanations": { "1": "We use two variables $\\textit{cnt0}$ and $\\textit{cnt1}$ to record the number of $0$s and $1$s in the current window, respectively. Pointers $i$ and $j$ mark the left and right boundaries of the window. We use an array $d$ to record the first position to the right of each position $i$ that does not satisfy the $k$ constraint, initially setting $d[i] = n$. Additionally, we use a prefix sum array $\\textit{pre}[i]$ of length $n + 1$ to record the number of substrings that satisfy the $k$ constraint with the right boundary at position $i$.\n\nWhen we move the window to the right, if the number of $0$s and $1$s in the window both exceed $k$, we update $d[i]$ to $j$, indicating that the first position to the right of $i$ that does not satisfy the $k$ constraint is $j$. Then we move $i$ one position to the right until the number of $0$s and $1$s in the window are both less than or equal to $k$. At this point, we can calculate the number of substrings that satisfy the $k$ constraint with the right boundary at $j$, which is $j - i + 1$, and update this in the prefix sum array.\n\nFinally, for each query $[l, r]$, we first find the first position $p$ to the right of $l$ that does not satisfy the $k$ constraint, which is $p = \\min(r + 1, d[l])$. All substrings in the range $[l, p - 1]$ satisfy the $k$ constraint, and the number of such substrings is $(1 + p - l) \\times (p - l) / 2$. Then, we calculate the number of substrings that satisfy the $k$ constraint with the right boundary in the range $[p, r]$, which is $\\textit{pre}[r + 1] - \\textit{pre}[p]$. Finally, we add the two results together.\n\nThe time complexity is $O(n + m)$, and the space complexity is $O(n)$. Here, $n$ and $m$ are the lengths of the string $s$ and the query array $\\textit{queries}$, respectively." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(n)" }, { "problem_id": 3262, "explanations": { "1": "We first use a self-join to connect the `EmployeeShifts` table to itself. The join condition ensures that we only compare shifts belonging to the same employee and check if there is any overlap between shifts.\n\n1. `t1.start_time < t2.start_time`: Ensures that the start time of the first shift is earlier than the start time of the second shift.\n2. `t1.end_time > t2.start_time`: Ensures that the end time of the first shift is later than the start time of the second shift.\n\nNext, we group the data by `employee_id` and count the number of overlapping shifts for each employee.\n\nFinally, we filter out employees with overlapping shift counts greater than $0$ and sort the results in ascending order by `employee_id`." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3263, "explanations": { "1": "We can directly traverse the linked list, adding the values of the nodes to the answer array $\\textit{ans}$ one by one.\n\nAfter the traversal is complete, return the answer array $\\textit{ans}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the linked list. Ignoring the space consumption of the answer array, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3264, "explanations": { "1": "We can use a min-heap to maintain the elements in the array $\\textit{nums}$. Each time, we extract the minimum value from the min-heap, multiply it by $\\textit{multiplier}$, and then put it back into the min-heap. During the implementation, we insert the indices of the elements into the min-heap and define a custom comparator function to sort the min-heap based on the values of the elements in $\\textit{nums}$ as the primary key and the indices as the secondary key.\n\nFinally, we return the array $\\textit{nums}$.\n\nThe time complexity is $O((n + k) \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O((n + k) \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3265, "explanations": { "1": "We can enumerate each number, and for each number, we can enumerate each pair of different digits, then swap these two digits to get a new number. We record this new number in a hash table $s$, representing all possible numbers after at most one swap. Then, we count how many numbers previously enumerated are in the hash table $s$ and add this count to the answer. Next, we add the currently enumerated number to the hash table $\\textit{cnt}$, representing the count of the current number.\n\nThis enumeration method may miss some pairs, such as $[100, 1]$, because the number obtained by swapping digits in $100$ is $1$, and previously enumerated numbers do not include $1$, thus missing some pairs. We can solve this problem by sorting the array before enumeration.\n\nThe time complexity is $O(n \\times (\\log n + \\log^3 M))$, and the space complexity is $O(n + \\log^2 M)$. Here, $n$ is the length of the array $\\textit{nums}$, and $M$ is the maximum value in the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times (\\log n + \\log^3 M))", "space_complexity": "O(n + \\log^2 M)" }, { "problem_id": 3266, "explanations": { "1": "Let the length of the array $\\textit{nums}$ be $n$, and the maximum value be $m$.\n\nWe first use a priority queue (min-heap) to simulate the operations until we complete $k$ operations or all elements in the heap are greater than or equal to $m$.\n\nAt this point, all elements in the array are less than $m \\times \\textit{multiplier}$. Since $1 \\leq m \\leq 10^9$ and $1 \\leq \\textit{multiplier} \\leq 10^6$, $m \\times \\textit{multiplier} \\leq 10^{15}$, which is within the range of a 64-bit integer.\n\nNext, each operation will turn the smallest element in the array into the largest element. Therefore, after every $n$ consecutive operations, each element in the array will have undergone exactly one multiplication operation.\n\nThus, after the simulation, for the remaining $k$ operations, the smallest $k \\bmod n$ elements in the array will undergo $\\lfloor k / n \\rfloor + 1$ multiplication operations, while the other elements will undergo $\\lfloor k / n \\rfloor$ multiplication operations.\n\nFinally, we multiply each element in the array by the corresponding number of multiplication operations and take the result modulo $10^9 + 7$. This can be calculated using fast exponentiation.\n\nThe time complexity is $O(n \\times \\log n \\times \\log M + n \\times \\log k)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$, and $M$ is the maximum value in the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n \\times \\log M + n \\times \\log k)", "space_complexity": "O(n)" }, { "problem_id": 3267, "explanations": { "1": "We can enumerate each number, and for each number, we can enumerate each pair of different digits, then swap these two digits to get a new number. Record this new number in a hash table $\\textit{vis}$, representing all possible numbers after at most one swap. Then continue to enumerate each pair of different digits, swap these two digits to get a new number, and record it in the hash table $\\textit{vis}$, representing all possible numbers after at most two swaps.\n\nThis enumeration may miss some pairs of numbers, such as $[100, 1]$, because the number obtained after swapping $100$ is $1$, and the previously enumerated numbers do not include $1$, so some pairs of numbers will be missed. We only need to sort the array before enumeration to solve this problem.\n\nThe time complexity is $O(n \\times (\\log n + \\log^5 M))$, and the space complexity is $O(n + \\log^4 M)$. Here, $n$ is the length of the array $\\textit{nums}$, and $M$ is the maximum value in the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times (\\log n + \\log^5 M))", "space_complexity": "O(n + \\log^4 M)" }, { "problem_id": 3268, "explanations": { "1": "We can merge all the `start_time` and `end_time` for each `employee_id` and store them in table `T`. Then, by using the `LEAD` function, we calculate the next time period for each `employee_id` and store it in table `P`.\n\nNext, we can join table `P` with the `EmployeeShifts` table to calculate the `concurrent_count` for each `employee_id`, which represents the number of overlapping time periods. This is stored in table `S`.\n\nFinally, we can perform a self-join on the `EmployeeShifts` table to calculate the `total_overlap_duration` for each `employee_id`, representing the total overlapping time, and store it in table `U`.\n\nUltimately, we can join tables `S` and `U` to calculate the `max_overlapping_shifts` and `total_overlap_duration` for each `employee_id`.\n\nSimilar Problems:\n\n- [3156. Employee Task Duration and Concurrent Tasks 🔒](https://github.com/doocs/leetcode/blob/main/solution/3100-3199/3156.Employee%20Task%20Duration%20and%20Concurrent%20Tasks/README_EN.md)\n- [3262. Find Overlapping Shifts 🔒](https://github.com/doocs/leetcode/blob/main/solution/3200-3299/3262.Find%20Overlapping%20Shifts/README_EN.md)" }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3269, "explanations": { "1": "We define $f[i][j]$ to represent the minimum of the maximum values among the first $i$ elements of array $\\textit{nums1}$ and the first $j$ elements of array $\\textit{nums2}$. Initially, $f[i][j] = 0$, and the answer is $f[m][n]$, where $m$ and $n$ are the lengths of arrays $\\textit{nums1}$ and $\\textit{nums2}$, respectively.\n\nIf $j = 0$, then the value of $f[i][0]$ can only be derived from $f[i - 1][0]$, with the transition equation $f[i][0] = \\textit{nxt}(f[i - 1][0], \\textit{nums1}[i - 1])$, where $\\textit{nxt}(x, y)$ represents the smallest integer greater than $x$ that has the same parity as $y$.\n\nIf $i = 0$, then the value of $f[0][j]$ can only be derived from $f[0][j - 1]$, with the transition equation $f[0][j] = \\textit{nxt}(f[0][j - 1], \\textit{nums2}[j - 1])$.\n\nIf $i > 0$ and $j > 0$, then the value of $f[i][j]$ can be derived from both $f[i - 1][j]$ and $f[i][j - 1]$, with the transition equation $f[i][j] = \\min(\\textit{nxt}(f[i - 1][j], \\textit{nums1}[i - 1]), \\textit{nxt}(f[i][j - 1], \\textit{nums2}[j - 1]))$.\n\nFinally, return $f[m][n]$.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the lengths of arrays $\\textit{nums1}$ and $\\textit{nums2}$, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 3270, "explanations": { "1": "We can directly simulate this process by defining a variable $\\textit{ans}$ to store the answer and a variable $\\textit{k}$ to represent the current digit place, where $\\textit{k} = 1$ represents the units place, $\\textit{k} = 10$ represents the tens place, and so on.\n\nStarting from the units place, for each digit place, we calculate the current digit of $\\textit{num1}$, $\\textit{num2}$, and $\\textit{num3}$, take the minimum of the three, and then add this minimum value multiplied by $\\textit{k}$ to the answer. Then, multiply $\\textit{k}$ by 10 and continue to the next digit place.\n\nFinally, return the answer.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 3271, "explanations": { "1": "We can simulate the process according to the steps described in the problem.\n\nTraverse the string $s$, and each time take $k$ characters, calculate the sum of their hash values, denoted as $t$. Then, take $t$ modulo $26$ to find the corresponding character and add it to the end of the result string.\n\nFinally, return the result string.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. Ignoring the space consumption of the answer string, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3272, "explanations": { "1": "We can consider enumerating all palindromic numbers of length $n$ and checking whether they are $k$-palindromic numbers. Due to the properties of palindromic numbers, we only need to enumerate the first half of the digits and then reverse and append them to form the full number.\n\nThe length of the first half of the digits is $\\lfloor \\frac{n - 1}{2} \\rfloor$, so the range of the first half is $[10^{\\lfloor \\frac{n - 1}{2} \\rfloor}, 10^{\\lfloor \\frac{n - 1}{2} \\rfloor + 1})$. We can reverse the first half and append it to form a palindromic number of length $n$. Note that if $n$ is odd, the middle digit needs special handling.\n\nNext, we check whether the palindromic number is $k$-palindromic. If it is, we count all unique permutations of the number. To avoid duplicates, we can use a set $\\textit{vis}$ to store the smallest permutation of each palindromic number that has already been processed. If the smallest permutation of the current palindromic number is already in the set, we skip it. Otherwise, we calculate the number of unique permutations of the palindromic number and add it to the result.\n\nWe can use an array $\\textit{cnt}$ to count the occurrences of each digit and use combinatorics to calculate the number of permutations. Specifically, if digit $0$ appears $x_0$ times, digit $1$ appears $x_1$ times, ..., and digit $9$ appears $x_9$ times, the number of permutations of the palindromic number is:\n\n$$\n\\frac{(n - x_0) \\cdot (n - 1)!}{x_0! \\cdot x_1! \\cdots x_9!}\n$$\n\nHere, $(n - x_0)$ represents the number of choices for the highest digit (excluding $0$), $(n - 1)!$ represents the permutations of the remaining digits, and we divide by the factorial of the occurrences of each digit to avoid duplicates.\n\nFinally, we sum up all the permutation counts to get the final result.\n\nTime complexity is $O(10^m \\times n \\times \\log n)$, and space complexity is $O(10^m \\times n)$, where $m = \\lfloor \\frac{n - 1}{2} \\rfloor$." }, "is_english": true, "time_complexity": "O(10^m \\times n \\times \\log n)", "space_complexity": "O(10^m \\times n)" }, { "problem_id": 3273, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3274, "explanations": { "1": "We calculate the differences in the x-coordinates and y-coordinates of the two points. If the sum of these differences is even, then the colors of the squares at these two coordinates are the same; otherwise, they are different.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 3275, "explanations": { "1": "We can use a priority queue (max-heap) to maintain the $k$ obstacles closest to the origin.\n\nTraverse $\\textit{queries}$, and for each query, calculate the sum of the absolute values of $x$ and $y$, then add it to the priority queue. If the size of the priority queue exceeds $k$, pop the top element. If the current size of the priority queue is equal to $k$, add the top element to the answer array; otherwise, add $-1$ to the answer array.\n\nAfter the traversal, return the answer array.\n\nThe time complexity is $O(n \\times \\log k)$, and the space complexity is $O(k)$. Here, $n$ is the length of the array $\\textit{queries}$." }, "is_english": true, "time_complexity": "O(n \\times \\log k)", "space_complexity": "O(k)" }, { "problem_id": 3276, "explanations": { "1": "We define $f[i][j]$ to represent the maximum score when selecting numbers from $[1,..i]$ and the state of the rows corresponding to the selected numbers is $j$. Initially, $f[i][j] = 0$, and the answer is $f[\\textit{mx}][2^m - 1]$, where $\\textit{mx}$ represents the maximum value in the matrix, and $m$ represents the number of rows in the matrix.\n\nFirst, we preprocess the matrix using a hash table $g$ to record the set of rows corresponding to each number. Then, we can use state compression dynamic programming to solve the problem.\n\nFor the state $f[i][j]$, we can choose not to select the number $i$, in which case $f[i][j] = f[i-1][j]$. Alternatively, we can choose the number $i$. In this case, we need to enumerate each row $k$ in the set $g[i]$ corresponding to the number $i$. If the $k$-th bit of $j$ is $1$, it means we can select the number $i$. Thus, $f[i][j] = \\max(f[i][j], f[i-1][j \\oplus 2^k] + i)$.\n\nFinally, we return $f[\\textit{mx}][2^m - 1]$.\n\nThe time complexity is $O(m \\times 2^m \\times \\textit{mx})$, and the space complexity is $O(\\textit{mx} \\times 2^m)$. Here, $m$ is the number of rows in the matrix, and $\\textit{mx}$ is the maximum value in the matrix." }, "is_english": true, "time_complexity": "O(m \\times 2^m \\times \\textit{mx})", "space_complexity": "O(\\textit{mx} \\times 2^m)" }, { "problem_id": 3277, "explanations": { "1": "We define $f[i][j]$ to represent the XOR value of $\\textit{nums}[i..j]$. According to the problem description, we can derive the state transition equation:\n\n$$\nf[i][j] = f[i][j-1] \\oplus f[i+1][j]\n$$\n\nwhere $\\oplus$ denotes the XOR operation.\n\nWe further define $g[i][j]$ to represent the maximum value of $f[i][j]$. The state transition equation is:\n\n$$\ng[i][j] = \\max(f[i][j], g[i][j-1], g[i+1][j])\n$$\n\nFinally, we traverse the query array. For each query $[l, r]$, we add $g[l][r]$ to the answer array.\n\nThe time complexity is $O(n^2 + m)$, and the space complexity is $O(n^2)$. Here, $n$ and $m$ are the lengths of the arrays $\\textit{nums}$ and $\\textit{queries}$, respectively." }, "is_english": true, "time_complexity": "O(n^2 + m)", "space_complexity": "O(n^2)" }, { "problem_id": 3278, "explanations": { "1": "We can perform an equi-join of the `Candidates` table and the `Projects` table on the `skill` column, counting the number of matched skills and calculating the total score for each candidate in each project, which is recorded in table `S`.\n\nNext, we count the required number of skills for each project, recording the results in table `T`.\n\nThen, we perform an equi-join of tables `S` and `T` on the `project_id` column, filtering out candidates whose number of matched skills equals the required number of skills, and recording them in table `P`. We calculate the rank (`rk`) for each candidate within each project.\n\nFinally, we filter out the candidates with rank $rk = 1$ for each project, identifying them as the best candidates." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3279, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3280, "explanations": { "1": "We first split the string $\\textit{date}$ by `-`, then convert each part to its binary representation, and finally join these three parts with `-`.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $\\textit{date}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3281, "explanations": { "1": "We can first sort the $\\textit{start}$ array. Then, we consider selecting integers from left to right, where the score is equal to the minimum difference between any two adjacent selected integers.\n\nIf a difference $x$ satisfies the condition, then any $x' < x$ will also satisfy the condition. Therefore, we can use binary search to find the largest difference that satisfies the condition.\n\nWe define the left boundary of the binary search as $l = 0$ and the right boundary as $r = \\textit{start}[-1] + d - \\textit{start}[0]$. Each time, we take the middle value $mid = \\left\\lfloor \\frac{l + r + 1}{2} \\right\\rfloor$ and check whether it satisfies the condition.\n\nWe define a function $\\text{check}(mi)$ to determine whether the condition is satisfied, implemented as follows:\n\n- We define a variable $\\textit{last} = -\\infty$, representing the last selected integer.\n- We traverse the $\\textit{start}$ array. If $\\textit{last} + \\textit{mi} > \\textit{st} + d$, it means we cannot select the integer $\\textit{st}$, and we return $\\text{false}$. Otherwise, we update $\\textit{last} = \\max(\\textit{st}, \\textit{last} + \\textit{mi})$.\n- If we traverse the entire $\\textit{start}$ array and all conditions are satisfied, we return $\\text{true}$.\n\nThe time complexity is $O(n \\times \\log M)$, where $n$ and $M$ are the length and the maximum value of the $\\textit{start}$ array, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(1)" }, { "problem_id": 3282, "explanations": { "1": "Suppose we jump from index $i$ to index $j$, then the score is $(j - i) \\times \\text{nums}[i]$. This is equivalent to taking $j - i$ steps, and each step earns a score of $\\text{nums}[i]$. Then we continue to jump from $j$ to the next index $k$, and the score is $(k - j) \\times \\text{nums}[j]$, and so on. If $\\text{nums}[i] \\gt \\text{nums}[j]$, then we should not jump from $i$ to $j$, because the score obtained this way is definitely less than the score obtained by jumping directly from $i$ to $k$. Therefore, each time we should jump to the next index with a value greater than the current index.\n\nWe can maintain a variable $mx$ to represent the maximum value of $\\text{nums}[i]$ encountered so far. Then we traverse the array from left to right until the second-to-last element, updating $mx$ each time and accumulating the score.\n\nAfter the traversal, the result is the maximum total score.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\text{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3283, "explanations": { "1": "First, we preprocess the shortest distance for each pawn to any position on the chessboard and record it in the array $\\textit{dist}$, where $\\textit{dist}[i][x][y]$ represents the shortest distance for the $i$-th pawn to the position $(x, y)$.\n\nNext, we design a function $\\text{dfs}(\\textit{last}, \\textit{state}, \\textit{k})$, where $\\textit{last}$ represents the number of the last pawn eaten, $\\textit{state}$ represents the current state of the remaining pawns, and $\\textit{k}$ represents whether it is Alice's or Bob's turn. The function returns the maximum number of moves for the current turn. The answer is $\\text{dfs}(n, 2^n-1, 1)$. Here, initially, the number of the last pawn eaten is $n$, which is also the position of the knight.\n\nThe specific implementation of the function $\\text{dfs}$ is as follows:\n\n- If $\\textit{state} = 0$, it means there are no pawns left, return $0$;\n- If $\\textit{k} = 1$, it means it is Alice's turn. We need to find a pawn such that the number of moves after eating this pawn is maximized, i.e., $\\text{dfs}(i, \\textit{state} \\oplus 2^i, \\textit{k} \\oplus 1) + \\textit{dist}[\\textit{last}][x][y]$;\n- If $\\textit{k} = 0$, it means it is Bob's turn. We need to find a pawn such that the number of moves after eating this pawn is minimized, i.e., $\\text{dfs}(i, \\textit{state} \\oplus 2^i, \\textit{k} \\oplus 1) + \\textit{dist}[\\textit{last}][x][y]$.\n\nTo avoid repeated calculations, we use memoization, i.e., using a hash table to record the states that have already been calculated.\n\nThe time complexity is $O(n \\times m^2 + 2^n \\times n^2)$, and the space complexity is $O(n \\times m^2 + 2^n \\times n)$. Here, $n$ and $m$ represent the number of pawns and the size of the chessboard, respectively." }, "is_english": true, "time_complexity": "O(n \\times m^2 + 2^n \\times n^2)", "space_complexity": "O(n \\times m^2 + 2^n \\times n)" }, { "problem_id": 3284, "explanations": { "1": "We define two variables $f$ and $g$, representing the length of the increasing subarray ending at the current element and the length of the decreasing subarray ending at the current element, respectively. We use two other variables $s$ and $t$ to represent the sum of the increasing subarray ending at the current element and the sum of the decreasing subarray ending at the current element, respectively. Initially, $f = g = 1$, and $s = t = \\textit{nums}[0]$.\n\nNext, we traverse the array starting from the second element. For the current element $\\textit{nums}[i]$, we consider the increasing subarray and the decreasing subarray ending at $\\textit{nums}[i]$.\n\nIf $\\textit{nums}[i] - \\textit{nums}[i - 1] = 1$, then $\\textit{nums}[i]$ can be added to the increasing subarray ending at $\\textit{nums}[i - 1]$. In this case, we update $f$ and $s$, and add $s$ to the answer.\n\nIf $\\textit{nums}[i] - \\textit{nums}[i - 1] = -1$, then $\\textit{nums}[i]$ can be added to the decreasing subarray ending at $\\textit{nums}[i - 1]$. In this case, we update $g$ and $t$, and add $t$ to the answer.\n\nOtherwise, $\\textit{nums}[i]$ cannot be added to the increasing or decreasing subarray ending at $\\textit{nums}[i - 1]$. We add $\\textit{nums}[i]$ to the answer.\n\nAfter the traversal, return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3285, "explanations": { "1": "We directly traverse the mountains starting from index $1$. If the height of the mountain to its left is greater than $threshold$, we add its index to the result array.\n\nAfter the traversal, we return the result array.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{height}$. Ignoring the space consumption of the result array, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3286, "explanations": { "1": "We define a 2D array $\\textit{dist}$, where $\\textit{dist}[i][j]$ represents the minimum health value required to reach position $(i, j)$ from the top-left corner. Initially, we set $\\textit{dist}[0][0]$ to $\\textit{grid}[0][0]$ and add $(0, 0)$ to the queue $\\textit{q}$.\n\nThen, we continuously take elements $(x, y)$ from the queue and try to move in four directions. If we move to a valid position $(nx, ny)$ and the health value required to move from $(x, y)$ to $(nx, ny)$ is smaller, we update $\\textit{dist}[nx][ny] = \\textit{dist}[x][y] + \\textit{grid}[nx][ny]$ and add $(nx, ny)$ to the queue $\\textit{q}$.\n\nFinally, when the queue is empty, we obtain $\\textit{dist}[m-1][n-1]$, which is the minimum health value required to reach the bottom-right corner from the top-left corner. If this value is less than $\\textit{health}$, then we can reach the bottom-right corner; otherwise, we cannot.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the number of rows and columns of the grid, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 3287, "explanations": { "1": "We consider dividing the sequence into two parts, the first $k$ elements and the last $k$ elements, and calculate all possible XOR values for the prefixes and suffixes.\n\nDefine $f[i][j][x]$ to represent whether there exists a subset with an XOR value of $x$ by taking $j$ elements from the first $i$ elements. Define $g[i][j][y]$ to represent whether there exists a subset with an XOR value of $y$ by taking $j$ elements starting from index $i$.\n\nConsider the transition equation for $f[i][j][x]$. For the $i$-th element (starting from $0$), we can choose to take it or not, so we have:\n\n$$\nf[i + 1][j][x] = f[i + 1][j][x] \\lor f[i][j][x] \\\\\nf[i + 1][j + 1][x \\lor \\text{nums}[i]] = f[i + 1][j + 1][x \\lor \\text{nums}[i]] \\lor f[i][j][x]\n$$\n\nFor the transition equation of $g[i][j][y]$, similarly for the $i$-th element (starting from $n - 1$), we can choose to take it or not, so we have:\n\n$$\ng[i - 1][j][y] = g[i - 1][j][y] \\lor g[i][j][y] \\\\\ng[i - 1][j + 1][y \\lor \\text{nums}[i - 1]] = g[i - 1][j + 1][y \\lor \\text{nums}[i - 1]] \\lor g[i][j][y]\n$$\n\nFinally, we enumerate $i$ in the range $[k, n - k]$. For each $i$, we enumerate $x$ and $y$, where $0 \\leq x, y < 2^7$. If both $f[i][k][x]$ and $g[i][k][y]$ are true, we update the answer $\\text{ans} = \\max(\\text{ans}, x \\oplus y)$.\n\nThe time complexity is $O(n \\times m \\times k)$, and the space complexity is $O(n \\times m \\times k)$, where $n$ is the length of the array, and $m = 2^7$." }, "is_english": true, "time_complexity": "O(n \\times m \\times k)", "space_complexity": "O(n \\times m \\times k)" }, { "problem_id": 3288, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3289, "explanations": { "1": "We can use an array $\\textit{cnt}$ to record the number of occurrences of each number.\n\nTraverse the array $\\textit{nums}$, and when a number appears for the second time, add it to the answer array.\n\nAfter the traversal, return the answer array.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$.", "2": "Let the length of array $\\textit{nums}$ be $n + 2$, which contains integers from $0$ to $n - 1$, with two numbers appearing twice.\n\nWe can find these two numbers using XOR operations. First, we perform XOR operations on all numbers in array $\\textit{nums}$ and the integers from $0$ to $n - 1$. The result is the XOR value of the two duplicate numbers, denoted as $xx$.\n\nNext, we can find certain characteristics of these two numbers through $xx$ and separate them. The specific steps are as follows:\n\n1. Find the position of the lowest bit or highest bit with value $1$ in the binary representation of $xx$, denoted as $k$. This position indicates that the two numbers differ at this bit.\n2. Based on the value of the $k$-th bit, divide the numbers in array $\\textit{nums}$ and the integers from $0$ to $n - 1$ into two groups: one group with $0$ at the $k$-th bit, and another group with $1$ at the $k$-th bit. Then perform XOR operations on these two groups separately, and the results are the two duplicate numbers.\n\nThe time complexity is $O(n)$, where $n$ is the length of array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3290, "explanations": { "1": "We design a function $\\textit{dfs}(i, j)$, which represents the maximum score that can be obtained starting from the $i$-th element of array $a$ and the $j$-th element of array $b$. Then the answer is $\\textit{dfs}(0, 0)$.\n\nThe function $\\textit{dfs}(i, j)$ is calculated as follows:\n\n- If $j \\geq \\text{len}(b)$, it means array $b$ has been completely traversed. At this point, if array $a$ has also been completely traversed, return $0$; otherwise, return negative infinity.\n- If $i \\geq \\text{len}(a)$, it means array $a$ has been completely traversed. Return $0$.\n- Otherwise, we can either skip the $j$-th element of array $b$ and move to the next element, i.e., $\\textit{dfs}(i, j + 1)$; or we can choose the $j$-th element of array $b$, in which case the score is $a[i] \\times b[j]$ plus $\\textit{dfs}(i + 1, j + 1)$. We take the maximum of these two values as the return value of $\\textit{dfs}(i, j)$.\n\nWe can use memoization to avoid redundant calculations.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the lengths of arrays $a$ and $b$, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 3291, "explanations": { "1": "We can use a trie to store all valid strings and then use memoization to calculate the answer.\n\nWe design a function $\\textit{dfs}(i)$, which represents the minimum number of strings needed to concatenate starting from the $i$-th character of the string $\\textit{target}$. The answer is $\\textit{dfs}(0)$.\n\nThe function $\\textit{dfs}(i)$ is calculated as follows:\n\n- If $i \\geq n$, it means the string $\\textit{target}$ has been completely traversed, so we return $0$;\n- Otherwise, we can find valid strings in the trie that start with $\\textit{target}[i]$, and then recursively calculate $\\textit{dfs}(i + \\text{len}(w))$, where $w$ is the valid string found. We take the minimum of these values and add $1$ as the return value of $\\textit{dfs}(i)$.\n\nTo avoid redundant calculations, we use memoization.\n\nThe time complexity is $O(n^2 + L)$, and the space complexity is $O(n + L)$. Here, $n$ is the length of the string $\\textit{target}$, and $L$ is the total length of all valid strings." }, "is_english": true, "time_complexity": "O(n^2 + L)", "space_complexity": "O(n + L)" }, { "problem_id": 3292, "explanations": { "1": "Due to the large data scale of this problem, using the \"Trie + Memoization\" method will time out. We need to find a more efficient solution.\n\nConsider starting from the $i$-th character of the string $\\textit{target}$ and finding the maximum matching substring length, denoted as $\\textit{dist}$. For any $j \\in [i, i + \\textit{dist} - 1]$, we can find a string in $\\textit{words}$ such that $\\textit{target}[i..j]$ is a prefix of this string. This has a monotonic property, so we can use binary search to determine $\\textit{dist}$.\n\nSpecifically, we first preprocess the hash values of all prefixes of strings in $\\textit{words}$ and store them in the array $\\textit{s}$ grouped by prefix length. Additionally, we preprocess the hash values of $\\textit{target}$ and store them in $\\textit{hashing}$ to facilitate querying the hash value of any $\\textit{target}[l..r]$.\n\nNext, we design a function $\\textit{f}(i)$ to represent the maximum matching substring length starting from the $i$-th character of the string $\\textit{target}$. We can determine $\\textit{f}(i)$ using binary search.\n\nDefine the left boundary of the binary search as $l = 0$ and the right boundary as $r = \\min(n - i, m)$, where $n$ is the length of the string $\\textit{target}$ and $m$ is the maximum length of strings in $\\textit{words}$. During the binary search, we need to check if $\\textit{target}[i..i+\\textit{mid}-1]$ is one of the hash values in $\\textit{s}[\\textit{mid}]$. If it is, update the left boundary $l$ to $\\textit{mid}$; otherwise, update the right boundary $r$ to $\\textit{mid} - 1$. After the binary search, return $l$.\n\nAfter calculating $\\textit{f}(i)$, the problem becomes a classic greedy problem. Starting from $i = 0$, for each position $i$, the farthest position we can move to is $i + \\textit{f}(i)$. We need to find the minimum number of moves to reach the end.\n\nWe define $\\textit{last}$ to represent the last moved position and $\\textit{mx}$ to represent the farthest position we can move to from the current position. Initially, $\\textit{last} = \\textit{mx} = 0$. We traverse from $i = 0$. If $i$ equals $\\textit{last}$, it means we need to move again. If $\\textit{last} = \\textit{mx}$, it means we cannot move further, so we return $-1$. Otherwise, we update $\\textit{last}$ to $\\textit{mx}$ and increment the answer by one.\n\nAfter the traversal, return the answer.\n\nThe time complexity is $O(n \\times \\log n + L)$, and the space complexity is $O(n + L)$. Here, $n$ is the length of the string $\\textit{target}$, and $L$ is the total length of all valid strings." }, "is_english": true, "time_complexity": "O(n \\times \\log n + L)", "space_complexity": "O(n + L)" }, { "problem_id": 3293, "explanations": { "1": "We can perform a left join between the `Products` table and the `Discounts` table on the `category` column, then calculate the final price. If a product's category does not have an associated discount, its price remains unchanged." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3294, "explanations": { "1": "We can start from the given node and traverse the linked list backward until we reach the head node. Then, we traverse the linked list forward from the head node, adding the values of the nodes we encounter to the answer array.\n\nAfter the traversal is complete, return the answer array.\n\nThe time complexity is $O(n)$, where $n$ is the number of nodes in the linked list. Ignoring the space consumption of the answer array, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3295, "explanations": { "1": "We use a hash table $s$ to store all the words in $\\textit{bannedWords}$. Then, we traverse each word in $\\textit{message}$. If the word appears in the hash table $s$, we increment the counter $cnt$ by one. If $cnt$ is greater than or equal to $2$, we return $\\text{true}$; otherwise, we return $\\text{false}$.\n\nThe time complexity is $O((n + m) \\times |w|)$, and the space complexity is $O(m \\times |w|)$. Here, $n$ is the length of the array $\\textit{message}$, and $m$ and $|w|$ are the length of the array $\\textit{bannedWords}$ and the maximum length of the words in the array, respectively." }, "is_english": true, "time_complexity": "O((n + m) \\times |w|)", "space_complexity": "O(m \\times |w|)" }, { "problem_id": 3296, "explanations": { "1": "We notice that if all workers can reduce the mountain height to $0$ in $t$ seconds, then for any $t' > t$, the workers can also reduce the mountain height to $0$ in $t'$ seconds. Therefore, we can use binary search to find the minimum $t$ such that the workers can reduce the mountain height to $0$ in $t$ seconds.\n\nWe define a function $\\textit{check}(t)$, which indicates whether the workers can reduce the mountain height to $0$ in $t$ seconds. Specifically, we iterate through each worker. For the current worker $\\textit{workerTimes}[i]$, assuming they reduce the height by $h'$ in $t$ seconds, we can derive the inequality:\n\n$$\n\\left(1 + h'\\right) \\cdot \\frac{h'}{2} \\cdot \\textit{workerTimes}[i] \\leq t\n$$\n\nSolving the inequality, we get:\n\n$$\nh' \\leq \\left\\lfloor \\sqrt{\\frac{2t}{\\textit{workerTimes}[i]} + \\frac{1}{4}} - \\frac{1}{2} \\right\\rfloor\n$$\n\nWe can sum up all the $h'$ values for the workers to get the total reduced height $h$. If $h \\geq \\textit{mountainHeight}$, it means the workers can reduce the mountain height to $0$ in $t$ seconds.\n\nNext, we determine the left boundary of the binary search $l = 1$. Since there is at least one worker, and each worker's working time does not exceed $10^6$, to reduce the mountain height to $0$, it takes at least $(1 + \\textit{mountainHeight}) \\cdot \\textit{mountainHeight} / 2 \\cdot \\textit{workerTimes}[i] \\leq 10^{16}$ seconds. Therefore, we can set the right boundary of the binary search to $r = 10^{16}$. Then, we continuously halve the interval $[l, r]$ until $l = r$. At this point, $l$ is the answer.\n\nThe time complexity is $O(n \\times \\log M)$, where $n$ is the number of workers, and $M$ is the right boundary of the binary search, which is $10^{16}$ in this problem. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(1)" }, { "problem_id": 3297, "explanations": { "1": "The problem is essentially to find how many substrings in $\\textit{word1}$ contain all the characters in $\\textit{word2}$. We can use a sliding window to handle this.\n\nFirst, if the length of $\\textit{word1}$ is less than the length of $\\textit{word2}$, then it is impossible for $\\textit{word1}$ to contain all the characters of $\\textit{word2}$, so we directly return $0$.\n\nNext, we use a hash table or an array of length $26$ called $\\textit{cnt}$ to count the occurrences of characters in $\\textit{word2}$. Then, we use $\\textit{need}$ to record how many more characters are needed to meet the condition, initialized to the length of $\\textit{cnt}$.\n\nWe then use a sliding window $\\textit{win}$ to record the occurrences of characters in the current window. We use $\\textit{ans}$ to record the number of substrings that meet the condition, and $\\textit{l}$ to record the left boundary of the window.\n\nWe traverse each character in $\\textit{word1}$. For the current character $c$, we add it to $\\textit{win}$. If the value of $\\textit{win}[c]$ equals $\\textit{cnt}[c]$, it means the current window already contains one of the characters in $\\textit{word2}$, so we decrement $\\textit{need}$ by one. If $\\textit{need}$ equals $0$, it means the current window contains all the characters in $\\textit{word2}$. We need to shrink the left boundary of the window until $\\textit{need}$ is greater than $0$. Specifically, if $\\textit{win}[\\textit{word1}[l]]$ equals $\\textit{cnt}[\\textit{word1}[l]]$, it means the current window contains one of the characters in $\\textit{word2}$. After shrinking the left boundary, it no longer meets the condition, so we increment $\\textit{need}$ by one and decrement $\\textit{win}[\\textit{word1}[l]]$ by one. Then, we increment $\\textit{l}$ by one. At this point, the window is $[l, r]$. For any $0 \\leq l' < l$, $[l', r]$ are substrings that meet the condition, and there are $l$ such substrings, which we add to the answer.\n\nAfter traversing all characters in $\\textit{word1}$, we get the answer.\n\nThe time complexity is $O(n + m)$, where $n$ and $m$ are the lengths of $\\textit{word1}$ and $\\textit{word2}$, respectively. The space complexity is $O(|\\Sigma|)$, where $\\Sigma$ is the character set. Here, it is the set of lowercase letters, so the space complexity is constant." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 3298, "explanations": { "1": "The problem is essentially to find how many substrings in $\\textit{word1}$ contain all the characters in $\\textit{word2}$. We can use a sliding window to handle this.\n\nFirst, if the length of $\\textit{word1}$ is less than the length of $\\textit{word2}$, then it is impossible for $\\textit{word1}$ to contain all the characters of $\\textit{word2}$, so we directly return $0$.\n\nNext, we use a hash table or an array of length $26$ called $\\textit{cnt}$ to count the occurrences of characters in $\\textit{word2}$. Then, we use $\\textit{need}$ to record how many more characters are needed to meet the condition, initialized to the length of $\\textit{cnt}$.\n\nWe then use a sliding window $\\textit{win}$ to record the occurrences of characters in the current window. We use $\\textit{ans}$ to record the number of substrings that meet the condition, and $\\textit{l}$ to record the left boundary of the window.\n\nWe traverse each character in $\\textit{word1}$. For the current character $c$, we add it to $\\textit{win}$. If the value of $\\textit{win}[c]$ equals $\\textit{cnt}[c]$, it means the current window already contains one of the characters in $\\textit{word2}$, so we decrement $\\textit{need}$ by one. If $\\textit{need}$ equals $0$, it means the current window contains all the characters in $\\textit{word2}$. We need to shrink the left boundary of the window until $\\textit{need}$ is greater than $0$. Specifically, if $\\textit{win}[\\textit{word1}[l]]$ equals $\\textit{cnt}[\\textit{word1}[l]]$, it means the current window contains one of the characters in $\\textit{word2}$. After shrinking the left boundary, it no longer meets the condition, so we increment $\\textit{need}$ by one and decrement $\\textit{win}[\\textit{word1}[l]]$ by one. Then, we increment $\\textit{l}$ by one. At this point, the window is $[l, r]$. For any $0 \\leq l' < l$, $[l', r]$ are substrings that meet the condition, and there are $l$ such substrings, which we add to the answer.\n\nAfter traversing all characters in $\\textit{word1}$, we get the answer.\n\nThe time complexity is $O(n + m)$, where $n$ and $m$ are the lengths of $\\textit{word1}$ and $\\textit{word2}$, respectively. The space complexity is $O(|\\Sigma|)$, where $\\Sigma$ is the character set. Here, it is the set of lowercase letters, so the space complexity is constant." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 3299, "explanations": { "1": "Let us count how many times each element $\\textit{nums}[i]$ appears in a continuous subsequence of length greater than 1. Then, multiplying this count by $\\textit{nums}[i]$ gives the contribution of $\\textit{nums}[i]$ in all continuous subsequences of length greater than 1. We sum these contributions, and adding the sum of all elements, we get the answer.\n\nWe can first compute the contribution of strictly increasing subsequences, then the contribution of strictly decreasing subsequences, and finally add the sum of all elements.\n\nTo implement this, we define a function $\\textit{calc}(\\textit{nums})$, where $\\textit{nums}$ is an array. This function returns the sum of all continuous subsequences of length greater than 1 in $\\textit{nums}$.\n\nIn the function, we can use two arrays, $\\textit{left}$ and $\\textit{right}$, to record the number of strictly increasing subsequences ending with $\\textit{nums}[i] - 1$ on the left of each element $\\textit{nums}[i]$, and the number of strictly increasing subsequences starting with $\\textit{nums}[i] + 1$ on the right of each element $\\textit{nums}[i]$. In this way, we can calculate the contribution of $\\textit{nums}$ in all continuous subsequences of length greater than 1 in $O(n)$ time complexity.\n\nIn the main function, we first call $\\textit{calc}(\\textit{nums})$ to compute the contribution of strictly increasing subsequences, then reverse $\\textit{nums}$ and call $\\textit{calc}(\\textit{nums})$ again to compute the contribution of strictly decreasing subsequences. Finally, adding the sum of all elements gives the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3300, "explanations": { "1": "We can traverse the array $\\textit{nums}$. For each number $x$, we calculate the sum of its digits $y$. The minimum value among all $y$ is the answer.\n\nThe time complexity is $O(n \\times \\log M)$, where $n$ and $M$ are the length of the array $\\textit{nums}$ and the maximum value in the array, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(1)" }, { "problem_id": 3301, "explanations": { "1": "We can sort the maximum heights of the towers in descending order, then allocate the heights one by one starting from the maximum height. Use a variable $mx$ to record the current maximum allocated height.\n\nIf the current height $x$ is greater than $mx - 1$, update $x$ to $mx - 1$. If $x$ is less than or equal to $0$, it means the height cannot be allocated, and we directly return $-1$. Otherwise, we add $x$ to the answer and update $mx$ to $x$.\n\nFinally, return the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array $\\textit{maximumHeight}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 3302, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3303, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3304, "explanations": { "1": "We can use an array $\\textit{word}$ to store the string after each operation. When the length of $\\textit{word}$ is less than $k$, we continuously perform operations on $\\textit{word}$.\n\nFinally, return $\\textit{word}[k - 1]$.\n\nThe time complexity is $O(k)$, and the space complexity is $O(k)$. Here, $k$ is the input parameter." }, "is_english": true, "time_complexity": "O(k)", "space_complexity": "O(k)" }, { "problem_id": 3305, "explanations": { "1": "We can transform the problem into solving the following two subproblems:\n\n1. Find the total number of substrings where each vowel appears at least once and contains at least $k$ consonants, denoted as $\\textit{f}(k)$;\n2. Find the total number of substrings where each vowel appears at least once and contains at least $k + 1$ consonants, denoted as $\\textit{f}(k + 1)$.\n\nThen the answer is $\\textit{f}(k) - \\textit{f}(k + 1)$.\n\nTherefore, we design a function $\\textit{f}(k)$ to count the total number of substrings where each vowel appears at least once and contains at least $k$ consonants.\n\nWe can use a hash table $\\textit{cnt}$ to count the occurrences of each vowel, a variable $\\textit{ans}$ to store the answer, a variable $\\textit{l}$ to record the left boundary of the sliding window, and a variable $\\textit{x}$ to record the number of consonants in the current window.\n\nTraverse the string. If the current character is a vowel, add it to the hash table $\\textit{cnt}$; otherwise, increment $\\textit{x}$ by one. If $\\textit{x} \\ge k$ and the size of the hash table $\\textit{cnt}$ is $5$, it means the current window meets the conditions. We then move the left boundary in a loop until the window no longer meets the conditions. At this point, all substrings ending at the right boundary $\\textit{r}$ and with the left boundary in the range $[0, .. \\textit{l} - 1]$ meet the conditions, totaling $\\textit{l}$ substrings. We add $\\textit{l}$ to the answer. Continue traversing the string until the end, and we get $\\textit{f}(k)$.\n\nFinally, we return $\\textit{f}(k) - \\textit{f}(k + 1)$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $\\textit{word}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3306, "explanations": { "1": "We can transform the problem into solving the following two subproblems:\n\n1. Find the total number of substrings where each vowel appears at least once and contains at least $k$ consonants, denoted as $\\textit{f}(k)$;\n2. Find the total number of substrings where each vowel appears at least once and contains at least $k + 1$ consonants, denoted as $\\textit{f}(k + 1)$.\n\nThen the answer is $\\textit{f}(k) - \\textit{f}(k + 1)$.\n\nTherefore, we design a function $\\textit{f}(k)$ to count the total number of substrings where each vowel appears at least once and contains at least $k$ consonants.\n\nWe can use a hash table $\\textit{cnt}$ to count the occurrences of each vowel, a variable $\\textit{ans}$ to store the answer, a variable $\\textit{l}$ to record the left boundary of the sliding window, and a variable $\\textit{x}$ to record the number of consonants in the current window.\n\nTraverse the string. If the current character is a vowel, add it to the hash table $\\textit{cnt}$; otherwise, increment $\\textit{x}$ by one. If $\\textit{x} \\ge k$ and the size of the hash table $\\textit{cnt}$ is $5$, it means the current window meets the conditions. We then move the left boundary in a loop until the window no longer meets the conditions. At this point, all substrings ending at the right boundary $\\textit{r}$ and with the left boundary in the range $[0, .. \\textit{l} - 1]$ meet the conditions, totaling $\\textit{l}$ substrings. We add $\\textit{l}$ to the answer. Continue traversing the string until the end, and we get $\\textit{f}(k)$.\n\nFinally, we return $\\textit{f}(k) - \\textit{f}(k + 1)$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $\\textit{word}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3307, "explanations": { "1": "Since the length of the string doubles after each operation, if we perform $i$ operations, the length of the string will be $2^i$.\n\nWe can simulate this process to find the first string length $n$ that is greater than or equal to $k$.\n\nNext, we backtrack and discuss the following cases:\n\n- If $k \\gt n / 2$, it means $k$ is in the second half. If $\\textit{operations}[i - 1] = 1$, it means the character at position $k$ is obtained by adding $1$ to the character in the first half. We add $1$ to it. Then we update $k$ to $k - n / 2$.\n- If $k \\le n / 2$, it means $k$ is in the first half and is not affected by $\\textit{operations}[i - 1]$.\n- Next, we update $n$ to $n / 2$ and continue backtracking until $n = 1$.\n\nFinally, we take the resulting number modulo $26$ and add the ASCII code of `'a'` to get the answer.\n\nThe time complexity is $O(\\log k)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log k)", "space_complexity": "O(1)" }, { "problem_id": 3308, "explanations": { "1": "We can use equi-join to join the `Drivers` table with the `Vehicles` table on `driver_id`, and then join with the `Trips` table on `vehicle_id`. Next, we group by `fuel_type` and `driver_id` to calculate each driver's average rating, total mileage, and total accident count. Then, using the `RANK()` window function, we rank the drivers of each fuel type in descending order of rating, descending order of total mileage, and ascending order of total accident count. Finally, we filter out the driver ranked 1 for each fuel type." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3309, "explanations": { "1": "According to the problem description, the length of the array $\\textit{nums}$ is $3$. We can enumerate all permutations of $\\textit{nums}$, which has $3! = 6$ permutations. Then, we convert the elements of the permuted array into binary strings, concatenate these binary strings, and finally convert the concatenated binary string into a decimal number to get the maximum value.\n\nThe time complexity is $O(\\log M)$, where $M$ represents the maximum value of the elements in $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log M)", "space_complexity": "O(1)" }, { "problem_id": 3310, "explanations": { "1": "We can start from $k$ and find all suspicious methods, recording them in the array $\\textit{suspicious}$. Then, we traverse from $0$ to $n-1$, starting from all non-suspicious methods, and mark all reachable methods as non-suspicious. Finally, we return all non-suspicious methods.\n\nThe time complexity is $O(n + m)$, and the space complexity is $O(n + m)$. Here, $n$ and $m$ represent the number of methods and the number of call relationships, respectively." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(n + m)" }, { "problem_id": 3311, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3312, "explanations": { "1": "We can preprocess to obtain the occurrence count of the greatest common divisor (GCD) of all pairs in the array $\\textit{nums}$, recorded in the array $\\textit{cntG}$. Then, we calculate the prefix sum of the array $\\textit{cntG}$. Finally, for each query, we can use binary search to find the index of the first element in the array $\\textit{cntG}$ that is greater than $\\textit{queries}[i]$, which is the answer.\n\nLet $\\textit{mx}$ denote the maximum value in the array $\\textit{nums}$, and let $\\textit{cnt}$ record the occurrence count of each number in the array $\\textit{nums}$. Let $\\textit{cntG}[i]$ denote the number of pairs in the array $\\textit{nums}$ whose GCD is equal to $i$. To calculate $\\textit{cntG}[i]$, we can follow these steps:\n\n1. Calculate the occurrence count $v$ of multiples of $i$ in the array $\\textit{nums}$. Then, the number of pairs formed by any two elements from these multiples must have a GCD that is a multiple of $i$, i.e., $\\textit{cntG}[i]$ needs to be increased by $v \\times (v - 1) / 2$;\n2. We need to exclude pairs whose GCD is a multiple of $i$ and greater than $i$. Therefore, for multiples $j$ of $i$, we need to subtract $\\textit{cntG}[j]$.\n\nThe above steps require us to traverse $i$ from large to small so that when calculating $\\textit{cntG}[i]$, we have already calculated all $\\textit{cntG}[j]$.\n\nFinally, we calculate the prefix sum of the array $\\textit{cntG}$, and for each query, we can use binary search to find the index of the first element in the array $\\textit{cntG}$ that is greater than $\\textit{queries}[i]$, which is the answer.\n\nThe time complexity is $O(n + (M + q) \\times \\log M)$, and the space complexity is $O(M)$. Here, $n$ and $M$ represent the length and the maximum value of the array $\\textit{nums}$, respectively, and $q$ represents the number of queries." }, "is_english": true, "time_complexity": "O(n + (M + q) \\times \\log M)", "space_complexity": "O(M)" }, { "problem_id": 3313, "explanations": { "1": "According to the problem description, the last marked node must be one endpoint of the tree's diameter, because the distance from any node on the diameter to any other node on the diameter is the greatest.\n\nWe can start a depth-first search (DFS) from any node to find the farthest node $a$, which is one endpoint of the tree's diameter.\n\nThen, starting from node $a$, we perform another depth-first search to find the farthest node $b$, which is the other endpoint of the tree's diameter. During this process, we calculate the distance from each node to node $a$, denoted as $\\textit{dist2}$.\n\nNext, we perform a depth-first search starting from node $b$ to calculate the distance from each node to node $b$, denoted as $\\textit{dist3}$.\n\nFor each node $i$, if $\\textit{dist2}[i] > $\\textit{dist3}[i]$, then the distance from node $a$ to node $i$ is greater, so node $a$ is the last marked node; otherwise, node $b$ is the last marked node.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3314, "explanations": { "1": "For an integer $a$, the result of $a \\lor (a + 1)$ is always odd. Therefore, if $\\text{nums[i]}$ is even, then $\\text{ans}[i]$ does not exist, and we directly return $-1$. In this problem, $\\textit{nums}[i]$ is a prime number, so to check if it is even, we only need to check if it equals $2$.\n\nIf $\\text{nums[i]}$ is odd, suppose $\\text{nums[i]} = \\text{0b1101101}$. Since $a \\lor (a + 1) = \\text{nums[i]}$, this is equivalent to changing the last $0$ bit of $a$ to $1$. To solve for $a$, we need to change the bit after the last $0$ in $\\text{nums[i]}$ to $0$. We start traversing from the least significant bit (index $1$) and find the first $0$ bit. If it is at position $i$, we change the $(i - 1)$-th bit of $\\text{nums[i]}$ to $1$, i.e., $\\text{ans}[i] = \\text{nums[i]} \\oplus 2^{i - 1}$.\n\nBy traversing all elements in $\\text{nums}$, we can obtain the answer.\n\nThe time complexity is $O(n \\times \\log M)$, where $n$ and $M$ are the length of the array $\\text{nums}$ and the maximum value in the array, respectively. Ignoring the space consumption of the answer array, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(1)" }, { "problem_id": 3315, "explanations": { "1": "For an integer $a$, the result of $a \\lor (a + 1)$ is always odd. Therefore, if $\\text{nums[i]}$ is even, then $\\text{ans}[i]$ does not exist, and we directly return $-1$. In this problem, $\\textit{nums}[i]$ is a prime number, so to check if it is even, we only need to check if it equals $2$.\n\nIf $\\text{nums[i]}$ is odd, suppose $\\text{nums[i]} = \\text{0b1101101}$. Since $a \\lor (a + 1) = \\text{nums[i]}$, this is equivalent to changing the last $0$ bit of $a$ to $1$. To solve for $a$, we need to change the bit after the last $0$ in $\\text{nums[i]}$ to $0$. We start traversing from the least significant bit (index $1$) and find the first $0$ bit. If it is at position $i$, we change the $(i - 1)$-th bit of $\\text{nums[i]}$ to $1$, i.e., $\\text{ans}[i] = \\text{nums[i]} \\oplus 2^{i - 1}$.\n\nBy traversing all elements in $\\text{nums}$, we can obtain the answer.\n\nThe time complexity is $O(n \\times \\log M)$, where $n$ and $M$ are the length of the array $\\text{nums}$ and the maximum value in the array, respectively. Ignoring the space consumption of the answer array, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(1)" }, { "problem_id": 3316, "explanations": { "1": "We define $f[i][j]$ to represent the maximum number of deletions in the first $i$ characters of $\\textit{source}$ that match the first $j$ characters of $\\textit{pattern}$. Initially, $f[0][0] = 0$, and the rest $f[i][j] = -\\infty$.\n\nFor $f[i][j]$, we have two choices:\n\n- We can skip the $i$-th character of $\\textit{source}$, in which case $f[i][j] = f[i-1][j] + \\text{int}(i-1 \\in \\textit{targetIndices})$;\n- If $\\textit{source}[i-1] = \\textit{pattern}[j-1]$, we can match the $i$-th character of $\\textit{source}$, in which case $f[i][j] = \\max(f[i][j], f[i-1][j-1])$.\n\nThe final answer is $f[m][n]$.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$. Here, $m$ and $n$ are the lengths of $\\textit{source}$ and $\\textit{pattern}$, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 3317, "explanations": { "1": "We define $f[i][j]$ to represent the number of ways to arrange the first $i$ performers into $j$ programs. Initially, $f[0][0] = 1$, and the rest $f[i][j] = 0$.\n\nFor $f[i][j]$, where $1 \\leq i \\leq n$ and $1 \\leq j \\leq x$, we consider the $i$-th performer:\n\n- If the performer is assigned to a program that already has performers, there are $j$ choices, i.e., $f[i - 1][j] \\times j$;\n- If the performer is assigned to a program that has no performers, there are $x - (j - 1)$ choices, i.e., $f[i - 1][j - 1] \\times (x - (j - 1))$.\n\nSo the state transition equation is:\n\n$$\nf[i][j] = f[i - 1][j] \\times j + f[i - 1][j - 1] \\times (x - (j - 1))\n$$\n\nFor each $j$, there are $y^j$ choices, so the final answer is:\n\n$$\n\\sum_{j = 1}^{x} f[n][j] \\times y^j\n$$\n\nNote that since the answer can be very large, we need to take the modulo $10^9 + 7$.\n\nThe time complexity is $O(n \\times x)$, and the space complexity is $O(n \\times x)$. Here, $n$ and $x$ represent the number of performers and the number of programs, respectively." }, "is_english": true, "time_complexity": "O(n \\times x)", "space_complexity": "O(n \\times x)" }, { "problem_id": 3318, "explanations": { "1": "We use a hash table $\\textit{cnt}$ to count the occurrences of each element in the window, an ordered set $\\textit{l}$ to store the $x$ elements with the highest occurrences in the window, and another ordered set $\\textit{r}$ to store the remaining elements.\n\nWe maintain a variable $\\textit{s}$ to represent the sum of the elements in $\\textit{l}$. Initially, we add the first $k$ elements to the window, update the ordered sets $\\textit{l}$ and $\\textit{r}$, and calculate the value of $\\textit{s}$. If the size of $\\textit{l}$ is less than $x$ and $\\textit{r}$ is not empty, we repeatedly move the largest element from $\\textit{r}$ to $\\textit{l}$ until the size of $\\textit{l}$ equals $x$, updating the value of $\\textit{s}$ in the process. If the size of $\\textit{l}$ is greater than $x$, we repeatedly move the smallest element from $\\textit{l}$ to $\\textit{r}$ until the size of $\\textit{l}$ equals $x$, updating the value of $\\textit{s}$ in the process. At this point, we can calculate the current window's $\\textit{x-sum}$ and add it to the answer array. Then we remove the left boundary element of the window, update $\\textit{cnt}$, and update the ordered sets $\\textit{l}$ and $\\textit{r}$, as well as the value of $\\textit{s}$. Continue traversing the array until the traversal is complete.\n\nThe time complexity is $O(n \\times \\log k)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$.\n\nSimilar problems:\n\n- [3013. Divide an Array Into Subarrays With Minimum Cost II](/solution/3000-3099/3013.Divide%20an%20Array%20Into%20Subarrays%20With%20Minimum%20Cost%20II/README_EN.md)" }, "is_english": true, "time_complexity": "O(n \\times \\log k)", "space_complexity": "O(n)" }, { "problem_id": 3319, "explanations": { "1": "We define a function $\\textit{dfs}$ to calculate the size of the perfect binary subtree rooted at the current node, using an array $\\textit{nums}$ to record the sizes of all perfect binary subtrees. If the subtree rooted at the current node is not a perfect binary subtree, it returns $-1$.\n\nThe execution process of the function $\\textit{dfs}$ is as follows:\n\n1. If the current node is null, return $0$;\n2. Recursively calculate the sizes of the perfect binary subtrees of the left and right subtrees, denoted as $l$ and $r$ respectively;\n3. If the sizes of the left and right subtrees are not equal, or if the sizes of the left and right subtrees are less than $0$, return $-1$;\n4. Calculate the size of the perfect binary subtree rooted at the current node $\\textit{cnt} = l + r + 1$, and add $\\textit{cnt}$ to the array $\\textit{nums}$;\n5. Return $\\textit{cnt}$.\n\nWe call the $\\textit{dfs}$ function to calculate the sizes of all perfect binary subtrees. If the length of the array $\\textit{nums}$ is less than $k$, return $-1$. Otherwise, sort the array $\\textit{nums}$ in descending order and return the $k$-th largest perfect binary subtree size.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3320, "explanations": { "1": "We design a function $\\textit{dfs}(i, j, k)$, where $i$ represents starting from the $i$-th character of the string $s$, $j$ represents the current score difference between $\\textit{Alice}$ and $\\textit{Bob}$, and $k$ represents the last creature summoned by $\\textit{Bob}$. The function calculates how many sequences of moves $\\textit{Bob}$ can make to defeat $\\textit{Alice}$.\n\nThe answer is $\\textit{dfs}(0, 0, -1)$, where $-1$ indicates that $\\textit{Bob}$ has not summoned any creatures yet. In languages other than Python, since the score difference can be negative, we can add $n$ to the score difference to ensure it is non-negative.\n\nThe calculation process of the function $\\textit{dfs}(i, j, k)$ is as follows:\n\n- If $n - i \\leq j$, then the remaining rounds are not enough for $\\textit{Bob}$ to surpass $\\textit{Alice}$'s score, so return $0$.\n- If $i \\geq n$, then all rounds have ended. If $\\textit{Bob}$'s score is less than $0$, return $1$; otherwise, return $0$.\n- Otherwise, we enumerate the creatures $\\textit{Bob}$ can summon this round. If the creature summoned this round is the same as the one summoned in the previous round, $\\textit{Bob}$ cannot win this round, so we skip it. Otherwise, we recursively calculate $\\textit{dfs}(i + 1, j + \\textit{calc}(d[s[i]], l), l)$, where $\\textit{calc}(x, y)$ represents the outcome between $x$ and $y$, and $d$ is a mapping that maps characters to $\\textit{012}$. We sum all the results and take the modulo $10^9 + 7$.\n\nThe time complexity is $O(n^2 \\times k^2)$, where $n$ is the length of the string $s$, and $k$ represents the size of the character set. The space complexity is $O(n^2 \\times k)$." }, "is_english": true, "time_complexity": "O(n^2 \\times k^2)", "space_complexity": "O(n^2 \\times k)" }, { "problem_id": 3321, "explanations": { "1": "We use a hash table $\\textit{cnt}$ to count the occurrences of each element in the window, an ordered set $\\textit{l}$ to store the $x$ elements with the highest occurrences in the window, and another ordered set $\\textit{r}$ to store the remaining elements.\n\nWe maintain a variable $\\textit{s}$ to represent the sum of the elements in $\\textit{l}$. Initially, we add the first $k$ elements to the window, update the ordered sets $\\textit{l}$ and $\\textit{r}$, and calculate the value of $\\textit{s}$. If the size of $\\textit{l}$ is less than $x$ and $\\textit{r}$ is not empty, we repeatedly move the largest element from $\\textit{r}$ to $\\textit{l}$ until the size of $\\textit{l}$ equals $x$, updating the value of $\\textit{s}$ in the process. If the size of $\\textit{l}$ is greater than $x$, we repeatedly move the smallest element from $\\textit{l}$ to $\\textit{r}$ until the size of $\\textit{l}$ equals $x$, updating the value of $\\textit{s}$ in the process. At this point, we can calculate the current window's $\\textit{x-sum}$ and add it to the answer array. Then we remove the left boundary element of the window, update $\\textit{cnt}$, and update the ordered sets $\\textit{l}$ and $\\textit{r}$, as well as the value of $\\textit{s}$. Continue traversing the array until the traversal is complete.\n\nThe time complexity is $O(n \\times \\log k)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$.\n\nSimilar problems:\n\n- [3013. Divide an Array Into Subarrays With Minimum Cost II](/solution/3000-3099/3013.Divide%20an%20Array%20Into%20Subarrays%20With%20Minimum%20Cost%20II/README_EN.md)" }, "is_english": true, "time_complexity": "O(n \\times \\log k)", "space_complexity": "O(n)" }, { "problem_id": 3322, "explanations": { "1": "We can use the window function `RANK()` to rank the teams by grouping them by season and sorting based on points, goal difference, and team name.\n\nFinally, we just need to sort by `season_id`, `position`, and `team_name`." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3323, "explanations": { "1": "First, we sort the given set of intervals $\\textit{intervals}$ by their left endpoints, then merge all overlapping intervals to obtain a new set of intervals $\\textit{merged}$.\n\nWe can then set the initial answer to the length of $\\textit{merged}$.\n\nNext, we enumerate each interval $[\\_, e]$ in $\\textit{merged}$. Using binary search, we find the first interval in $\\textit{merged}$ whose left endpoint is greater than or equal to $e + k + 1$, and let its index be $j$. We can then update the answer as $\\textit{ans} = \\min(\\textit{ans}, |\\textit{merged}| - (j - i - 1))$.\n\nFinally, we return the answer $\\textit{ans}$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the number of intervals." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3324, "explanations": { "1": "We can simulate Alice's typing process, starting from an empty string and updating the string after each keystroke until the target string is obtained.\n\nThe time complexity is $O(n^2 \\times |\\Sigma|)$, where $n$ is the length of the target string and $\\Sigma$ is the character set, which in this case is the set of lowercase letters, so $|\\Sigma| = 26$." }, "is_english": true, "time_complexity": "O(n^2 \\times |\\Sigma|)", "space_complexity": null }, { "problem_id": 3325, "explanations": { "1": "We can enumerate the right endpoint of the substring, and then use a sliding window to maintain the left endpoint of the substring, ensuring that the occurrence count of each character in the sliding window is less than $k$.\n\nWe can use an array $\\textit{cnt}$ to maintain the occurrence count of each character in the sliding window, then use a variable $\\textit{l}$ to maintain the left endpoint of the sliding window, and use a variable $\\textit{ans}$ to maintain the answer.\n\nWhen we enumerate the right endpoint, we can add the character at the right endpoint to the sliding window, then check if the occurrence count of the character at the right endpoint in the sliding window is greater than or equal to $k$. If it is, we remove the character at the left endpoint from the sliding window until the occurrence count of each character in the sliding window is less than $k$. At this point, for substrings with left endpoints in the range $[0, ..l - 1]$ and right endpoint $r$, all satisfy the problem's requirements, so we add $l$ to the answer.\n\nAfter enumeration, we return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(|\\Sigma|)$, where $\\Sigma$ is the character set, which in this case is the set of lowercase letters, so $|\\Sigma| = 26$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 3326, "explanations": { "1": "According to the problem description,\n\nIf an integer $x$ is a prime number, then its largest proper divisor is $1$, so $x / 1 = x$, meaning $x$ cannot be divided further.\n\nIf an integer $x$ is not a prime number, we assume the largest proper divisor of $x$ is $y$, then $x / y$ must be a prime number. Therefore, we find the smallest prime factor $\\textit{lpf}[x]$ such that $x \\bmod \\textit{lpf}[x] = 0$, making $x$ become $\\textit{lpf}[x]$, at which point it cannot be divided further.\n\nThus, we can preprocess the smallest prime factor for each integer from $1$ to $10^6$. Then, we traverse the array from right to left. If the current element is greater than the next element, we change the current element to its smallest prime factor. If after changing the current element to its smallest prime factor it is still greater than the next element, it means the array cannot be made non-decreasing, and we return $-1$. Otherwise, we increment the operation count by one. Continue traversing until the entire array is processed.\n\nThe time complexity for preprocessing is $O(M \\times \\log \\log M)$, where $M = 10^6$. The time complexity for traversing the array is $O(n)$, where $n$ is the length of the array. The space complexity is $O(M)$." }, "is_english": true, "time_complexity": "O(M \\times \\log \\log M)", "space_complexity": "O(M)" }, { "problem_id": 3327, "explanations": { "1": "We can use Depth-First Search (DFS) to traverse the tree and compute the entire $\\textit{dfsStr}$, while also determining the interval $[l, r]$ for each node.\n\nThen, we use string hashing to compute the hash values of both $\\textit{dfsStr}$ and the reverse of $\\textit{dfsStr}$ to check if it is a palindrome.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3328, "explanations": { "1": "We can group the `cities` table by the `state` field, then apply filtering on each group to retain only the groups that meet the specified conditions." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3329, "explanations": { "1": "We can enumerate the right endpoint of the substring, and then use a sliding window to maintain the left endpoint of the substring, ensuring that the occurrence count of each character in the sliding window is less than $k$.\n\nWe can use an array $\\textit{cnt}$ to maintain the occurrence count of each character in the sliding window, then use a variable $\\textit{l}$ to maintain the left endpoint of the sliding window, and use a variable $\\textit{ans}$ to maintain the answer.\n\nWhen we enumerate the right endpoint, we can add the character at the right endpoint to the sliding window, then check if the occurrence count of the character at the right endpoint in the sliding window is greater than or equal to $k$. If it is, we remove the character at the left endpoint from the sliding window until the occurrence count of each character in the sliding window is less than $k$. At this point, for substrings with left endpoints in the range $[0, ..l - 1]$ and right endpoint $r$, all satisfy the problem's requirements, so we add $l$ to the answer.\n\nAfter enumeration, we return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(|\\Sigma|)$, where $\\Sigma$ is the character set, which in this case is the set of lowercase letters, so $|\\Sigma| = 26$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 3330, "explanations": { "1": "According to the problem description, if all adjacent characters are different, there is only 1 possible original input string. If there is 1 pair of adjacent identical characters, such as \"abbc\", then there are 2 possible original strings: \"abc\" and \"abbc\".\n\nBy analogy, if there are $k$ pairs of adjacent identical characters, then there are $k + 1$ possible original input strings.\n\nTherefore, we just need to traverse the string, count the number of pairs of adjacent identical characters, and add 1.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3331, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3332, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3333, "explanations": { "1": "For the constraint that the length is at least $k$, we can split it into two subproblems:\n\n- Without length restriction, for each group of consecutive identical characters, we can choose any number from $1$ to the length of the group. Let the number of ways be $a$.\n- For length less than $k$, let the number of ways be $b$.\n\nThus, the final answer is $a - b$.\n\nWe can group consecutive identical characters in the string $\\textit{word}$. Since at least one character must be chosen from each group, if a group has more than $0$ remaining selectable characters, we add it to an array $\\textit{nums}$. After initially selecting one character from each group, we update the remaining required character count $k$.\n\nIf $k < 1$, it means that after selecting one character from each group, the requirement of length at least $k$ is already satisfied, so the answer is $a$.\n\nOtherwise, we need to calculate the value of $b$. We use a 2D array $\\textit{f}$, where $\\textit{f}[i][j]$ represents the number of ways to select $j$ characters from the first $i$ groups. Initially, $\\textit{f}[0][0] = 1$, meaning there is $1$ way to select $0$ characters from $0$ groups. Then $b = \\sum_{j=0}^{k-1} \\text{f}[m][j]$, where $m$ is the length of $\\textit{nums}$. The answer is $a - b$.\n\nConsider the transition equation for $\\textit{f}[i][j]$. For the $i$-th group of characters, suppose its remaining length is $x$. For each $j$, we can enumerate the number of characters $l$ chosen from this group, where $l \\in [0, \\min(x, j)]$. Then, $\\textit{f}[i][j]$ can be transferred from $\\textit{f}[i-1][j-l]$. We can use prefix sums to optimize this transition.\n\nThe time complexity is $O(n + k^2)$, and the space complexity is $O(k^2)$, where $n$ is the length of the string $\\textit{word}$." }, "is_english": true, "time_complexity": "O(n + k^2)", "space_complexity": "O(k^2)" }, { "problem_id": 3334, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3335, "explanations": { "1": "We define $f[i][j]$ to represent the count of the $j$-th letter in the alphabet after $i$ transformations. Initially, $f[0][j]$ is the count of the $j$-th letter in the string $s$.\n\nAfter each transformation, the count of the $j$-th letter in the alphabet can be calculated as follows:\n\n$$\n\\begin{align*}\nf[i][0] &= f[i - 1][25] \\\\\nf[i][1] &= f[i - 1][0] + f[i - 1][25] \\\\\nf[i][2] &= f[i - 1][1] \\\\\nf[i][3] &= f[i - 1][2] \\\\\n&\\vdots \\\\\nf[i][25] &= f[i - 1][24]\n\\end{align*}\n$$\n\nThe answer is $f[t][0] + f[t][1] + \\ldots + f[t][25]$.\n\nSince the answer can be very large, we take the result modulo $10^9 + 7$.\n\nThe time complexity is $O(t \\times |\\Sigma|)$, and the space complexity is $O(t \\times |\\Sigma|)$, where $|\\Sigma|$ is the size of the alphabet." }, "is_english": true, "time_complexity": "O(t \\times |\\Sigma|)", "space_complexity": "O(t \\times |\\Sigma|)" }, { "problem_id": 3336, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3337, "explanations": { "1": "We define $f[i][j]$ as the number of times the $j$-th letter appears in the alphabet after $i$ transformations. Initially, $f[0][j]$ corresponds to the frequency of the $j$-th letter in the input string $s$.\n\nSince the frequency of each letter after a transformation affects the next transformation, and the total number of transformations $t$ can be large, we can accelerate this recurrence process using fast matrix exponentiation.\n\nNote that the result can be very large, so we take modulo $10^9 + 7$.\n\nThe time complexity of this approach is $O(n + \\log t \\times |\\Sigma|^3)$, where $n$ is the length of the string and $|\\Sigma|$ is the size of the alphabet (in this case, 26). The space complexity is $O(|\\Sigma|^2)$, which is the size of the matrix used for matrix multiplication." }, "is_english": true, "time_complexity": "O(n + \\log t \\times |\\Sigma|^3)", "space_complexity": "O(|\\Sigma|^2)" }, { "problem_id": 3338, "explanations": { "1": "We can use the `DENSE_RANK()` window function to rank employees in each department by salary in descending order, and then filter out the employees with a rank of $2$." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3339, "explanations": { "1": "Given the numbers $[1, m]$, there are $\\textit{cnt0} = \\lfloor \\frac{m}{2} \\rfloor$ even numbers and $\\textit{cnt1} = m - \\textit{cnt0}$ odd numbers.\n\nWe design a function $\\textit{dfs}(i, j, k)$, which represents the number of ways to fill up to the $i$-th position, with $j$ remaining positions needing to satisfy the condition, and the parity of the last position being $k$, where $k = 0$ indicates the last position is even, and $k = 1$ indicates the last position is odd. The answer is $\\textit{dfs}(0, k, 1)$.\n\nThe execution logic of the function $\\textit{dfs}(i, j, k)$ is as follows:\n\n- If $j < 0$, it means the remaining positions are less than $0$, so return $0$;\n- If $i \\ge n$, it means all positions are filled. If $j = 0$, it means the condition is satisfied, so return $1$, otherwise return $0$;\n- Otherwise, we can choose to fill with an odd or even number, calculate the number of ways for both, and return their sum.\n\nThe time complexity is $O(n \\times k)$, and the space complexity is $O(n \\times k)$. Here, $n$ and $k$ are the parameters given in the problem.", "2": "We can convert the memoized search from Solution 1 into dynamic programming.\n\nDefine $f[i][j][k]$ to represent the number of ways to fill the $i$-th position, with $j$ positions satisfying the condition, and the parity of the previous position being $k$. The answer will be $\\sum_{k = 0}^{1} f[n][k]$.\n\nInitially, we set $f[0][0][1] = 1$, indicating that after filling the $0$-th position, there are $0$ positions satisfying the condition, and the parity of the previous position is odd. All other $f[i][j][k]$ are initialized to $0$.\n\nThe state transition equations are as follows:\n\n$$\n\\begin{aligned}\nf[i][j][0] &= \\left( f[i - 1][j][1] + \\left( f[i - 1][j - 1][0] \\text{ if } j > 0 \\right) \\right) \\times \\textit{cnt0} \\bmod \\textit{mod}, \\\\\nf[i][j][1] &= \\left( f[i - 1][j][0] + f[i - 1][j][1] \\right) \\times \\textit{cnt1} \\bmod \\textit{mod}.\n\\end{aligned}\n$$\n\nThe time complexity is $O(n \\times k)$, and the space complexity is $O(n \\times k)$, where $n$ and $k$ are the parameters given in the problem.", "3": "We observe that the computation of $f[i]$ only depends on $f[i - 1]$, allowing us to optimize the space usage with a rolling array.\n\nThe time complexity is $O(n \\times k)$, and the space complexity is $O(k)$, where $n$ and $k$ are the parameters given in the problem." }, "is_english": true, "time_complexity": "O(n \\times k)", "space_complexity": "O(n \\times k)" }, { "problem_id": 3340, "explanations": { "1": "We can use an array $f$ of length $2$ to record the sum of numbers at even indices and odd indices. Then, we traverse the string $\\textit{nums}$ and add the numbers to the corresponding positions based on the parity of the indices. Finally, we check whether $f[0]$ is equal to $f[1]$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3341, "explanations": { "1": "We define a two-dimensional array $\\textit{dist}$, where $\\textit{dist}[i][j]$ represents the minimum time required to reach room $(i, j)$ from the starting point. Initially, we set all elements in the $\\textit{dist}$ array to infinity, and then set the $\\textit{dist}$ value of the starting point $(0, 0)$ to $0$.\n\nWe use a priority queue $\\textit{pq}$ to store each state, where each state consists of three values $(d, i, j)$, representing the time $d$ required to reach room $(i, j)$ from the starting point. Initially, we add the starting point $(0, 0, 0)$ to $\\textit{pq}$.\n\nIn each iteration, we take the front element $(d, i, j)$ from $\\textit{pq}$. If $(i, j)$ is the endpoint, we return $d$. If $d$ is greater than $\\textit{dist}[i][j]$, we skip this state. Otherwise, we enumerate the four adjacent positions $(x, y)$ of $(i, j)$. If $(x, y)$ is within the map, we calculate the final time $t$ from $(i, j)$ to $(x, y)$ as $t = \\max(\\textit{moveTime}[x][y], \\textit{dist}[i][j]) + 1$. If $t$ is less than $\\textit{dist}[x][y]$, we update the value of $\\textit{dist}[x][y]$ and add $(t, x, y)$ to $\\textit{pq}$.\n\nThe time complexity is $O(n \\times m \\times \\log (n \\times m))$, and the space complexity is $O(n \\times m)$. Here, $n$ and $m$ are the number of rows and columns of the map, respectively." }, "is_english": true, "time_complexity": "O(n \\times m \\times \\log (n \\times m))", "space_complexity": "O(n \\times m)" }, { "problem_id": 3342, "explanations": { "1": "We define a two-dimensional array $\\textit{dist}$, where $\\textit{dist}[i][j]$ represents the minimum time required to reach room $(i, j)$ from the starting point. Initially, we set all elements in the $\\textit{dist}$ array to infinity, and then set the $\\textit{dist}$ value of the starting point $(0, 0)$ to $0$.\n\nWe use a priority queue $\\textit{pq}$ to store each state, where each state consists of three values $(d, i, j)$, representing the time $d$ required to reach room $(i, j)$ from the starting point. Initially, we add the starting point $(0, 0, 0)$ to $\\textit{pq}$.\n\nIn each iteration, we take the front element $(d, i, j)$ from $\\textit{pq}$. If $(i, j)$ is the endpoint, we return $d$. If $d$ is greater than $\\textit{dist}[i][j]$, we skip this state. Otherwise, we enumerate the four adjacent positions $(x, y)$ of $(i, j)$. If $(x, y)$ is within the map, we calculate the final time $t$ from $(i, j)$ to $(x, y)$ as $t = \\max(\\textit{moveTime}[x][y], \\textit{dist}[i][j]) + (i + j) \\bmod 2 + 1$. If $t$ is less than $\\textit{dist}[x][y]$, we update the value of $\\textit{dist}[x][y]$ and add $(t, x, y)$ to $\\textit{pq}$.\n\nThe time complexity is $O(n \\times m \\times \\log (n \\times m))$, and the space complexity is $O(n \\times m)$. Here, $n$ and $m$ are the number of rows and columns of the map, respectively." }, "is_english": true, "time_complexity": "O(n \\times m \\times \\log (n \\times m))", "space_complexity": "O(n \\times m)" }, { "problem_id": 3343, "explanations": { "1": "First, we count the occurrences of each digit in the string $\\textit{num}$ and record them in the array $\\textit{cnt}$, then calculate the total sum $\\textit{s}$ of the string $\\textit{num}$.\n\nIf $\\textit{s}$ is odd, then $\\textit{num}$ cannot be balanced, so we directly return $0$.\n\nNext, we define a memoization search function $\\text{dfs}(i, j, a, b)$, where $i$ represents the current digit to be filled, $j$ represents the remaining sum of digits to be filled in odd positions, and $a$ and $b$ represent the remaining number of digits to be filled in odd and even positions, respectively. Let $n$ be the length of the string $\\textit{num}$, then the answer is $\\text{dfs}(0, s / 2, n / 2, (n + 1) / 2)$.\n\nIn the function $\\text{dfs}(i, j, a, b)$, we first check if all digits have been filled. If so, we need to ensure that $j = 0$, $a = 0$, and $b = 0$. If these conditions are met, it means the current arrangement is balanced, so we return $1$; otherwise, we return $0$.\n\nNext, we check if the remaining number of digits to be filled in odd positions $a$ is $0$ and $j > 0$. If so, it means the current arrangement is not balanced, so we return $0$ early.\n\nOtherwise, we can enumerate the number of current digits assigned to odd positions $l$, and the number of digits assigned to even positions is $r = \\textit{cnt}[i] - l$. We need to ensure $0 \\leq r \\leq b$ and $l \\times i \\leq j$. Then we calculate the number of current arrangements $t = C_a^l \\times C_b^r \\times \\text{dfs}(i + 1, j - l \\times i, a - l, b - r)$. Finally, the answer is the sum of all arrangement counts.\n\nThe time complexity is $O(|\\Sigma| \\times n^2 \\times (n + |\\Sigma|))$, where $|\\Sigma|$ represents the number of different digits, and in this problem $|\\Sigma| = 10$. The space complexity is $O(n^2 \\times |\\Sigma|^2)$." }, "is_english": true, "time_complexity": "O(|\\Sigma| \\times n^2 \\times (n + |\\Sigma|))", "space_complexity": "O(n^2 \\times |\\Sigma|^2)" }, { "problem_id": 3344, "explanations": { "1": "We can roughly estimate the maximum value of $n$. For $j \\lor k$, the sum of the results is approximately $n^2 (n - 1) / 2$. Multiplying this by each $i \\in [0, n)$, the result is approximately $(n-1)^5 / 4$. To ensure $(n - 1)^5 / 4 \\leq s$, we have $n \\leq 1320$.\n\nTherefore, we can preprocess $f[n] = \\sum_{i=0}^{n-1} \\sum_{j=0}^{i} (i \\lor j)$, and then use binary search to find the largest $n$ such that $f[n-1] \\cdot (n-1) \\cdot n / 2 \\leq s$.\n\nIn terms of time complexity, the preprocessing has a time complexity of $O(n^2)$, and the binary search has a time complexity of $O(\\log n)$. Therefore, the total time complexity is $O(n^2 + \\log n)$. The space complexity is $O(n)$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 3345, "explanations": { "1": "We note that within every $10$ numbers, there will definitely be an integer whose digit product is $0$. Therefore, we can directly enumerate integers greater than or equal to $n$ until we find an integer whose digit product is divisible by $t$.\n\nThe time complexity is $O(\\log n)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 3346, "explanations": { "1": "According to the problem description, for each element $x$ in the array $\\textit{nums}$, we can change it to any integer within the range $[x-k, x+k]$. We want to perform operations on some elements in $\\textit{nums}$ to maximize the frequency of a certain integer in the array.\n\nThe problem can be transformed into merging all elements in the interval $[x-k, x+k]$ corresponding to each element $x$, and finding the integer that contains the most original elements in the merged intervals. This can be implemented using a difference array.\n\nWe use a dictionary $d$ to record the difference array. For each element $x$, we perform the following operations on the difference array:\n\n- Add $1$ at position $x-k$, indicating that a new interval starts from this position.\n- Subtract $1$ at position $x+k+1$, indicating that an interval ends from this position.\n- Add $0$ at position $x$, ensuring that position $x$ exists in the difference array for subsequent calculations.\n\nAt the same time, we need to record the number of occurrences of each element in the original array, using a dictionary $cnt$ to implement this.\n\nNext, we perform prefix sum calculation on the difference array to get how many intervals cover each position. For each position $x$, we calculate the number of intervals covering it as $s$. Then we discuss by cases:\n\n- If $x$ appears in the original array, operations on $x$ itself are meaningless. Therefore, there are $s - cnt[x]$ other elements that can be changed to $x$ through operations, but at most $\\textit{numOperations}$ operations can be performed. So the maximum frequency at this position is $\\textit{cnt}[x] + \\min(s - \\textit{cnt}[x], \\textit{numOperations})$.\n- If $x$ does not appear in the original array, then at most $\\textit{numOperations}$ operations can be performed to change other elements to $x$. Therefore, the maximum frequency at this position is $\\min(s, \\textit{numOperations})$.\n\nCombining the above two cases, we can uniformly express it as $\\min(s, \\textit{cnt}[x] + \\textit{numOperations})$.\n\nFinally, we traverse all positions, calculate the maximum frequency at each position, and take the maximum value among them as the answer.\n\nThe time complexity is $O(n \\times \\log n)$ and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3347, "explanations": { "1": "According to the problem description, for each element $x$ in the array $\\textit{nums}$, we can change it to any integer within the range $[x-k, x+k]$. We want to perform operations on some elements in $\\textit{nums}$ to maximize the frequency of a certain integer in the array.\n\nThe problem can be transformed into merging all elements in the interval $[x-k, x+k]$ corresponding to each element $x$, and finding the integer that contains the most original elements in the merged intervals. This can be implemented using a difference array.\n\nWe use a dictionary $d$ to record the difference array. For each element $x$, we perform the following operations on the difference array:\n\n- Add $1$ at position $x-k$, indicating that a new interval starts from this position.\n- Subtract $1$ at position $x+k+1$, indicating that an interval ends from this position.\n- Add $0$ at position $x$, ensuring that position $x$ exists in the difference array for subsequent calculations.\n\nAt the same time, we need to record the number of occurrences of each element in the original array, using a dictionary $cnt$ to implement this.\n\nNext, we perform prefix sum calculation on the difference array to get how many intervals cover each position. For each position $x$, we calculate the number of intervals covering it as $s$. Then we discuss by cases:\n\n- If $x$ appears in the original array, operations on $x$ itself are meaningless. Therefore, there are $s - cnt[x]$ other elements that can be changed to $x$ through operations, but at most $\\textit{numOperations}$ operations can be performed. So the maximum frequency at this position is $\\textit{cnt}[x] + \\min(s - \\textit{cnt}[x], \\textit{numOperations})$.\n- If $x$ does not appear in the original array, then at most $\\textit{numOperations}$ operations can be performed to change other elements to $x$. Therefore, the maximum frequency at this position is $\\min(s, \\textit{numOperations})$.\n\nCombining the above two cases, we can uniformly express it as $\\min(s, \\textit{cnt}[x] + \\textit{numOperations})$.\n\nFinally, we traverse all positions, calculate the maximum frequency at each position, and take the maximum value among them as the answer.\n\nThe time complexity is $O(n \\times \\log n)$ and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3348, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3349, "explanations": { "1": "According to the problem description, we only need to find the maximum length of adjacent increasing subarrays $\\textit{mx}$. If $\\textit{mx} \\ge k$, then there exist two adjacent strictly increasing subarrays of length $k$.\n\nWe can use a single pass to calculate $\\textit{mx}$. Specifically, we maintain three variables: $\\textit{cur}$ and $\\textit{pre}$ represent the length of the current increasing subarray and the previous increasing subarray respectively, while $\\textit{mx}$ represents the maximum length of adjacent increasing subarrays.\n\nWhenever we encounter a non-increasing position, we update $\\textit{mx}$, assign $\\textit{cur}$ to $\\textit{pre}$, and reset $\\textit{cur}$ to $0$. The update formula for $\\textit{mx}$ is $\\textit{mx} = \\max(\\textit{mx}, \\lfloor \\frac{\\textit{cur}}{2} \\rfloor, \\min(\\textit{pre}, \\textit{cur}))$, meaning the adjacent increasing subarrays come from either half the length of the current increasing subarray, or the smaller value between the previous increasing subarray and the current increasing subarray.\n\nFinally, we just need to check whether $\\textit{mx}$ is greater than or equal to $k$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3350, "explanations": { "1": "We can use a single pass to calculate the maximum length of adjacent increasing subarrays $\\textit{ans}$. Specifically, we maintain three variables: $\\textit{cur}$ and $\\textit{pre}$ represent the length of the current increasing subarray and the previous increasing subarray respectively, while $\\textit{ans}$ represents the maximum length of adjacent increasing subarrays.\n\nWhenever we encounter a non-increasing position, we update $\\textit{ans}$, assign $\\textit{cur}$ to $\\textit{pre}$, and reset $\\textit{cur}$ to $0$. The update formula for $\\textit{ans}$ is $\\textit{ans} = \\max(\\textit{ans}, \\lfloor \\frac{\\textit{cur}}{2} \\rfloor, \\min(\\textit{pre}, \\textit{cur}))$, meaning the adjacent increasing subarrays come from either half the length of the current increasing subarray, or the smaller value between the previous increasing subarray and the current increasing subarray.\n\nFinally, we just need to return $\\textit{ans}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3351, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3352, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3353, "explanations": { "1": "We can traverse the array, and for each element, if it is not equal to the previous element, we need to perform an operation. Finally, we return the number of operations.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3354, "explanations": { "1": "Suppose we initially move to the left and encounter a non-zero element. In that case, we need to decrement this element by one, then change the direction of movement and continue moving.\n\nTherefore, we can maintain the sum of elements to the left of each zero-value element as $l$, and the sum of elements to the right as $s - l$. If $l = s - l$, meaning the sum of elements on the left equals the sum of elements on the right, we can choose the current zero-value element and move either left or right, adding $2$ to the answer. If $|l - (s - l)| = 1$, and the sum of elements on the left is greater, we can choose the current zero-value element and move left, adding $1$ to the answer. If the sum of elements on the right is greater, we can choose the current zero-value element and move right, adding $1$ to the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3355, "explanations": { "1": "We can use a difference array to solve this problem.\n\nDefine an array $d$ of length $n + 1$, with all initial values set to $0$. For each query $[l, r]$, we add $1$ to $d[l]$ and subtract $1$ from $d[r + 1]$.\n\nThen we traverse the array $d$ within the range $[0, n - 1]$, accumulating the prefix sum $s$. If $\\textit{nums}[i] > s$, it means $\\textit{nums}$ cannot be converted to a zero array, so we return $\\textit{false}$.\n\nAfter traversing, return $\\textit{true}$.\n\nThe time complexity is $O(n + m)$, and the space complexity is $O(n)$. Here, $n$ and $m$ are the lengths of the array $\\textit{nums}$ and the number of queries, respectively." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(n)" }, { "problem_id": 3356, "explanations": { "1": "We notice that the more queries we use, the easier it is to turn the array into a zero array, which shows monotonicity. Therefore, we can use binary search to enumerate the number of queries and check whether the array can be turned into a zero array after the first $k$ queries.\n\nWe define the left boundary $l$ and right boundary $r$ for binary search, initially $l = 0$, $r = m + 1$, where $m$ is the number of queries. We define a function $\\text{check}(k)$ to indicate whether the array can be turned into a zero array after the first $k$ queries. We can use a difference array to maintain the value of each element.\n\nDefine an array $d$ of length $n + 1$, initialized to all $0$. For each of the first $k$ queries $[l, r, val]$, we add $val$ to $d[l]$ and subtract $val$ from $d[r + 1]$.\n\nThen we iterate through the array $d$ in the range $[0, n - 1]$, accumulating the prefix sum $s$. If $\\textit{nums}[i] > s$, it means $\\textit{nums}$ cannot be transformed into a zero array, so we return $\\textit{false}$.\n\nDuring the binary search, if $\\text{check}(k)$ returns $\\text{true}$, it means the array can be turned into a zero array, so we update the right boundary $r$ to $k$; otherwise, we update the left boundary $l$ to $k + 1$.\n\nFinally, we check whether $l > m$. If so, return -1; otherwise, return $l$.\n\nThe time complexity is $O((n + m) \\times \\log m)$, and the space complexity is $O(n)$, where $n$ and $m$ are the lengths of the array $\\textit{nums}$ and $\\textit{queries}$, respectively." }, "is_english": true, "time_complexity": "O((n + m) \\times \\log m)", "space_complexity": "O(n)" }, { "problem_id": 3357, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3358, "explanations": { "1": "We directly filter out books where `rating` is `NULL`, then sort them in ascending order by `book_id`.\n\nNote that the result set should only include the fields `book_id`, `title`, `author`, and `published_year`." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3359, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3360, "explanations": { "1": "We simulate the game process according to the problem description until the game can no longer continue.\n\nSpecifically, we maintain two variables $x$ and $k$, representing the current number of stones that can be removed and the number of operations performed, respectively. Initially, $x = 10$ and $k = 0$.\n\nIn each round of operations, if the current number of stones that can be removed $x$ does not exceed the remaining number of stones $n$, we remove $x$ stones, decrease $x$ by $1$, and increase $k$ by $1$. Otherwise, we cannot perform the operation, and the game ends.\n\nFinally, we check the parity of $k$. If $k$ is odd, Alice wins the game; otherwise, Bob wins the game.\n\nThe time complexity is $O(\\sqrt{n})$, where $n$ is the number of stones. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\sqrt{n})", "space_complexity": "O(1)" }, { "problem_id": 3361, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3362, "explanations": { "1": "We want to \"remove\" as many interval queries as possible, while ensuring that for each position $i$, the number of selected queries covering it, $s(i)$, is at least the original array value $\\textit{nums}[i]$, so that the value at that position can be reduced to 0 or below. If for some position $i$ we cannot satisfy $s(i) \\ge \\textit{nums}[i]$, it means that no matter how many more queries we select, it is impossible to make that position zero, so we return $-1$.\n\nTo achieve this, we traverse the queries in order of their left endpoints and maintain:\n\n1. **Difference array** `d`: Used to record where the currently applied queries take effect—when we \"apply\" a query on the interval $[l, r]$, we immediately do `d[l] += 1` and `d[r+1] -= 1`. This way, when traversing to index $i$, the prefix sum tells us how many queries cover $i$.\n2. **Max heap** `pq`: Stores the right endpoints of the current \"candidate\" interval queries (store as negative numbers to simulate a max heap in Python's min heap). Why choose the \"latest ending\" interval? Because it can cover farther positions. Our greedy strategy is: **at each $i$, only pick the longest interval from the heap when necessary to increase coverage**, so that more intervals are available for subsequent positions.\n\nThe specific steps are as follows:\n\n1. Sort `queries` by the left endpoint `l` in ascending order;\n2. Initialize the difference array `d` with length `n+1` (to handle the decrement at `r+1`), and set the current coverage count `s=0`, heap pointer `j=0`;\n3. For $i=0$ to $n-1$:\n - First, add `d[i]` to `s` to update the current coverage count;\n - Push all queries $[l, r]$ with left endpoint $\\le i$ into the max heap `pq` (store `-r`), and advance `j`;\n - While the current coverage `s` is less than the required value `nums[i]`, and the heap is not empty, and the top interval in the heap still covers $i$ (i.e., $-pq[0] \\ge i$):\n 1. Pop the top of the heap (the longest interval), which is equivalent to \"applying\" this query;\n 2. Increment `s` by 1 and do `d[r+1] -= 1` (so that after passing $r$, the coverage count automatically decreases);\n\n - Repeat the above steps until `s \\ge nums[i]` or no more intervals can be selected;\n - If at this point `s < nums[i]`, it means it is impossible to make position $i$ zero, so return $-1$.\n\n4. After traversing all positions, the intervals remaining in the heap are those that were **not popped**, i.e., the queries that are truly **retained** (not used for the \"zeroing\" task). The heap size is the answer.\n\nThe time complexity is $O(n + m \\times \\log m)$, and the space complexity is $O(n + m)$, where $n$ is the length of the array and $m$ is the number of queries." }, "is_english": true, "time_complexity": "O(n + m \\times \\log m)", "space_complexity": "O(n + m)" }, { "problem_id": 3363, "explanations": { "1": "According to the problem description, for the child starting from $(0, 0)$ to reach $(n - 1, n - 1)$ in exactly $n - 1$ steps, they can only move through the rooms on the main diagonal $(i, i)$, where $i = 0, 1, \\ldots, n - 1$. The child starting from $(0, n - 1)$ can only move through rooms above the main diagonal, while the child starting from $(n - 1, 0)$ can only move through rooms below the main diagonal. This means that except for reaching the destination at $(n - 1, n - 1)$, no other rooms will be visited by multiple children.\n\nWe can use dynamic programming to calculate the number of fruits that the children starting from $(0, n - 1)$ and $(n - 1, 0)$ can collect when reaching $(i, j)$. Define $f[i][j]$ as the number of fruits a child can collect when reaching $(i, j)$.\n\nFor the child starting from $(0, n - 1)$, the state transition equation is:\n\n$$\nf[i][j] = \\max(f[i - 1][j], f[i - 1][j - 1], f[i - 1][j + 1]) + \\text{fruits}[i][j]\n$$\n\nNote that $f[i - 1][j + 1]$ is only valid when $j + 1 < n$.\n\nFor the child starting from $(n - 1, 0)$, the state transition equation is:\n\n$$\nf[i][j] = \\max(f[i][j - 1], f[i - 1][j - 1], f[i + 1][j - 1]) + \\text{fruits}[i][j]\n$$\n\nSimilarly, $f[i + 1][j - 1]$ is only valid when $i + 1 < n$.\n\nFinally, the answer is $\\sum_{i=0}^{n-1} \\text{fruits}[i][i] + f[n-2][n-1] + f[n-1][n-2]$, which is the sum of fruits on the main diagonal plus the fruits that the two children can collect when reaching $(n - 2, n - 1)$ and $(n - 1, n - 2)$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$, where $n$ is the side length of the room grid." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 3364, "explanations": { "1": "We can enumerate the left endpoint $i$ of the subarray, then enumerate the right endpoint $j$ from $i$ to $n$ within the interval $[i, n)$. We calculate the sum $s$ of the interval $[i, j]$. If $s$ is greater than $0$ and the interval length is between $[l, r]$, we update the answer.\n\nFinally, if the answer is still the initial value, it means no subarray meets the conditions, so we return $-1$. Otherwise, we return the answer.\n\nThe time complexity is $O(n^2)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(1)" }, { "problem_id": 3365, "explanations": { "1": "Let the length of the string $s$ be $n$, then the length of each substring is $m = n / k$.\n\nWe use a hash table $\\textit{cnt}$ to record the difference between the number of occurrences of each substring of length $m$ in string $s$ and in string $t$.\n\nWe traverse the string $s$, extracting substrings of length $m$ each time, and update the hash table $\\textit{cnt}$.\n\nFinally, we check whether all values in the hash table $\\textit{cnt}$ are $0$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3366, "explanations": { "1": "For convenience, we denote the given $k$ as $d$.\n\nNext, we define $f[i][j][k]$ to represent the minimum sum of the first $i$ numbers using $j$ operations of type 1 and $k$ operations of type 2. Initially, $f[0][0][0] = 0$, and the rest $f[i][j][k] = +\\infty$.\n\nConsider how to transition the state for $f[i][j][k]$. We can enumerate the $i$-th number $x$ and then consider the impact of $x$ on $f[i][j][k]$:\n\n- If $x$ does not use operation 1 or operation 2, then $f[i][j][k] = f[i-1][j][k] + x$;\n- If $j \\gt 0$, then we can use operation 1. In this case, $f[i][j][k] = \\min(f[i][j][k], f[i-1][j-1][k] + \\lceil \\frac{x+1}{2} \\rceil)$;\n- If $k \\gt 0$ and $x \\geq d$, then we can use operation 2. In this case, $f[i][j][k] = \\min(f[i][j][k], f[i-1][j][k-1] + (x - d))$;\n- If $j \\gt 0$ and $k \\gt 0$, then we can use both operation 1 and operation 2. If we use operation 1 first, then $x$ becomes $\\lceil \\frac{x+1}{2} \\rceil$. If $x \\geq d$, then we can use operation 2. In this case, $f[i][j][k] = \\min(f[i][j][k], f[i-1][j-1][k-1] + \\lceil \\frac{x+1}{2} \\rceil - d)$. If we use operation 2 first, then $x$ becomes $x - d$. If $x \\geq d$, then we can use operation 1. In this case, $f[i][j][k] = \\min(f[i][j][k], f[i-1][j-1][k-1] + \\lceil \\frac{x-d+1}{2} \\rceil)$.\n\nThe final answer is $\\min_{j=0}^{op1} \\min_{k=0}^{op2} f[n][j][k]$. If it is $+\\infty$, then output $-1$.\n\nThe time complexity is $O(n \\times \\textit{op1} \\times \\textit{op2})$, and the space complexity is $O(n \\times \\textit{op1} \\times \\textit{op2})$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times \\textit{op1} \\times \\textit{op2})", "space_complexity": "O(n \\times \\textit{op1} \\times \\textit{op2})" }, { "problem_id": 3367, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3368, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3369, "explanations": { "1": "We define a queue $\\textit{q}$ to store the added numbers, a variable $\\textit{s}$ to store the sum of all numbers, a hash table $\\textit{cnt}$ to store the occurrence count of each number, an ordered set $\\textit{sl}$ to store all numbers, and an ordered set $\\textit{sl2}$ to store all numbers and their occurrence counts, sorted by occurrence count in descending order and by value in ascending order.\n\nIn the `addNumber` method, we add the number to the queue $\\textit{q}$, add the number to the ordered set $\\textit{sl}$, then remove the number and its occurrence count from the ordered set $\\textit{sl2}$, update the occurrence count of the number, and finally add the number and its updated occurrence count to the ordered set $\\textit{sl2}$, and update the sum of all numbers. The time complexity is $O(\\log n)$.\n\nIn the `removeFirstAddedNumber` method, we remove the earliest added number from the queue $\\textit{q}$, remove the number from the ordered set $\\textit{sl}$, then remove the number and its occurrence count from the ordered set $\\textit{sl2}$, update the occurrence count of the number, and finally add the number and its updated occurrence count to the ordered set $\\textit{sl2}$, and update the sum of all numbers. The time complexity is $O(\\log n)$.\n\nIn the `getMean` method, we return the sum of all numbers divided by the number of numbers. The time complexity is $O(1)$.\n\nIn the `getMedian` method, we return the $\\textit{len}(\\textit{q}) / 2$-th number in the ordered set $\\textit{sl}$. The time complexity is $O(1)$ or $O(\\log n)$.\n\nIn the `getMode` method, we return the first number in the ordered set $\\textit{sl2}$. The time complexity is $O(1)$.\n\n> In Python, we can directly access elements in an ordered set by index. In other languages, we can implement this using a heap.\n\nThe space complexity is $O(n)$, where $n$ is the number of added numbers." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(n)" }, { "problem_id": 3370, "explanations": { "1": "We start with $x = 1$ and continuously left shift $x$ until $x - 1 \\geq n$. At this point, $x - 1$ is the answer we are looking for.\n\nThe time complexity is $O(\\log n)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 3371, "explanations": { "1": "We use a hash table $\\textit{cnt}$ to record the frequency of each element in the array $\\textit{nums}$.\n\nNext, we enumerate each element $x$ in the array $\\textit{nums}$ as a possible outlier. For each $x$, we calculate the sum $t$ of all elements in the array $\\textit{nums}$ except $x$. If $t$ is not even, or half of $t$ is not in $\\textit{cnt}$, then $x$ does not meet the condition, and we skip this $x$. Otherwise, if $x$ is not equal to half of $t$, or $x$ appears more than once in $\\textit{cnt}$, then $x$ is a possible outlier, and we update the answer.\n\nAfter enumerating all elements, we return the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3372, "explanations": { "1": "According to the problem description, to maximize the number of target nodes for node $i$, we must connect node $i$ to one of the nodes $j$ in the second tree. Therefore, the number of target nodes for node $i$ can be divided into two parts:\n\n- In the first tree, the number of nodes reachable from node $i$ within a depth of $k$.\n- In the second tree, the maximum number of nodes reachable from any node $j$ within a depth of $k - 1$.\n\nThus, we can first calculate the number of nodes reachable within a depth of $k - 1$ for each node in the second tree. Then, we enumerate each node $i$ in the first tree, calculate the sum of the two parts mentioned above, and take the maximum value.\n\nThe time complexity is $O(n^2 + m^2)$, and the space complexity is $O(n + m)$. Here, $n$ and $m$ are the number of nodes in the two trees, respectively." }, "is_english": true, "time_complexity": "O(n^2 + m^2)", "space_complexity": "O(n + m)" }, { "problem_id": 3373, "explanations": { "1": "The number of target nodes for node $i$ can be divided into two parts:\n\n- The number of nodes in the first tree with the same depth parity as node $i$.\n- The maximum number of nodes in the second tree with the same depth parity.\n\nFirst, we use Depth-First Search (DFS) to calculate the number of nodes in the second tree with the same depth parity, denoted as $\\textit{cnt2}$. Then, we calculate the number of nodes in the first tree with the same depth parity as node $i$, denoted as $\\textit{cnt1}$. Therefore, the number of target nodes for node $i$ is $\\max(\\textit{cnt2}) + \\textit{cnt1}$.\n\nThe time complexity is $O(n + m)$, and the space complexity is $O(n + m)$. Here, $n$ and $m$ are the number of nodes in the first and second trees, respectively." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(n + m)" }, { "problem_id": 3374, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3375, "explanations": { "1": "According to the problem description, we can choose the second largest value in the current array as the valid integer $h$ each time, and change all numbers greater than $h$ to $h$. This minimizes the number of operations. Additionally, since the operation reduces the numbers, if there are numbers in the current array smaller than $k$, we cannot make all numbers equal to $k$, so we directly return -1.\n\nWe iterate through the array $\\textit{nums}$. For the current number $x$, if $x < k$, we directly return -1. Otherwise, we add $x$ to the hash table and update the minimum value $\\textit{mi}$ in the current array. Finally, we return the size of the hash table minus 1 (if $\\textit{mi} = k$, we need to subtract 1).\n\nTime complexity is $O(n)$, and space complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3376, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3377, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3378, "explanations": { "1": "", "2": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3379, "explanations": { "1": "We create a result array $\\textit{ans}$. For each index, we move right or left $|nums[i]|$ steps based on whether $nums[i]$ is positive or negative, calculate the landing index, and assign the value at that index to $\\textit{ans}[i]$.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3380, "explanations": { "1": "We can enumerate the bottom-left corner $(x_3, y_3)$ and the top-right corner $(x_4, y_4)$ of the rectangle. Then, we enumerate all points $(x, y)$ and check if the point is inside or on the boundary of the rectangle. If it is, it does not meet the condition. Otherwise, we exclude the points outside the rectangle and check if there are 4 remaining points. If there are, these 4 points can form a rectangle. We calculate the area of the rectangle and take the maximum value.\n\nThe time complexity is $O(n^3)$, where $n$ is the length of the array $\\textit{points}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n^3)", "space_complexity": "O(1)" }, { "problem_id": 3381, "explanations": { "1": "According to the problem description, for a subarray's length to be divisible by $k$, it is equivalent to requiring that for subarray $\\textit{nums}[i+1 \\ldots j]$, we have $i \\bmod k = j \\bmod k$.\n\nWe can enumerate the right endpoint $j$ of the subarray and use an array $\\textit{f}$ of length $k$ to record the minimum prefix sum for each modulo $k$. Initially, $\\textit{f}[k-1] = 0$, indicating that the prefix sum at index $-1$ is $0$.\n\nThen for the current right endpoint $j$ with prefix sum $s$, we can calculate the maximum sum of subarrays ending at $j$ with length divisible by $k$ as $s - \\textit{f}[j \\bmod k]$, and update the answer accordingly. At the same time, we need to update $\\textit{f}[j \\bmod k]$ to be the minimum of the current prefix sum $s$ and $\\textit{f}[j \\bmod k]$.\n\nAfter the enumeration is complete, return the answer.\n\nThe time complexity is $O(n)$ and the space complexity is $O(k)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(k)" }, { "problem_id": 3382, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3383, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3384, "explanations": { "1": "We can use an equi-join to find the teams of both the passer and the receiver for each pass. Then, based on the timestamp, we determine whether the pass occurred in the first half or the second half. By checking if the passer and receiver belong to the same team, we calculate the advantage value for each pass. Finally, we group by team name and half number, and sum the advantage values to get the advantage value for each team in the first and second halves." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3385, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3386, "explanations": { "1": "We define two variables $\\textit{ans}$ and $t$, representing the index of the button with the longest press time and the press time, respectively.\n\nNext, we start traversing the array $\\textit{events}$ from index $k = 1$. For each $k$, we calculate the press time of the current button $d = t2 - t1$, where $t2$ is the press time of the current button and $t1$ is the press time of the previous button. If $d > t$ or $d = t$ and the index $i$ of the current button is less than $\\textit{ans}$, we update $\\textit{ans} = i$ and $t = d$.\n\nFinally, we return $\\textit{ans}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{events}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3387, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3388, "explanations": { "1": "We can preprocess $\\text{LCP}[i][j]$ to represent the length of the longest common prefix of $\\textit{nums}[i:]$ and $\\textit{nums}[j:]$. Initially, $\\text{LCP}[i][j] = 0$.\n\nNext, we enumerate $i$ and $j$ in reverse order. For each pair of $i$ and $j$, if $\\textit{nums}[i] = \\textit{nums}[j]$, then we can get $\\text{LCP}[i][j] = \\text{LCP}[i + 1][j + 1] + 1$.\n\nFinally, we enumerate the ending position $i$ of the first subarray (excluding position $i$) and the ending position $j$ of the second subarray (excluding position $j$). The length of the first subarray is $i$, the length of the second subarray is $j - i$, and the length of the third subarray is $n - j$. If $i \\leq j - i$ and $\\text{LCP}[0][i] \\geq i$, or $j - i \\leq n - j$ and $\\text{LCP}[i][j] \\geq j - i$, then this split is beautiful, and we increment the answer by one.\n\nAfter enumerating, the answer is the number of beautiful splits.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 3389, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3390, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3391, "explanations": { "1": "We use a three-dimensional array $\\textit{g}$ to represent the matrix, where $\\textit{g}[x][y][z]$ represents the value at coordinate $(x, y, z)$ in the matrix. We use an array $\\textit{cnt}$ of length $n$ to record the number of 1s in each layer. We use an ordered set $\\textit{sl}$ to maintain the number of 1s and the layer number for each layer. The elements in $\\textit{sl}$ are $(\\textit{cnt}[x], x)$, so $\\textit{sl}$ can be sorted in descending order by the number of 1s, and in descending order by layer number if the number of 1s is the same.\n\nWhen calling the `setCell` method, we first check if $(x, y, z)$ has already been set to 1. If it has, we return directly. Otherwise, we set $\\textit{g}[x][y][z]$ to 1, remove $(\\textit{cnt}[x], x)$ from $\\textit{sl}$, increment $\\textit{cnt}[x]$ by 1, and add $(\\textit{cnt}[x], x)$ to $\\textit{sl}$.\n\nWhen calling the `unsetCell` method, we first check if $(x, y, z)$ has already been set to 0. If it has, we return directly. Otherwise, we set $\\textit{g}[x][y][z]$ to 0, remove $(\\textit{cnt}[x], x)$ from $\\textit{sl}$, decrement $\\textit{cnt}[x]$ by 1, and if $\\textit{cnt}[x]$ is greater than 0, add $(\\textit{cnt}[x], x)$ to $\\textit{sl}$.\n\nWhen calling the `largestMatrix` method, we return the second value of the first element in $\\textit{sl}$. If $\\textit{sl}$ is empty, we return $n - 1$.\n\nIn terms of time complexity, the `setCell` and `unsetCell` methods both have a time complexity of $O(\\log n)$, and the `largestMatrix` method has a time complexity of $O(1)$. The space complexity is $O(n^3)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(n^3)" }, { "problem_id": 3392, "explanations": { "1": "We traverse each subarray of length $3$ in the array $\\textit{nums}$ and check if twice the sum of the first and third numbers equals the second number. If it does, we increment the answer by $1$.\n\nAfter traversing, we return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3393, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3394, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3395, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3396, "explanations": { "1": "We can traverse the array $\\textit{nums}$ in reverse order and use a hash table $\\textit{s}$ to record the elements that have already been traversed. When we encounter an element $\\textit{nums}[i]$, if $\\textit{nums}[i]$ is already in the hash table $\\textit{s}$, it means we need to remove all elements from $\\textit{nums}[0..i]$. The number of operations required is $\\left\\lfloor \\frac{i}{3} \\right\\rfloor + 1$. Otherwise, we add $\\textit{nums}[i]$ to the hash table $\\textit{s}$ and continue to the next element.\n\nAfter traversing, if no duplicate elements are found, the elements in the array are already distinct, and no operations are needed, so the answer is $0$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3397, "explanations": { "1": "We can sort the array $\\textit{nums}$ and then consider each element $x$ from left to right.\n\nFor the first element, we can greedily change it to $x - k$, making $x$ as small as possible to leave more space for subsequent elements. We use the variable $\\textit{pre}$ to track the maximum value of the elements used so far, initialized to negative infinity.\n\nFor subsequent elements $x$, we can greedily change it to $\\min(x + k, \\max(x - k, \\textit{pre} + 1))$. Here, $\\max(x - k, \\textit{pre} + 1)$ means we try to make $x$ as small as possible but not smaller than $\\textit{pre} + 1$. If this value exists and is less than $x + k$, we can change $x$ to this value, increment the count of distinct elements, and update $\\textit{pre}$ to this value.\n\nAfter traversing the array, we obtain the maximum number of distinct elements.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 3398, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3399, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3400, "explanations": { "1": "We can enumerate the number of right shifts $k$, where $0 \\leq k < n$. For each $k$, we can calculate the number of matching indices between the array $\\textit{nums1}$ after right shifting $k$ times and $\\textit{nums2}$. The maximum value is taken as the answer.\n\nThe time complexity is $O(n^2)$, where $n$ is the length of the array $\\textit{nums1}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(1)" }, { "problem_id": 3401, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3402, "explanations": { "1": "We can traverse the matrix column by column. For each column, we calculate the minimum number of operations required to make it strictly increasing. Specifically, for each column, we maintain a variable $\\textit{pre}$ to represent the value of the previous element in the current column. Then, we traverse the current column from top to bottom. For the current element $\\textit{cur}$, if $\\textit{pre} < \\textit{cur}$, it means the current element is already greater than the previous element, so we only need to update $\\textit{pre} = \\textit{cur}$. Otherwise, we need to increase the current element to $\\textit{pre} + 1$ and add the number of increases to the answer.\n\nThe time complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns of the matrix $\\textit{grid}$, respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(1)" }, { "problem_id": 3403, "explanations": { "1": "If we fix the left endpoint of the substring, the longer the substring, the larger its lexicographical order. Suppose the left endpoint of the substring is $i$, and the minimum length of the remaining substrings is $\\text{numFriends} - 1$, then the right endpoint of the substring can be up to $\\min(n, i + n - (\\text{numFriends} - 1))$, where $n$ is the length of the string. Note that we are talking about left-closed, right-open intervals.\n\nWe enumerate all possible left endpoints, extract the corresponding substrings, compare their lexicographical order, and finally obtain the lexicographically largest substring.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$, where $n$ is the length of the string." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 3404, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3405, "explanations": { "1": "For an array of length $n$, there are $n - 1$ pairs of adjacent elements. We need to select $k$ of these $n - 1$ adjacent pairs such that the two elements in each of these $k$ pairs are equal, and the remaining $n - 1 - k$ adjacent pairs have different elements.\n\nThis is equivalent to splitting the array $n - 1 - k$ times, resulting in $n - k$ segments, where all elements in each segment are equal. The number of ways to split is $C_{n - 1}^{n - 1 - k} = C_{n - 1}^{k}$.\n\nFor the first segment, we can choose any element from $[1, m]$. For the remaining $n - k - 1$ segments, we just need to ensure that the element in each segment is different from the previous segment, so each of these segments has $m - 1$ choices. In total, there are $m \\times (m - 1)^{n - k - 1}$ ways to choose.\n\nCombining the two parts above, we get the answer:\n\n$$\nC_{n - 1}^{k} \\times m \\times (m - 1)^{n - k - 1} \\bmod (10^9 + 7)\n$$\n\nIn the code implementation, we can precompute factorials and inverses, and use fast power to calculate combinations.\n\nIgnoring the preprocessing time and space, the time complexity is $O(\\log (n - k))$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log (n - k))", "space_complexity": "O(1)" }, { "problem_id": 3406, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3407, "explanations": { "1": "According to the problem description, `*` can be replaced by any sequence of zero or more characters, so we can split the pattern string $p$ by `*` into several substrings. If these substrings appear in order in the string $s$, then $p$ can become a substring of $s$.\n\nTherefore, we first initialize a pointer $i$ to the start of string $s$, then iterate over each substring $t$ obtained by splitting the pattern string $p$ by `*`. For each $t$, we search for it in $s$ starting from position $i$. If it is found, we move the pointer $i$ to the end of $t$ and continue searching for the next substring. If it is not found, it means the pattern string $p$ cannot become a substring of $s$, and we return $\\text{false}$. If all substrings are found, we return $\\text{true}$.\n\nThe time complexity is $O(n \\times m)$, and the space complexity is $O(m)$, where $n$ and $m$ are the lengths of strings $s$ and $p$, respectively." }, "is_english": true, "time_complexity": "O(n \\times m)", "space_complexity": "O(m)" }, { "problem_id": 3408, "explanations": { "1": "We use a hash map $\\text{d}$ to store task information, where the key is the task ID and the value is a tuple $(\\text{userId}, \\text{priority})$ representing the user ID and the priority of the task.\n\nWe use an ordered set $\\text{st}$ to store all tasks currently in the system, where each element is a tuple $(-\\text{priority}, -\\text{taskId})$ representing the negative priority and negative task ID. We use negative values so that the task with the highest priority and largest task ID appears first in the ordered set.\n\nFor each operation, we can process as follows:\n\n- **Initialization**: For each task $(\\text{userId}, \\text{taskId}, \\text{priority})$, add it to the hash map $\\text{d}$ and the ordered set $\\text{st}$.\n- **Add Task**: Add the task $(\\text{userId}, \\text{taskId}, \\text{priority})$ to the hash map $\\text{d}$ and the ordered set $\\text{st}$.\n- **Edit Task**: Retrieve the user ID and old priority for the given task ID from the hash map $\\text{d}$, remove the old task information from the ordered set $\\text{st}$, then add the new task information to both the hash map and the ordered set.\n- **Remove Task**: Retrieve the priority for the given task ID from the hash map $\\text{d}$, remove the task information from the ordered set $\\text{st}$, and delete the task from the hash map.\n- **Execute Top Priority Task**: If the ordered set $\\text{st}$ is empty, return -1. Otherwise, take the first element from the ordered set, get the task ID, retrieve the corresponding user ID from the hash map, and remove the task from both the hash map and the ordered set. Finally, return the user ID.\n\nFor time complexity, initialization requires $O(n \\log n)$ time, where $n$ is the number of initial tasks. Each add, edit, remove, and execute operation requires $O(\\log m)$ time, where $m$ is the current number of tasks in the system. Since the total number of operations does not exceed $2 \\times 10^5$, the overall time complexity is acceptable. The space complexity is $O(n + m)$ for storing the hash map and ordered set." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(n + m)" }, { "problem_id": 3409, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3410, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3411, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3412, "explanations": { "1": "We can use a hash table $\\textit{d}$ to store the index list of each unmarked character, where the key is the character and the value is the list of indices.\n\nWe traverse the string $\\textit{s}$, and for each character $\\textit{x}$, we find its mirror character $\\textit{y}$. If $\\textit{d}$ contains $\\textit{y}$, we take out the index list $\\textit{ls}$ corresponding to $\\textit{y}$, take out the last element $\\textit{j}$ from $\\textit{ls}$, and remove $\\textit{j}$ from $\\textit{ls}$. If $\\textit{ls}$ becomes empty, we remove $\\textit{y}$ from $\\textit{d}$. At this point, we have found a pair of indices $(\\textit{j}, \\textit{i})$ that meet the condition, and we add $\\textit{i} - \\textit{j}$ to the answer. Otherwise, we add $\\textit{x}$ to $\\textit{d}$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $\\textit{s}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3413, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3414, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3415, "explanations": { "1": "We can use regular expressions to match product names that contain three consecutive digits." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3416, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3417, "explanations": { "1": "We traverse each row. If the current row index is odd, we reverse the elements of that row. Then, we traverse the elements of the row and add them to the answer array according to the rules specified in the problem.\n\nThe time complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns of the 2D array $\\textit{grid}$, respectively. Ignoring the space consumption of the answer array, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(1)" }, { "problem_id": 3418, "explanations": { "1": "We design a function $\\textit{dfs}(i, j, k)$, which represents the maximum amount of coins the robot can collect starting from $(i, j)$ with $k$ conversion opportunities left. The robot can only move right or down, so the value of $\\textit{dfs}(i, j, k)$ depends only on $\\textit{dfs}(i + 1, j, k)$ and $\\textit{dfs}(i, j + 1, k)$.\n\n- If $i \\geq m$ or $j \\geq n$, it means the robot has moved out of the grid, so we return a very small value.\n- If $i = m - 1$ and $j = n - 1$, it means the robot has reached the bottom-right corner of the grid. If $k > 0$, the robot can choose to convert the bandit at the current position, so we return $\\max(0, \\textit{coins}[i][j])$. If $k = 0$, the robot cannot convert the bandit at the current position, so we return $\\textit{coins}[i][j]$.\n- If $\\textit{coins}[i][j] < 0$, it means there is a bandit at the current position. If $k > 0$, the robot can choose to convert the bandit at the current position, so we return $\\textit{coins}[i][j] + \\max(\\textit{dfs}(i + 1, j, k), \\textit{dfs}(i, j + 1, k))$. If $k = 0$, the robot cannot convert the bandit at the current position, so we return $\\textit{coins}[i][j] + \\max(\\textit{dfs}(i + 1, j, k), \\textit{dfs}(i, j + 1, k))$.\n\nBased on the above analysis, we can write the code for memoized search.\n\nThe time complexity is $O(m \\times n \\times k)$, and the space complexity is $O(m \\times n \\times k)$. Here, $m$ and $n$ are the number of rows and columns of the 2D array $\\textit{coins}$, and $k$ is the number of conversion opportunities, which is $3$ in this problem." }, "is_english": true, "time_complexity": "O(m \\times n \\times k)", "space_complexity": "O(m \\times n \\times k)" }, { "problem_id": 3419, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3420, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3421, "explanations": { "1": "First, we use the window function `ROW_NUMBER()` to calculate the ranking of each student's exam date in each subject, separately calculating the first and most recent exam rankings for each student in each subject.\n\nThen, we use a subquery `JOIN` operation to join the scores of the first and most recent exams together. Finally, we filter out the students whose most recent exam scores are higher than their first exam scores according to the problem requirements." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3422, "explanations": { "1": "According to the problem description, we need to find a subarray of length $k$ and make all elements in the subarray equal with the minimum number of operations. That is, we need to find a subarray of length $k$ such that the minimum number of operations required to make all elements in the subarray equal to the median of these $k$ elements is minimized.\n\nWe can use two ordered sets $l$ and $r$ to maintain the left and right parts of the $k$ elements, respectively. $l$ is used to store the smaller part of the $k$ elements, and $r$ is used to store the larger part of the $k$ elements. The number of elements in $l$ is either equal to the number of elements in $r$ or one less than the number of elements in $r$, so the minimum value in $r$ is the median of the $k$ elements.\n\nThe time complexity is $O(n \\times \\log k)$, and the space complexity is $O(k)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times \\log k)", "space_complexity": "O(k)" }, { "problem_id": 3423, "explanations": { "1": "We traverse the array $\\textit{nums}$, calculate the absolute difference between adjacent elements, and maintain the maximum absolute difference. Finally, we compare it with the absolute difference between the first and last elements and take the maximum value.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3424, "explanations": { "1": "If splitting the array is not allowed, we can directly calculate the sum of absolute differences between the two arrays as the total cost $c_1$. If splitting is allowed, we can divide the array $\\textit{arr}$ into $n$ subarrays of length 1, then rearrange them in any order, and compare with array $\\textit{brr}$, calculating the sum of absolute differences as the total cost $c_2$. To minimize $c_2$, we can sort both arrays and then calculate the sum of absolute differences. The final result is $\\min(c_1, c_2 + k)$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$, where $n$ is the length of the array $\\textit{arr}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 3425, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3426, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3427, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3428, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3429, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3430, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3431, "explanations": { "1": "According to the problem description, to make $\\textit{nums}$ a sortable array, the position of the number $3$ must be after the position of the number $1$. If the position of the number $3$ is before the position of the number $1$, no matter how we swap, the number $3$ cannot reach the position of the number $1$, so it is impossible to make $\\textit{nums}$ a sortable array.\n\nWe use $\\textit{first2}$ and $\\textit{first3}$ to represent the first occurrence positions of the numbers $2$ and $3$, and $\\textit{last1}$ and $\\textit{last2}$ to represent the last occurrence positions of the numbers $1$ and $2$.\n\nWhen the index $i$ is in the range $[\\textit{first2}, \\textit{last1})$ or $[\\textit{first3}, \\textit{last2})]$, the corresponding $\\textit{locked}[i]$ must be $0$, otherwise, we need one operation. Therefore, we only need to traverse the array $\\textit{locked}$ and count the indices that do not meet the condition.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3432, "explanations": { "1": "We use two variables $l$ and $r$ to represent the sum of the left subarray and the right subarray, respectively. Initially, $l = 0$ and $r = \\sum_{i=0}^{n-1} \\textit{nums}[i]$.\n\nNext, we traverse the first $n - 1$ elements. Each time, we add the current element to the left subarray and subtract it from the right subarray. Then, we check if $l - r$ is even. If it is, we increment the answer by one.\n\nFinally, we return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3433, "explanations": { "1": "We sort the events in ascending order of timestamps. If the timestamps are the same, we place OFFLINE events before MESSAGE events.\n\nThen we simulate the occurrence of events, using the `online_t` array to record the next online time for each user and a variable `lazy` to record the number of mentions that need to be applied to all users.\n\nWe traverse the event list and handle each event based on its type:\n\n- If it is an ONLINE event, we update the `online_t` array.\n- If it is an ALL event, we increment `lazy` by one.\n- If it is a HERE event, we traverse the `online_t` array. If a user's next online time is less than or equal to the current time, we increment that user's mention count by one.\n- If it is a MESSAGE event, we increment the mention count of the mentioned user by one.\n\nFinally, if `lazy` is greater than 0, we add `lazy` to the mention count of all users.\n\nThe time complexity is $O(n + m \\times \\log m \\log M + L)$, and the space complexity is $O(n)$. Here, $n$ and $m$ are the total number of users and events, respectively, while $M$ and $L$ are the maximum value of the timestamps and the total length of all mentioned strings, respectively." }, "is_english": true, "time_complexity": "O(n + m \\times \\log m \\log M + L)", "space_complexity": "O(n)" }, { "problem_id": 3434, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3435, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3436, "explanations": { "1": "We can use a regular expression with `REGEXP` to match valid email addresses.\n\nThe time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the input string." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3437, "explanations": { "1": "We design a function $\\textit{dfs}(i)$, which represents filling the $i$-th position, with position indices starting from $0$.\n\nIn $\\textit{dfs}(i)$, if $i \\geq n$, it means all positions have been filled, and we add the current permutation to the answer array.\n\nOtherwise, we enumerate the numbers $j$ that can be placed in the current position. If $j$ has not been used and $j$ has a different parity from the last number in the current permutation, we can place $j$ in the current position and continue to recursively fill the next position.\n\nThe time complexity is $O(n \\times n!)$, and the space complexity is $O(n)$. Here, $n$ is the length of the permutation." }, "is_english": true, "time_complexity": "O(n \\times n!)", "space_complexity": "O(n)" }, { "problem_id": 3438, "explanations": { "1": "We can use an array $\\textit{cnt}$ of length $10$ to record the occurrences of each digit in the string $\\textit{s}$.\n\nThen, we traverse the adjacent digit pairs in the string $\\textit{s}$. If the two digits are not equal and the occurrences of these two digits are equal to the digits themselves, we have found a valid pair of adjacent digits and return it.\n\nAfter traversing, if no valid pair of adjacent digits is found, we return an empty string.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $\\textit{s}$. The space complexity is $O(|\\Sigma|)$, where $\\Sigma$ is the character set of the string $\\textit{s}$. In this problem, $\\Sigma = \\{1, 2, \\ldots, 9\\}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 3439, "explanations": { "1": "The problem is essentially about merging adjacent free time intervals into a longer free interval. There are $n + 1$ free intervals in total:\n\n- The first free interval is from the start of the event to the start of the first meeting;\n- The middle $n - 1$ free intervals are between each pair of adjacent meetings;\n- The last free interval is from the end of the last meeting to the end of the event.\n\nAt most $k$ meetings can be rescheduled, which is equivalent to merging up to $k + 1$ free intervals. We need to find the maximum length among all possible merged $k + 1$ free intervals.\n\nWe can store the lengths of these free intervals in an array $\\textit{nums}$. Then, we use a sliding window of length $k + 1$ to traverse this array, calculate the sum for each window, and find the maximum sum, which is the maximum free time we are looking for.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of meetings.", "2": "In Solution 1, we used an array to store the lengths of the free intervals. In fact, we do not need to store the entire array; we can use a function $f(i)$ to represent the length of the $i$-th free interval. This way, we can save space.\n\nThe time complexity is $O(n)$, where $n$ is the number of meetings. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3440, "explanations": { "1": "According to the problem description, for meeting $i$, let $l_i$ be the non-free position to its left, $r_i$ be the non-free position to its right, and let the duration of meeting $i$ be $w_i = \\text{endTime}[i] - \\text{startTime}[i]$. Then:\n\n$$\nl_i = \\begin{cases}\n0 & i = 0 \\\\\\\\\n\\text{endTime}[i - 1] & i > 0\n\\end{cases}\n$$\n\n$$\nr_i = \\begin{cases}\n\\text{eventTime} & i = n - 1 \\\\\\\\\n\\text{startTime}[i + 1] & i < n - 1\n\\end{cases}\n$$\n\nThe meeting can be moved to the left or right, and the free time in this case is:\n\n$$\nr_i - l_i - w_i\n$$\n\nIf there exists a maximum free time on the left, $\\text{pre}_{i - 1}$, such that $\\text{pre}_{i - 1} \\geq w_i$, then meeting $i$ can be moved to that position on the left, resulting in a new free time:\n\n$$\nr_i - l_i\n$$\n\nSimilarly, if there exists a maximum free time on the right, $\\text{suf}_{i + 1}$, such that $\\text{suf}_{i + 1} \\geq w_i$, then meeting $i$ can be moved to that position on the right, resulting in a new free time:\n\n$$\nr_i - l_i\n$$\n\nTherefore, we first preprocess two arrays, $\\text{pre}$ and $\\text{suf}$, where $\\text{pre}[i]$ represents the maximum free time in the range $[0, i]$, and $\\text{suf}[i]$ represents the maximum free time in the range $[i, n - 1]$. Then, for each meeting $i$, we calculate the maximum free time after moving it, and take the maximum value.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of meetings." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3441, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3442, "explanations": { "1": "We can use a hash table or an array $\\textit{cnt}$ to record the occurrences of each character in the string $s$. Then, we traverse $\\textit{cnt}$ to find the maximum frequency $a$ of characters that appear an odd number of times and the minimum frequency $b$ of characters that appear an even number of times. Finally, we return $a - b$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(|\\Sigma|)$, where $\\Sigma$ is the character set. In this problem, $|\\Sigma| = 26$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 3443, "explanations": { "1": "We can enumerate four cases: $\\textit{SE}$, $\\textit{SW}$, $\\textit{NE}$, and $\\textit{NW}$, and then calculate the maximum Manhattan distance for each case.\n\nWe define a function $\\text{calc}(a, b)$ to calculate the maximum Manhattan distance when the effective directions are $\\textit{a}$ and $\\textit{b}$.\n\nWe define a variable $\\textit{mx}$ to record the current Manhattan distance, a variable $\\textit{cnt}$ to record the number of changes made, and initialize the answer $\\textit{ans}$ to $0$.\n\nTraverse the string $\\textit{s}$. If the current character is $\\textit{a}$ or $\\textit{b}$, increment $\\textit{mx}$ by $1$. Otherwise, if $\\textit{cnt} < k$, increment $\\textit{mx}$ by $1$ and increment $\\textit{cnt}$ by $1$. Otherwise, decrement $\\textit{mx}$ by $1$. Then update $\\textit{ans} = \\max(\\textit{ans}, \\textit{mx})$.\n\nFinally, return the maximum value among the four cases.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $\\textit{s}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3444, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3445, "explanations": { "1": "We want to find a substring $\\textit{subs}$ of string $s$ that satisfies the following conditions:\n\n- The length of $\\textit{subs}$ is at least $k$.\n- The number of occurrences of character $a$ in $\\textit{subs}$ is odd.\n- The number of occurrences of character $b$ in $\\textit{subs}$ is even.\n- Maximize the frequency difference $f_a - f_b$, where $f_a$ and $f_b$ are the number of occurrences of $a$ and $b$ in $\\textit{subs}$, respectively.\n\nThe characters in $s$ are from '0' to '4', so there are 5 possible characters. We can enumerate all different character pairs $(a, b)$, for a total of at most $5 \\times 4 = 20$ combinations. We define:\n\n- Character $a$ is the target character with odd frequency.\n- Character $b$ is the target character with even frequency.\n\nWe use a sliding window to maintain the left and right boundaries of the substring, with variables:\n\n- $l$ denotes the position before the left boundary, so the window is $[l+1, r]$;\n- $r$ is the right boundary, traversing the entire string;\n- $\\textit{curA}$ and $\\textit{curB}$ denote the number of occurrences of $a$ and $b$ in the current window;\n- $\\textit{preA}$ and $\\textit{preB}$ denote the cumulative occurrences of $a$ and $b$ before the left boundary $l$.\n\nWe use a 2D array $t[2][2]$ to record the minimum value of $\\textit{preA} - \\textit{preB}$ for each possible parity combination of the window's left end, where $t[i][j]$ means $\\textit{preA} \\bmod 2 = i$ and $\\textit{preB} \\bmod 2 = j$.\n\nEach time we move $r$ to the right, if the window length satisfies $r - l \\ge k$ and $\\textit{curB} - \\textit{preB} \\ge 2$, we try to move the left boundary $l$ to shrink the window, and update the corresponding $t[\\textit{preA} \\bmod 2][\\textit{preB} \\bmod 2]$.\n\nThen, we try to update the answer:\n\n$$\n\\textit{ans} = \\max(\\textit{ans},\\ \\textit{curA} - \\textit{curB} - t[(\\textit{curA} \\bmod 2) \\oplus 1][\\textit{curB} \\bmod 2])\n$$\n\nIn this way, we can compute the maximum frequency difference for the current window each time $r$ moves to the right.\n\nThe time complexity is $O(n \\times |\\Sigma|^2)$, where $n$ is the length of $s$ and $|\\Sigma|$ is the alphabet size (5 in this problem). The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times |\\Sigma|^2)", "space_complexity": "O(1)" }, { "problem_id": 3446, "explanations": { "1": "We can simulate the diagonal sorting process as described in the problem.\n\nFirst, we sort the diagonals of the lower-left triangle, including the main diagonal, in non-increasing order. Then, we sort the diagonals of the upper-right triangle in non-decreasing order. Finally, we return the sorted matrix.\n\nThe time complexity is $O(n^2 \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the size of the matrix." }, "is_english": true, "time_complexity": "O(n^2 \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3447, "explanations": { "1": "First, we find the maximum value in the array $\\textit{groups}$, denoted as $\\textit{mx}$. We use an array $\\textit{d}$ to record the index corresponding to each element. Initially, $\\textit{d}[x] = -1$ indicates that the element $x$ has not been assigned yet.\n\nThen, we traverse the array $\\textit{elements}$. For each element $x$, if $x > \\textit{mx}$ or $\\textit{d}[x] \\neq -1$, it means that the element $x$ cannot be assigned or has already been assigned, so we skip it directly. Otherwise, starting from $x$, we increment by $x$ each time and set $\\textit{d}[y]$ to $j$, indicating that the element $y$ is assigned to the index $j$.\n\nFinally, we traverse the array $\\textit{groups}$ and obtain the answer based on the records in the $\\textit{d}$ array.\n\nThe time complexity is $O(M \\times \\log m + n)$, and the space complexity is $O(M)$. Here, $n$ and $m$ are the lengths of the arrays $\\textit{groups}$ and $\\textit{elements}$, respectively, while $M$ is the maximum value in the array $\\textit{groups}$." }, "is_english": true, "time_complexity": "O(M \\times \\log m + n)", "space_complexity": "O(M)" }, { "problem_id": 3448, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3449, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3450, "explanations": { "1": "We use a hash table $d$ to store the students on each bench, where the key is the bench number and the value is a set containing the student IDs on that bench.\n\nTraverse the student array $\\textit{students}$ and store the student IDs and bench numbers in the hash table $d$.\n\nFinally, we traverse the values of the hash table $d$ and take the maximum size of the sets, which is the maximum number of different students on a single bench.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the student array $\\textit{students}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3451, "explanations": { "1": "We can determine if an IP address is invalid based on the following conditions:\n\n1. The number of `.` in the IP address is not equal to $3$;\n2. Any octet in the IP address starts with `0`;\n3. Any octet in the IP address is greater than $255$.\n\nThen we group the invalid IP addresses and count the occurrences of each invalid IP address `invalid_count`, and finally sort by `invalid_count` and `ip` in descending order." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3452, "explanations": { "1": "We can traverse the array $\\textit{nums}$ and check each element $\\textit{nums}[i]$ to see if it meets the conditions:\n\n- If $i \\ge k$ and $\\textit{nums}[i] \\le \\textit{nums}[i - k]$, then $\\textit{nums}[i]$ is not a good number.\n- If $i + k < \\textit{len}(\\textit{nums})$ and $\\textit{nums}[i] \\le \\textit{nums}[i + k]$, then $\\textit{nums}[i]$ is not a good number.\n- Otherwise, $\\textit{nums}[i]$ is a good number, and we add it to the answer.\n\nAfter traversing, we return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3453, "explanations": { "1": "According to the problem, we need to find a horizontal line such that the total area of squares above the line equals the total area of squares below the line. Since as the $y$ coordinate increases, the area below the line increases and the area above the line decreases, we can use binary search to find the $y$ coordinate of this horizontal line.\n\nWe define the left boundary of the binary search as $l = 0$, and the right boundary as $r = \\max(y_i + l_i)$, which is the highest point of all squares. Then we calculate the midpoint $mid = (l + r) / 2$ and calculate the area below this horizontal line. If this area is greater than or equal to half of the total area, it means we need to move the right boundary $r$ downward; otherwise, we move the left boundary $l$ upward. We repeat this process until the difference between the left and right boundaries is less than a very small value (e.g., $10^{-5}$).\n\nThe time complexity is $O(n \\log(MU))$, where $n$ is the number of squares, $M = 10^5$, and $U = \\max(y_i + l_i)$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\log(MU))", "space_complexity": "O(1)" }, { "problem_id": 3454, "explanations": { "1": "This problem can be solved using the sweep line algorithm to calculate the total area of all squares.\n\nWe treat the top and bottom boundaries of each square as event points for the sweep line, sorted by $y$ coordinate in ascending order. For each event point, we use a segment tree to maintain the length of the covered $x$-axis interval below the current sweep line, allowing us to calculate the area increment between the current sweep line and the previous one.\n\nThe specific steps are as follows:\n\n1. **Preprocess Event Points**: For each square, calculate the $y$ coordinates of its top and bottom boundaries and add them as event points to the event list. Each event point contains the $y$ coordinate, left boundary $x_1$, right boundary $x_2$, and a flag (indicating whether it's the top or bottom boundary).\n2. **Sort Event Points**: Sort all event points by $y$ coordinate in ascending order.\n3. **Build Segment Tree**: Build a segment tree using the discretized $x$ coordinates to maintain the length of the currently covered $x$-axis intervals.\n4. **Scan Event Points**: Traverse the sorted event point list. For each event point:\n - Calculate the area increment between the current event point and the previous one, and add it to the total area.\n - Based on the type of the current event point (top or bottom boundary), update the segment tree by increasing or decreasing the coverage count of the corresponding $x$-axis interval.\n5. **Calculate Target Area**: The target area is half of the total area.\n6. **Scan Event Points Again**: Traverse the event point list again, calculating the cumulative area. When the cumulative area reaches the target area, calculate and return the corresponding $y$ coordinate.\n\nThe time complexity is $O(n \\times \\log n)$ and the space complexity is $O(n)$, where $n$ is the number of squares." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3455, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3456, "explanations": { "1": "The problem essentially asks us to find each segment of consecutive identical characters and then determine if there exists a substring of length $k$. If such a substring exists, return $\\textit{true}$; otherwise, return $\\textit{false}$.\n\nWe can use two pointers $l$ and $r$ to traverse the string $s$. When $s[l] = s[r]$, move $r$ to the right until $s[r] \\neq s[l]$. At this point, check if $r - l$ equals $k$. If it does, return $\\textit{true}$; otherwise, move $l$ to $r$ and continue traversing.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3457, "explanations": { "1": "According to the problem description, we can eat $4$ pizzas each day. On odd days, we get the maximum value among these $4$ pizzas, and on even days, we get the second largest value among these $4$ pizzas.\n\nTherefore, we can sort the pizzas by weight in ascending order. We can eat for $\\textit{days} = n / 4$ days, with $\\textit{odd} = (\\textit{days} + 1) / 2$ days being odd days and $\\textit{even} = \\textit{days} - \\textit{odd}$ days being even days.\n\nFor odd days, we can choose the largest $\\textit{odd}$ pizzas and the smallest $\\textit{odd} \\times 3$ pizzas, with the increased weight being $\\sum_{i = n - \\textit{odd}}^{n - 1} \\textit{pizzas}[i]$.\n\nFor even days, among the remaining pizzas, we greedily choose the largest two pizzas and the smallest two pizzas each time, with the increased weight being $\\sum_{i = n - \\textit{odd} - 2}^{n - \\textit{odd} - 2 \\times \\textit{even}} \\textit{pizzas}[i]$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Here, $n$ is the length of the array $\\textit{pizzas}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 3458, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3459, "explanations": { "1": "We design a function $\\text{dfs}(i, j, k, \\textit{cnt})$ that returns the length of the longest V-shaped diagonal segment, where $(i, j)$ is the previous position, $k$ is the current direction, and $\\textit{cnt}$ is the remaining number of allowed turns.\n\nThe logic of the $\\text{dfs}$ function is as follows:\n\nFirst, based on the previous position and the current direction, we calculate the current position $(x, y)$ and determine the target value $\\textit{target}$. If $x$ or $y$ is out of bounds, or if $\\textit{grid}[x][y] \\neq \\textit{target}$, we return $0$.\n\nOtherwise, we have two choices:\n\nContinue moving in the current direction.\nMake a 90-degree clockwise turn at the current position and then continue moving.\nTo implement the turn, if the current direction is $k$, the new direction after a 90-degree clockwise turn is $(k + 1) \\bmod 4$. We take the maximum result from these two choices as the result for the current state.\n\nIn the main function, we iterate over the entire matrix. For each position with value 1, we try searching in all four directions and update the answer.\n\nAfter the traversal, we return the answer.\n\nTo avoid repeated calculations, we use memoization to cache intermediate results.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns in the matrix, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 3460, "explanations": { "1": "We record the lengths of the strings $s$ and $t$ as $n$ and $m$, respectively. Then, we use two pointers $i$ and $j$ to point to the beginning of the strings $s$ and $t$, and use a boolean variable $\\textit{rem}$ to record whether a character has been removed.\n\nNext, we start traversing the strings $s$ and $t$. If $s[i]$ is not equal to $t[j]$, we check if a character has already been removed. If a character has been removed, we exit the loop; otherwise, we mark that a character has been removed and skip $s[i]$. Otherwise, we skip both $s[i]$ and $t[j]$. Continue traversing until $i \\geq n$ or $j \\geq m$.\n\nFinally, return $j$.\n\nThe time complexity is $O(n+m)$, where $n$ and $m$ are the lengths of the strings $s$ and $t$, respectively." }, "is_english": true, "time_complexity": "O(n+m)", "space_complexity": null }, { "problem_id": 3461, "explanations": { "1": "We can simulate the operations described in the problem until the string $s$ contains exactly two digits, and then check if these two digits are the same.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 3462, "explanations": { "1": "We can use a priority queue (min-heap) $\\textit{pq}$ to maintain the largest $k$ elements.\n\nTraverse each row, sort the elements in each row, and then take the largest $\\textit{limit}$ elements from each row and add them to $\\textit{pq}$. If the size of $\\textit{pq}$ exceeds $k$, pop the top element of the heap.\n\nFinally, sum the elements in $\\textit{pq}$.\n\nThe time complexity is $O(n \\times m \\times (\\log m + \\log k))$, and the space complexity is $O(k)$. Here, $n$ and $m$ are the number of rows and columns of the matrix $\\textit{grid}$, respectively." }, "is_english": true, "time_complexity": "O(n \\times m \\times (\\log m + \\log k))", "space_complexity": "O(k)" }, { "problem_id": 3463, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3464, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3465, "explanations": { "1": "According to the problem statement, we need to find all products that contain a valid serial number, and the rules for a valid serial number are:\n\n- Starts with `SN` (case-sensitive).\n- Followed by 4 digits.\n- Must have a hyphen `-`, followed by 4 digits.\n\nBased on the above rules, we can use a regular expression to match valid serial numbers, then filter out the products that contain valid serial numbers, and finally sort them in ascending order by `product_id`." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3466, "explanations": { "1": "We design a function $\\textit{dfs}(i, j, k)$, which represents the maximum number of coins Mario can collect starting from position $i$, currently on lane $j$, with $k$ lane changes remaining. The answer is the maximum value of $\\textit{dfs}(i, 0, 2)$ for all $i$.\n\nThe function $\\textit{dfs}(i, j, k)$ is calculated as follows:\n\n- If $i \\geq n$, it means Mario has reached the end, return 0;\n- If no lane change is made, Mario can drive 1 mile, then exit, or continue driving, taking the maximum of the two, i.e., $\\max(x, \\textit{dfs}(i + 1, j, k) + x)$;\n- If a lane change is possible, there are two choices: drive 1 mile and then change lanes, or change lanes directly, taking the maximum of these two cases, i.e., $\\max(\\textit{dfs}(i + 1, j \\oplus 1, k - 1) + x, \\textit{dfs}(i, j \\oplus 1, k - 1))$.\n- Where $x$ represents the number of coins at the current position.\n\nTo avoid repeated calculations, we use memoized search to store the results that have already been computed.\n\nTime complexity is $O(n)$, and space complexity is $O(n)$. Where $n$ represents the length of the lanes." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3467, "explanations": { "1": "We can traverse the array $\\textit{nums}$ and count the number of even elements $\\textit{even}$. Then, we set the first $\\textit{even}$ elements of the array to $0$ and the remaining elements to $1$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3468, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3469, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3470, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3471, "explanations": { "1": "If $k = 1$, then each element in the array forms a subarray of size $1$. In this case, we only need to find the maximum value among the elements that appear exactly once in the array.\n\nIf $k = n$, then the entire array forms a subarray of size $n$. In this case, we only need to return the maximum value in the array.\n\nIf $1 < k < n$, only $\\textit{nums}[0]$ and $\\textit{nums}[n-1]$ can be the almost missing integers. If they appear elsewhere in the array, they are not almost missing integers. Therefore, we only need to check if $\\textit{nums}[0]$ and $\\textit{nums}[n-1]$ appear elsewhere in the array and return the maximum value among them.\n\nIf no almost missing integer exists, return $-1$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3472, "explanations": { "1": "We design a function $\\textit{dfs}(i, j, k)$, which represents the length of the longest palindromic subsequence that can be obtained in the substring $s[i..j]$ with at most $k$ operations. The answer is $\\textit{dfs}(0, n - 1, k)$.\n\nThe calculation process of the function $\\textit{dfs}(i, j, k)$ is as follows:\n\n- If $i > j$, return $0$;\n- If $i = j$, return $1$;\n- Otherwise, we can ignore $s[i]$ or $s[j]$ and calculate $\\textit{dfs}(i + 1, j, k)$ and $\\textit{dfs}(i, j - 1, k)$ respectively; or we can change $s[i]$ and $s[j]$ to the same character and calculate $\\textit{dfs}(i + 1, j - 1, k - t) + 2$, where $t$ is the ASCII code difference between $s[i]$ and $s[j]$.\n- Return the maximum value of the above three cases.\n\nTo avoid repeated calculations, we use memoized search.\n\nThe time complexity is $O(n^2 \\times k)$, and the space complexity is $O(n^2 \\times k)$. Where $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n^2 \\times k)", "space_complexity": "O(n^2 \\times k)" }, { "problem_id": 3473, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3474, "explanations": { "1": "Let $str1$ be $s$ and $str2$ be $t$.\n\nWe can use a string $ans$ of length $n + m - 1$ to store the generated string, where each character of $ans$ is initially set to $'a'$. We also need a boolean array $fixed$ of length $n + m - 1$ to record which positions in $ans$ have already been fixed.\n\nFirst, we iterate through the string $s$. For each index $i$, if $s[i]$ is 'T', we need to set the substring of $ans$ starting at index $i$ with length $m$ to $t$. During this process, if we find that a position has already been fixed and the character does not match the corresponding character in $t$, it means it is impossible to generate a valid string, so we return an empty string immediately.\n\nNext, we iterate through $s$ again. For each index $i$, if $s[i]$ is 'F', we need to check whether the substring of $ans$ starting at index $i$ with length $m$ is equal to $t$. If it is, we need to find a position in this substring and change its character to 'b' (since 'b' is lexicographically greater than 'a'), to ensure this substring is not equal to $t$. If we cannot find such a position, it means it is impossible to generate a valid string, so we return an empty string immediately.\n\nFinally, we concatenate the characters in $ans$ into a string and return it.\n\nThe time complexity is $O(n \\times m)$, and the space complexity is $O(n + m)$." }, "is_english": true, "time_complexity": "O(n \\times m)", "space_complexity": "O(n + m)" }, { "problem_id": 3475, "explanations": { "1": "We can use `LIKE` and `REGEXP` for pattern matching, where:\n\n- LIKE `'ATG%'` checks if it starts with ATG\n- REGEXP `'TAA$|TAG$|TGA$'` checks if it ends with TAA, TAG, or TGA ($ indicates the end of the string)\n- LIKE `'%ATAT%'` checks if it contains ATAT\n- REGEXP `'GGG+'` checks if it contains at least 3 consecutive Gs" }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3476, "explanations": { "1": "Since each task can only be completed by a worker with a specific skill, we can group the tasks by skill requirements and store them in a hash table $\\textit{d}$, where the key is the skill requirement and the value is a priority queue sorted by profit in descending order.\n\nThen, we iterate through the workers. For each worker, we find the corresponding priority queue in the hash table $\\textit{d}$ based on their skill requirement, take the front element (i.e., the maximum profit the worker can earn), and remove it from the priority queue. If the priority queue is empty, we remove it from the hash table.\n\nFinally, we add the maximum profit from the remaining tasks to the result.\n\nThe time complexity is $O((n + m) \\times \\log m)$, and the space complexity is $O(m)$. Where $n$ and $m$ are the number of workers and tasks, respectively." }, "is_english": true, "time_complexity": "O((n + m) \\times \\log m)", "space_complexity": "O(m)" }, { "problem_id": 3477, "explanations": { "1": "We use a boolean array $\\textit{vis}$ of length $n$ to record the baskets that have already been used, and a variable $\\textit{ans}$ to record the number of fruits that have not been placed, initially $\\textit{ans} = n$.\n\nNext, we traverse each fruit $x$. For the current fruit, we traverse all the baskets to find the first unused basket $i$ with a capacity greater than or equal to $x$. If found, we decrement $\\textit{ans}$ by $1$.\n\nAfter traversing, we return the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{fruits}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3478, "explanations": { "1": "We can convert the array $\\textit{nums1}$ into an array $\\textit{arr}$, where each element is a tuple $(x, i)$, representing the value $x$ at index $i$ in $\\textit{nums1}$. Then, we sort the array $\\textit{arr}$ in ascending order by $x$.\n\nWe use a min-heap $\\textit{pq}$ to maintain the elements from the array $\\textit{nums2}$. Initially, $\\textit{pq}$ is empty. We use a variable $\\textit{s}$ to record the sum of the elements in $\\textit{pq}$. Additionally, we use a pointer $j$ to maintain the current position in the array $\\textit{arr}$ that needs to be added to $\\textit{pq}$.\n\nWe traverse the array $\\textit{arr}$. For the $h$-th element $(x, i)$, we add all elements $\\textit{nums2}[\\textit{arr}[j][1]]$ to $\\textit{pq}$ that satisfy $j < h$ and $\\textit{arr}[j][0] < x$, and add these elements to $\\textit{s}$. If the size of $\\textit{pq}$ exceeds $k$, we pop the smallest element from $\\textit{pq}$ and subtract it from $\\textit{s}$. Then, we update the value of $\\textit{ans}[i]$ to $\\textit{s}$.\n\nAfter traversing, we return the answer array $\\textit{ans}$.\n\nThe time complexity is $O(n \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3479, "explanations": { "1": "We can use a segment tree to maintain the maximum basket capacity in an interval, which allows us to quickly find the first basket with capacity greater than or equal to the fruit quantity through binary search. If no such basket is found, we increment the answer by one; if found, we set that basket's capacity to zero, indicating that the basket has been used.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$, where $n$ is the length of $\\textit{baskets}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3480, "explanations": { "1": "We store all conflicting pairs $(a, b)$ (assuming $a < b$) in a list $g$, where $g[a]$ represents the set of all numbers $b$ that conflict with $a$.\n\nIf no deletion occurs, we can enumerate each subarray's left endpoint $a$ in reverse order. The upper bound of its right endpoint is the minimum value $b_1$ among all $g[x \\geq a]$ (excluding $b_1$), and the contribution to the answer is $b_1 - a$.\n\nIf we delete a conflicting pair containing $b_1$, then the new $b_1$ becomes the second minimum value $b_2$ among all $g[x \\geq a]$, and its additional contribution to the answer is $b_2 - b_1$. We use an array $\\text{cnt}$ to record the additional contribution for each $b_1$.\n\nThe final answer is the sum of all $b_1 - a$ contributions plus the maximum value of $\\text{cnt}[b_1]$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of conflicting pairs." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3481, "explanations": { "1": "We use a hash table $\\textit{d}$ to store the substitution mapping, and then define a function $\\textit{dfs}$ to recursively replace the placeholders in the string.\n\nThe execution logic of the function $\\textit{dfs}$ is as follows:\n\n1. Find the starting position $i$ of the first placeholder in the string $\\textit{s}$. If not found, return $\\textit{s}$;\n2. Find the ending position $j$ of the first placeholder in the string $\\textit{s}$. If not found, return $\\textit{s}$;\n3. Extract the key of the placeholder, and then recursively replace the value of the placeholder $d[key]$;\n4. Return the replaced string.\n\nIn the main function, we call the $\\textit{dfs}$ function, pass in the text string $\\textit{text}$, and return the result.\n\nThe time complexity is $O(m + n \\times L)$, and the space complexity is $O(m + n \\times L)$. Where $m$ is the length of the substitution mapping, and $n$ and $L$ are the length of the text string and the average length of the placeholders, respectively." }, "is_english": true, "time_complexity": "O(m + n \\times L)", "space_complexity": "O(m + n \\times L)" }, { "problem_id": 3482, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3483, "explanations": { "1": "We use a hash set $\\textit{s}$ to record all distinct three-digit even numbers, and then enumerate all possible three-digit even numbers to add them to the hash set.\n\nFinally, we return the size of the hash set.\n\nThe time complexity is $O(n^3)$, and the space complexity is $O(n^3)$. Where $n$ is the length of the array $\\textit{digits}$." }, "is_english": true, "time_complexity": "O(n^3)", "space_complexity": "O(n^3)" }, { "problem_id": 3484, "explanations": { "1": "We use a hash table $\\textit{d}$ to record the values of all cells, where the key is the cell reference and the value is the cell's value.\n\nWhen calling the `setCell` method, we store the cell reference and value in the hash table.\n\nWhen calling the `resetCell` method, we remove the cell reference from the hash table.\n\nWhen calling the `getValue` method, we split the formula into two cell references, calculate their values, and then return their sum.\n\nThe time complexity is $O(L)$, and the space complexity is $O(L)$. Where $L$ is the length of the formula." }, "is_english": true, "time_complexity": "O(L)", "space_complexity": "O(L)" }, { "problem_id": 3485, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3486, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3487, "explanations": { "1": "We first find the maximum value $\\textit{mx}$ in the array. If $\\textit{mx} \\leq 0$, then all elements in the array are less than or equal to 0. Since we need to select a non-empty subarray with the maximum element sum, the maximum element sum would be $\\textit{mx}$.\n\nIf $\\textit{mx} > 0$, then we need to find all distinct positive integers in the array such that their sum is maximized. We can use a hash table $\\textit{s}$ to record all distinct positive integers, and then iterate through the array, adding up all distinct positive integers.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3488, "explanations": { "1": "According to the problem description, we need to find the minimum distance between each element in the array and its previous identical element, as well as the minimum distance to its next identical element. Since the array is circular, we need to consider the circular nature of the array. We can extend the array to twice its original length, and then use hash tables $\\textit{left}$ and $\\textit{right}$ to record the positions where each element last appeared and will next appear, respectively. We calculate the minimum distance between each position's element and another identical element, recording it in the array $\\textit{d}$. Finally, we traverse the queries, and for each query $i$, we take the minimum value of $\\textit{d}[i]$ and $\\textit{d}[i+n]$. If this value is greater than or equal to $n$, it means there is no element identical to the queried element, so we return $-1$; otherwise, we return the value.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3489, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3490, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3491, "explanations": { "1": "We can first sort the array $\\textit{numbers}$ based on the length of strings. Then, we iterate through each string $\\textit{s}$ in the array and check if there is any previous string $\\textit{t}$ that is a prefix of $\\textit{s}$. If such a string exists, it means there is a string that is a prefix of another string, so we return $\\textit{false}$. If we have checked all strings and haven't found any prefix relationships, we return $\\textit{true}$.\n\nThe time complexity is $O(n^2 \\times m + n \\times \\log n)$, and the space complexity is $O(m + \\log n)$, where $n$ is the length of the array $\\textit{numbers}$, and $m$ is the average length of strings in the array $\\textit{numbers}$." }, "is_english": true, "time_complexity": "O(n^2 \\times m + n \\times \\log n)", "space_complexity": "O(m + \\log n)" }, { "problem_id": 3492, "explanations": { "1": "First, we calculate the maximum weight the boat can carry, which is $n \\times n \\times w$. Then, we take the minimum of this value and $\\text{maxWeight}$, and divide it by $w$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 3493, "explanations": { "1": "We first convert each attribute array into a hash table and store them in a hash table array $\\textit{ss}$. We define a graph $\\textit{g}$, where $\\textit{g}[i]$ stores the indices of attribute arrays that are connected to $\\textit{properties}[i]$.\n\nThen, we iterate through all attribute hash tables. For each pair of attribute hash tables $(i, j)$ where $j < i$, we check whether the number of common elements between them is at least $k$. If so, we add an edge from $i$ to $j$ in the graph $\\textit{g}$, as well as an edge from $j$ to $i$.\n\nFinally, we use Depth-First Search (DFS) to compute the number of connected components in the graph $\\textit{g}$.\n\nThe time complexity is $O(n^2 \\times m)$, and the space complexity is $O(n \\times m)$, where $n$ is the length of the attribute arrays and $m$ is the number of elements in an attribute array." }, "is_english": true, "time_complexity": "O(n^2 \\times m)", "space_complexity": "O(n \\times m)" }, { "problem_id": 3494, "explanations": { "1": "We define $f[i]$ as the time when wizard $i$ completes the previous potion.\n\nFor the current potion $x$, we need to calculate the completion time for each wizard. Let $\\textit{tot}$ represent the completion time of the current potion, initially $\\textit{tot} = 0$.\n\nFor each wizard $i$, the time he starts processing the current potion is $\\max(\\textit{tot}, f[i])$, and the time required to process this potion is $skill[i] \\times mana[x]$. Therefore, the time he completes this potion is $\\max(\\textit{tot}, f[i]) + skill[i] \\times mana[x]$. We update $\\textit{tot}$ to this value.\n\nSince the brewing process requires that the potion must be immediately passed to the next wizard and processing must start immediately after the current wizard completes their work, we need to update the completion time $f[i]$ for each wizard's previous potion. For the last wizard $n-1$, we directly update $f[n-1]$ to $\\textit{tot}$. For other wizards $i$, we can update $f[i]$ by traversing in reverse order, specifically, $f[i] = f[i+1] - skill[i+1] \\times mana[x]$.\n\nFinally, $f[n-1]$ is the minimum total time required to complete brewing all potions.\n\nThe time complexity is $O(n \\times m)$ and the space complexity is $O(n)$, where $n$ and $m$ are the number of wizards and potions respectively." }, "is_english": true, "time_complexity": "O(n \\times m)", "space_complexity": "O(n)" }, { "problem_id": 3495, "explanations": { "1": "According to the problem description, suppose the minimum number of operations required to make an element $x$ become $0$ is $p$, where $p$ is the smallest integer such that $4^p > x$.\n\nOnce we know the minimum number of operations for each element, for a range $[l, r]$, let $s$ be the sum of the minimum operations for all elements in $[l, r]$, and let $mx$ be the maximum number of operations, which is the number of operations for element $r$. Then, the minimum number of operations to make all elements in $[l, r]$ become $0$ is $\\max(\\lceil s / 2 \\rceil, mx)$.\n\nWe define a function $f(x)$ to represent the sum of the minimum operations for all elements in the range $[1, x]$. For each query $[l, r]$, we can compute $s = f(r) - f(l - 1)$ and $mx = f(r) - f(r - 1)$ to obtain the answer.\n\nThe time complexity is $O(q \\log M)$, where $q$ is the number of queries and $M$ is the maximum value in the query range. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(q \\log M)", "space_complexity": "O(1)" }, { "problem_id": 3496, "explanations": { "1": "According to the problem description, each operation removes the two elements at the endpoints. Therefore, when the number of elements is odd, one element will eventually remain; when the number of elements is even, two consecutive elements in the array will eventually remain.\n\nTo maximize the score after deletions, we should minimize the remaining elements.\n\nThus, if the array $\\textit{nums}$ has an odd number of elements, the answer is the sum of all elements $s$ in the array $\\textit{nums}$ minus the minimum value $\\textit{mi}$ in $\\textit{nums}$; if the array $\\textit{nums}$ has an even number of elements, the answer is the sum of all elements $s$ in the array $\\textit{nums}$ minus the minimum sum of any two consecutive elements.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3497, "explanations": { "1": "First, we filter the data in the table to exclude all records where `activity_type` is equal to `cancelled`. Then, we group the remaining data by `user_id` and `activity_type`, calculate the duration `duration` for each group, and store the results in table `T`.\n\nNext, we filter table `T` to extract records where `activity_type` is `free_trial` and `paid`, storing them in tables `F` and `P`, respectively. Finally, we perform an equi-join on these two tables using `user_id`, filter the required fields as per the problem statement, and sort the results to produce the final output." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3498, "explanations": { "1": "We can simulate the reverse degree of each character in the string. For each character, calculate its position in the reverse alphabet, multiply it by its position in the string, and then sum up all the results.\n\nTime complexity is $O(n)$, where $n$ is the length of the string. Space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3499, "explanations": { "1": "The problem is essentially equivalent to finding the number of `'1'` characters in the string $\\textit{s}$, plus the maximum number of `'0'` characters in two adjacent consecutive `'0'` segments.\n\nThus, we can use two pointers to traverse the string $\\textit{s}$. Use a variable $\\textit{mx}$ to record the maximum number of `'0'` characters in two adjacent consecutive `'0'` segments. We also need a variable $\\textit{pre}$ to record the number of `'0'` characters in the previous consecutive `'0'` segment.\n\nEach time, we count the number of consecutive identical characters $\\textit{cnt}$. If the current character is `'1'`, add $\\textit{cnt}$ to the answer. If the current character is `'0'`, update $\\textit{mx}$ as $\\textit{mx} = \\max(\\textit{mx}, \\textit{pre} + \\textit{cnt})$, and update $\\textit{pre}$ to $\\textit{cnt}$. Finally, add $\\textit{mx}$ to the answer.\n\nTime complexity is $O(n)$, where $n$ is the length of the string $\\textit{s}$. Space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3500, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3501, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3502, "explanations": { "1": "According to the problem description, the minimum cost for each position $i$ is the minimum cost from $0$ to $i$. We can use a variable $\\textit{mi}$ to record the minimum cost from $0$ to $i$.\n\nStarting from $0$, we iterate through each position $i$, updating $\\textit{mi}$ as $\\text{min}(\\textit{mi}, \\text{cost}[i])$ at each step, and assign $\\textit{mi}$ to the $i$-th position of the answer array.\n\nFinally, return the answer array.\n\nTime complexity is $O(n)$, where $n$ is the length of the array $\\textit{cost}$. Ignoring the space used by the answer array, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3503, "explanations": { "1": "According to the problem description, the concatenated palindrome string can be composed entirely of string $s$, entirely of string $t$, or a combination of both strings $s$ and $t$. Additionally, there may be extra palindromic substrings in either string $s$ or $t$.\n\nTherefore, we first reverse string $t$ and preprocess arrays $\\textit{g1}$ and $\\textit{g2}$, where $\\textit{g1}[i]$ represents the length of the longest palindromic substring starting at index $i$ in string $s$, and $\\textit{g2}[i]$ represents the length of the longest palindromic substring starting at index $i$ in string $t$.\n\nWe can initialize the answer $\\textit{ans}$ as the maximum value in $\\textit{g1}$ and $\\textit{g2}$.\n\nNext, we define $\\textit{f}[i][j]$ as the length of the palindromic substring ending at the $i$-th character of string $s$ and the $j$-th character of string $t$.\n\nFor $\\textit{f}[i][j]$, if $s[i - 1]$ equals $t[j - 1]$, then $\\textit{f}[i][j] = \\textit{f}[i - 1][j - 1] + 1$. We then update the answer:\n\n$$\n\\textit{ans} = \\max(\\textit{ans}, \\textit{f}[i][j] \\times 2 + (0 \\text{ if } i \\geq m \\text{ else } \\textit{g1}[i])) \\\\\n\\textit{ans} = \\max(\\textit{ans}, \\textit{f}[i][j] \\times 2 + (0 \\text{ if } j \\geq n \\text{ else } \\textit{g2}[j]))\n$$\n\nFinally, we return the answer $\\textit{ans}$.\n\nThe time complexity is $O(m \\times (m + n))$, and the space complexity is $O(m \\times n)$, where $m$ and $n$ are the lengths of strings $s$ and $t$, respectively." }, "is_english": true, "time_complexity": "O(m \\times (m + n))", "space_complexity": "O(m \\times n)" }, { "problem_id": 3504, "explanations": { "1": "According to the problem description, the concatenated palindrome string can be composed entirely of string $s$, entirely of string $t$, or a combination of both strings $s$ and $t$. Additionally, there may be extra palindromic substrings in either string $s$ or $t$.\n\nTherefore, we first reverse string $t$ and preprocess arrays $\\textit{g1}$ and $\\textit{g2}$, where $\\textit{g1}[i]$ represents the length of the longest palindromic substring starting at index $i$ in string $s$, and $\\textit{g2}[i]$ represents the length of the longest palindromic substring starting at index $i$ in string $t$.\n\nWe can initialize the answer $\\textit{ans}$ as the maximum value in $\\textit{g1}$ and $\\textit{g2}$.\n\nNext, we define $\\textit{f}[i][j]$ as the length of the palindromic substring ending at the $i$-th character of string $s$ and the $j$-th character of string $t$.\n\nFor $\\textit{f}[i][j]$, if $s[i - 1]$ equals $t[j - 1]$, then $\\textit{f}[i][j] = \\textit{f}[i - 1][j - 1] + 1$. We then update the answer:\n\n$$\n\\textit{ans} = \\max(\\textit{ans}, \\textit{f}[i][j] \\times 2 + (0 \\text{ if } i \\geq m \\text{ else } \\textit{g1}[i])) \\\\\n\\textit{ans} = \\max(\\textit{ans}, \\textit{f}[i][j] \\times 2 + (0 \\text{ if } j \\geq n \\text{ else } \\textit{g2}[j]))\n$$\n\nFinally, we return the answer $\\textit{ans}$.\n\nThe time complexity is $O(m \\times (m + n))$, and the space complexity is $O(m \\times n)$, where $m$ and $n$ are the lengths of strings $s$ and $t$, respectively." }, "is_english": true, "time_complexity": "O(m \\times (m + n))", "space_complexity": "O(m \\times n)" }, { "problem_id": 3505, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3506, "explanations": { "1": "First, consider the case where there is only one type of bacteria. In this case, there is no need to split the white blood cell (WBC); it can directly eliminate the bacteria, and the time cost is $\\textit{timeSeq}[0]$.\n\nIf there are two types of bacteria, the WBC needs to split into two, and each WBC eliminates one type of bacteria. The time cost is $\\textit{splitTime} + \\max(\\textit{timeSeq}[0], \\textit{timeSeq}[1])$.\n\nIf there are more than two types of bacteria, at each step, we need to consider splitting the WBCs into multiple cells, which is difficult to handle with a forward-thinking approach.\n\nInstead, we can adopt a reverse-thinking approach: instead of splitting the WBCs, we merge the bacteria. We select any two types of bacteria $i$ and $j$ to merge into a new type of bacteria. The time cost for this merge is $\\textit{splitTime} + \\max(\\textit{timeSeq}[i], \\textit{timeSeq}[j])$.\n\nTo minimize the involvement of bacteria with long elimination times in the merging process, we can greedily select the two bacteria with the smallest elimination times for merging at each step. Therefore, we can maintain a min-heap, repeatedly extracting the two bacteria with the smallest elimination times and merging them until only one type of bacteria remains. The elimination time of this final bacteria is the answer.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$, where $n$ is the number of bacteria." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3507, "explanations": { "1": "We define a function $\\text{is\\_non\\_decreasing}(a)$ to determine whether the array $a$ is a non-decreasing array.\n\nWe use a loop until the array $arr$ becomes a non-decreasing array. In each iteration of the loop, we find the minimum sum of adjacent element pairs in the array $arr$ and record the index $k$ of the left element of that pair. Then, we replace the left element with the sum of the pair and remove the right element. Finally, we return the number of operations.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 3508, "explanations": { "1": "We use a hash map $\\textit{vis}$ to store the hash values of packets that have already been added, a queue $\\textit{q}$ to store the packets currently in the router, a hash map $\\textit{idx}$ to record the number of packets already forwarded for each destination, and a hash map $\\textit{d}$ to store the list of timestamps for each destination.\n\nFor the $\\textit{addPacket}$ method, we compute the hash value of the packet. If it already exists in $\\textit{vis}$, we return $\\text{false}$; otherwise, we add it to $\\textit{vis}$, check if the current queue size exceeds the memory limit, and if so, call the $\\textit{forwardPacket}$ method to remove the oldest packet. Then, we add the new packet to the queue and append its timestamp to the corresponding destination's timestamp list, finally returning $\\text{true}$. The time complexity is $O(1)$.\n\nFor the $\\textit{forwardPacket}$ method, if the queue is empty, we return an empty array; otherwise, we remove the packet at the head of the queue, delete its hash value from $\\textit{vis}$, update the number of forwarded packets for the corresponding destination, and return the packet. The time complexity is $O(1)$.\n\nFor the $\\textit{getCount}$ method, we get the timestamp list and the number of forwarded packets for the given destination, then use binary search to find the number of timestamps within the specified range, and return that count. The time complexity is $O(\\log n)$, where $n$ is the length of the timestamp list.\n\nThe space complexity is $O(n)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(n)" }, { "problem_id": 3509, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3510, "explanations": { "1": "We define a sorted set $\\textit{sl}$ to store tuples $(\\textit{s}, i)$ of the sum of all adjacent element pairs and their left index, define another sorted set $\\textit{idx}$ to store the indices of remaining elements in the current array, and use the variable $\\textit{inv}$ to record the number of inversions in the current array. Initially, we traverse the array $\\textit{nums}$, add tuples of the sum of all adjacent element pairs and their left index to the sorted set $\\textit{sl}$, and calculate the number of inversions $\\textit{inv}$.\n\nIn each operation, we retrieve the element pair $(\\textit{s}, i)$ with the minimum sum from the sorted set $\\textit{sl}$. Then we can determine that the element pair corresponding to indices $i$ and $j$ (where $j$ is the next index after $i$ in the sorted set $\\textit{idx}$) is the adjacent element pair with the minimum sum in the current array. If $nums[i] > nums[j]$, this element pair is an inversion, and after merging and replacing, the number of inversions $\\textit{inv}$ decreases by one.\n\nNext, we need to update the element pairs related to indices $i$ and $j$:\n\n1. If index $i$ has a predecessor index $h$ in the sorted set $\\textit{idx}$, we need to update the element pair $(h, i)$. If $nums[h] > nums[i]$, this element pair is an inversion, and after merging and replacing, the number of inversions $\\textit{inv}$ decreases by one. Then, we remove the element pair $(h, i)$ from the sorted set $\\textit{sl}$ and add the new element pair $(h, s)$ to the sorted set $\\textit{sl}$. If $nums[h] > s$, the new element pair is an inversion, and after merging and replacing, the number of inversions $\\textit{inv}$ increases by one.\n\n2. If index $j$ has a successor index $k$ in the sorted set $\\textit{idx}$, we need to update the element pair $(j, k)$. If $nums[j] > nums[k]$, this element pair is an inversion, and after merging and replacing, the number of inversions $\\textit{inv}$ decreases by one. Then, we remove the element pair $(j, k)$ from the sorted set $\\textit{sl}$ and add the new element pair $(s, k)$ to the sorted set $\\textit{sl}$. If $s > nums[k]$, the new element pair is an inversion, and after merging and replacing, the number of inversions $\\textit{inv}$ increases by one.\n\nNext, we replace the element at index $i$ with $\\textit{s}$ and remove index $j$ from the sorted set $\\textit{idx}$. We repeat the above process until the number of inversions $\\textit{inv}$ becomes zero. Finally, the number of operations is the minimum number of operations required to make the array non-decreasing.\n\nThe time complexity is $O(n \\log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3511, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3512, "explanations": { "1": "The problem essentially asks for the result of the sum of the array elements modulo $k$. Therefore, we only need to iterate through the array, calculate the sum of all elements, and then take the modulo $k$. Finally, return this result.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3513, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3514, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3515, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3516, "explanations": { "1": "We calculate the distance $a$ between the 1st person and the 3rd person, and the distance $b$ between the 2nd person and the 3rd person.\n\n- If $a = b$, it means both people arrive at the same time, return $0$;\n- If $a \\lt b$, it means the 1st person will arrive first, return $1$;\n- Otherwise, it means the 2nd person will arrive first, return $2$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 3517, "explanations": { "1": "We first count the occurrence of each character in the string and record it in a hash table or array $\\textit{cnt}$. Since the string is a palindrome, the count of each character is either even, or there is exactly one character with an odd count.\n\nNext, starting from the lexicographically smallest character, we sequentially add half of each character's count to the first half of the result string $\\textit{t}$. If a character appears an odd number of times, we record it as the middle character $\\textit{ch}$. Finally, we concatenate $\\textit{t}$, $\\textit{ch}$, and the reverse of $\\textit{t}$ to obtain the final lexicographically smallest palindromic rearrangement.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(|\\Sigma|)$, where $|\\Sigma|$ is the size of the character set, which is $26$ in this problem." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 3518, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3519, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3520, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3521, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3522, "explanations": { "1": "We can simulate the process based on the problem description.\n\nDefine a boolean array $\\textit{vis}$ of length $n$ to record whether each instruction has been executed. Initially, all elements are set to $\\text{false}$.\n\nThen, starting from index $i = 0$, perform the following steps in a loop:\n\n1. Set $\\textit{vis}[i]$ to $\\text{true}$.\n2. If the first character of $\\textit{instructions}[i]$ is 'a', add $\\textit{value}[i]$ to the answer and increment $i$ by $1$. Otherwise, increment $i$ by $\\textit{value}[i]$.\n\nThe loop continues until $i \\lt 0$, $i \\ge n$, or $\\textit{vis}[i]$ is $\\text{true}$.\n\nFinally, return the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{value}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3523, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3524, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3525, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3526, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3527, "explanations": { "1": "We can use a hash table $\\textit{cnt}$ to count the occurrences of each response. For the responses of each day, we first remove duplicates, then add each response to the hash table and update its count.\n\nFinally, we iterate through the hash table to find the response with the highest count. If there are multiple responses with the same count, we return the lexicographically smallest one.\n\nThe complexity is $O(L)$, and the space complexity is $O(L)$, where $L$ is the total length of all responses." }, "is_english": true, "time_complexity": null, "space_complexity": "O(L)" }, { "problem_id": 3528, "explanations": { "1": "Since the problem guarantees that unit 0 can be converted to any other unit through a unique conversion path, we can use Depth-First Search (DFS) to traverse all unit conversion relationships. Additionally, since the length of the $\\textit{conversions}$ array is $n - 1$, representing $n - 1$ conversion relationships, we can treat the unit conversion relationships as a tree, where the root node is unit 0, and the other nodes are the other units.\n\nWe can use an adjacency list $g$ to represent the unit conversion relationships, where $g[i]$ represents the units that unit $i$ can convert to and the corresponding conversion factors.\n\nThen, we start the DFS from the root node $0$, i.e., call the function $\\textit{dfs}(s, \\textit{mul})$, where $s$ represents the current unit, and $\\textit{mul}$ represents the conversion factor from unit $0$ to unit $s$. Initially, $s = 0$, $\\textit{mul} = 1$. In each recursion, we store the conversion factor $\\textit{mul}$ of the current unit $s$ into the answer array, then traverse all adjacent units $t$ of the current unit $s$, and recursively call $\\textit{dfs}(t, \\textit{mul} \\times w \\mod (10^9 + 7))$, where $w$ is the conversion factor from unit $s$ to unit $t$.\n\nFinally, we return the answer array.\n\nThe complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of units." }, "is_english": true, "time_complexity": null, "space_complexity": "O(n)" }, { "problem_id": 3529, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3530, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3531, "explanations": { "1": "We can group the buildings by their x-coordinates and y-coordinates, storing them in hash tables $\\text{g1}$ and $\\text{g2}$, respectively. Here, $\\text{g1[x]}$ represents all y-coordinates for buildings with x-coordinate $x$, and $\\text{g2[y]}$ represents all x-coordinates for buildings with y-coordinate $y$. Then, we sort these lists.\n\nNext, we iterate through all buildings. For the current building $(x, y)$, we retrieve the corresponding y-coordinate list $l_1$ from $\\text{g1}$ and the x-coordinate list $l_2$ from $\\text{g2}$. We check the conditions to determine whether the building is covered. A building is covered if $l_2[0] < x < l_2[-1]$ and $l_1[0] < y < l_1[-1]$. If so, we increment the answer by one.\n\nAfter finishing the iteration, we return the final answer.\n\nThe complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$, where $n$ is the number of buildings." }, "is_english": true, "time_complexity": null, "space_complexity": "O(n)" }, { "problem_id": 3532, "explanations": { "1": "According to the problem description, the node indices within the same connected component must be consecutive. Therefore, we can use an array $g$ to record the connected component index for each node and a variable $\\textit{cnt}$ to track the current connected component index. As we iterate through the $\\textit{nums}$ array, if the difference between the current node and the previous node is greater than $\\textit{maxDiff}$, it indicates that the current node and the previous node are not in the same connected component. In this case, we increment $\\textit{cnt}$. Then, we assign the current node's connected component index to $\\textit{cnt}$.\n\nFinally, for each query $(u, v)$, we only need to check whether $g[u]$ and $g[v]$ are equal. If they are equal, it means $u$ and $v$ are in the same connected component, and the answer for the $i$-th query is $\\text{true}$. Otherwise, the answer is $\\text{false}$.\n\nThe complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the $\\textit{nums}$ array." }, "is_english": true, "time_complexity": null, "space_complexity": "O(n)" }, { "problem_id": 3533, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3534, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3535, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3536, "explanations": { "1": "我们用两个变量 $a$ 和 $b$ 来记录当前最大的数字和次大的数字。我们遍历 $n$ 的每一位数字,如果当前数字大于 $a$,则将 $b$ 赋值为 $a$,然后将 $a$ 赋值为当前数字;否则,如果当前数字大于 $b$,则将 $b$ 赋值为当前数字。最后返回 $a \\times b$ 即可。\n\n时间复杂度 $O(\\log n)$,其中 $n$ 是输入数字的大小。空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 3537, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3538, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3539, "explanations": { "1": "We design a function $\\text{dfs}(i, j, k, st)$, which represents the number of ways when we are currently processing the $i$-th element of array $\\textit{nums}$, still need to select numbers from the remaining $j$ positions to fill into the magical sequence, still need to satisfy having $k$ set bits in binary form, and the current carry from the previous bit is $st$. Then the answer is $\\text{dfs}(0, m, k, 0)$.\n\nThe execution process of function $\\text{dfs}(i, j, k, st)$ is as follows:\n\nIf $k < 0$ or $i = n$ and $j > 0$, it means the current solution is not feasible, return $0$.\n\nIf $i = n$, it means we have finished processing array $\\textit{nums}$. We need to check if there are still set bits in the current carry $st$, and if so, we need to decrease $k$. If $k = 0$ at this point, it means the current solution is feasible, return $1$, otherwise return $0$.\n\nOtherwise, we enumerate selecting $t$ numbers at position $i$ to fill into the magical sequence ($0 \\leq t \\leq j$). The number of ways to fill $t$ numbers into the magical sequence is $\\binom{j}{t}$, the array product is $\\textit{nums}[i]^t$, the updated carry is $(t + st) >> 1$, the updated number of required set bits is $k - ((t + st) \\& 1)$, and we recursively call $\\text{dfs}(i + 1, j - t, k - ((t + st) \\& 1), (t + st) >> 1)$. The sum of all $t$ solutions is $\\text{dfs}(i, j, k, st)$.\n\nTo efficiently compute the binomial coefficient $\\binom{m}{n}$, we preprocess the factorial array $f$ and the inverse factorial array $g$, where $f[i] = i! \\mod (10^9 + 7)$ and $g[i] = (i!)^{-1} \\mod (10^9 + 7)$. Then $\\binom{m}{n} = f[m] \\cdot g[n] \\cdot g[m - n] \\mod (10^9 + 7)$.\n\nThe time complexity is $O(n \\cdot m^3 \\cdot k)$ and the space complexity is $O(n \\cdot m^2 \\cdot k)$, where $n$ is the length of array $\\textit{nums}$, and $m$ and $k$ are the parameters in the problem." }, "is_english": true, "time_complexity": "O(n \\cdot m^3 \\cdot k)", "space_complexity": "O(n \\cdot m^2 \\cdot k)" }, { "problem_id": 3540, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3541, "explanations": { "1": "We first use a hash table or an array of length $26$, $\\textit{cnt}$, to count the frequency of each letter. Then, we iterate through this table to find the most frequent vowel and consonant, and return the sum of their frequencies.\n\nWe can use a variable $\\textit{a}$ to record the maximum frequency of vowels and another variable $\\textit{b}$ to record the maximum frequency of consonants. During the iteration, if the current letter is a vowel, we update $\\textit{a}$; otherwise, we update $\\textit{b}$.\n\nFinally, we return $\\textit{a} + \\textit{b}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(|\\Sigma|)$, where $|\\Sigma|$ is the size of the alphabet, which is $26$ in this case." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 3542, "explanations": { "1": "According to the problem description, we should first convert the smallest numbers to $0$, then the second smallest numbers to $0$, and so on. During this process, if two numbers are separated by smaller numbers, they require an additional operation to become $0$.\n\nWe can maintain a monotonically increasing stack $\\textit{stk}$ from bottom to top, and traverse each number $\\textit{x}$ in the array $\\textit{nums}$:\n\n- When the top element of the stack is greater than $\\textit{x}$, it means $\\textit{x}$ separates the top element. We need to pop the top element and increment the answer by $1$, continuing until the top element is not greater than $\\textit{x}$.\n- If $\\textit{x}$ is not $0$, and the stack is empty or the top element is not equal to $\\textit{x}$, then push $\\textit{x}$ onto the stack.\n\nAfter traversal, the remaining elements in the stack all require an additional operation to become $0$, so we add the size of the stack to the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3543, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3544, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3545, "explanations": { "1": "We can use an array $\\textit{cnt}$ to count the frequency of each character. Then, we sort this array and return the sum of the first $26 - k$ elements.\n\nThe time complexity is $O(|\\Sigma| \\times \\log |\\Sigma|)$, and the space complexity is $O(|\\Sigma|)$, where $|\\Sigma|$ is the size of the character set. In this problem, $|\\Sigma| = 26$." }, "is_english": true, "time_complexity": "O(|\\Sigma| \\times \\log |\\Sigma|)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 3546, "explanations": { "1": "First, we calculate the sum of all elements in the matrix, denoted as $s$. If $s$ is odd, it is impossible to divide the matrix into two parts with equal sums, so we directly return `false`.\n\nIf $s$ is even, we can enumerate all possible partition lines to check if there exists a line that divides the matrix into two parts with equal sums.\n\nWe traverse each row from top to bottom, calculating the sum of all elements in the rows above the current row, denoted as $\\textit{pre}$. If $\\textit{pre} \\times 2 = s$ and the current row is not the last row, it means we can perform a horizontal partition between the current row and the next row, so we return `true`.\n\nIf no such partition line is found, we traverse each column from left to right, calculating the sum of all elements in the columns to the left of the current column, denoted as $\\textit{pre}$. If $\\textit{pre} \\times 2 = s$ and the current column is not the last column, it means we can perform a vertical partition between the current column and the next column, so we return `true`.\n\nIf no such partition line is found, we return `false`.\n\nThe time complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns in the matrix, respectively. The space complexity is $O(1)$, as only constant extra space is used." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(1)" }, { "problem_id": 3547, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3548, "explanations": { "1": "我们可以先枚举水平分割线,计算分割后两部分的元素和,并使用哈希表记录每个部分中元素的出现次数。\n\n对于每条分割线,我们需要判断两部分的元素和是否相等,或者是否可以通过移除一个单元格使它们相等。如果两部分的元素和相等,那么我们直接返回 $\\text{true}$。如果两部分的元素和不相等,我们需要计算它们的差值 $\\textit{diff}$,如果 $\\textit{diff}$ 在较大部分的哈希表中存在,并且满足移除该单元格后两部分仍然连通的条件,那么我们也返回 $\\text{true}$。\n\n连通性的判断可以通过以下条件来实现:\n\n- 该部分的行数大于 $1$ 且列数大于 $1$。\n- 该部分的行数等于 $1$,且移除的单元格位于该部分的边界(即第一列或最后一列)。\n- 该部分的行数等于 $1$,且移除的单元格位于该部分的边界(即第一行或最后一行)。\n\n满足上述条件之一即可保证移除单元格后该部分仍然连通。\n\n我们还需要枚举垂直分割线,方法与水平分割线类似。为了方便枚举垂直分割线,我们可以先对矩阵进行转置,然后使用相同的逻辑进行判断。\n\n时间复杂度 $O(m \\times n)$,空间复杂度 $O(m \\times n)$。其中 $m$ 和 $n$ 分别是矩阵的行数和列数。" }, "is_english": false, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 3549, "explanations": { "1": "We can use the Fast Fourier Transform (FFT) to efficiently compute the product of two polynomials. FFT is an efficient algorithm that can compute the product of polynomials in $O(n \\log n)$ time complexity.\n\nThe specific steps are as follows:\n\n1. **Padding the length** Let the result length be $m = |A|+|B|-1$, and round it up to the nearest power of 2, $n$, to facilitate divide-and-conquer FFT.\n2. **FFT transformation** Perform the forward FFT (with `invert=False`) on both coefficient sequences.\n3. **Pointwise multiplication** Multiply the corresponding elements in the frequency domain.\n4. **Inverse FFT** Perform the inverse FFT (with `invert=True`) on the product sequence, and round the real parts to the nearest integer to obtain the final coefficients.\n\nThe time complexity is $O(n \\log n)$, and the space complexity is $O(n)$, where $n$ is the length of the polynomials." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3550, "explanations": { "1": "We can start from index $i = 0$ and iterate through each element $x$ in the array, calculating the digit sum $s$ of $x$. If $s = i$, return the index $i$. If no such index is found after traversing all elements, return -1.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$, as only constant extra space is used." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3551, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3552, "explanations": { "1": "We can use 0-1 BFS to solve this problem. We start from the top-left cell and use a double-ended queue to store the coordinates of the current cell. Each time we dequeue a cell, we check its four adjacent cells. If an adjacent cell is an empty cell and has not been visited, we add it to the queue and update its distance.\n\nIf an adjacent cell is a portal, we add it to the front of the queue and update its distance. We also need to maintain a dictionary to store the positions of each portal so that we can quickly find them when using a portal.\n\nWe also need a 2D array to store the distance for each cell, initialized to infinity. We set the distance of the starting point to 0 and then start BFS.\n\nDuring the BFS process, we check whether each cell is the destination. If it is, we return its distance. If the queue is empty and the destination has not been reached, we return -1.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns of the matrix, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 3553, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3554, "explanations": { "1": "First, we join the `ProductPurchases` table and the `ProductInfo` table on `product_id` to obtain a `user_category` table consisting of `user_id` and `category`. Next, we self-join the `user_category` table to get all category pairs purchased by each user. Finally, we group these category pairs, count the number of users for each pair, and filter out the pairs with at least 3 users.\n\nLastly, we sort the final result by customer count in descending order, then by `category1` in ascending order, and then by `category2` in ascending order." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3555, "explanations": { "1": "We can enumerate every subarray of length $k$. For each subarray $nums[i...i + k - 1]$, we need to find the smallest continuous segment such that, after sorting it, the entire subarray becomes non-decreasing.\n\nFor the subarray $nums[i...i + k - 1]$, we can traverse from left to right, maintaining a maximum value $mx$. If the current value is less than $mx$, it means the current value is not in the correct position, so we update the right boundary $r$ to the current position. Similarly, we can traverse from right to left, maintaining a minimum value $mi$. If the current value is greater than $mi$, it means the current value is not in the correct position, so we update the left boundary $l$ to the current position. Initially, both $l$ and $r$ are set to $-1$. If neither $l$ nor $r$ is updated, it means the subarray is already sorted, so we return $0$; otherwise, we return $r - l + 1$.\n\nThe time complexity is $O(n \\times k)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\times k)", "space_complexity": "O(1)" }, { "problem_id": 3556, "explanations": { "1": "We can enumerate all substrings and check whether they are prime numbers. Since the problem requires us to return the sum of the largest 3 distinct primes, we can use a hash table to store all the primes.\n\nAfter traversing all substrings, we sort the primes in the hash table in ascending order, and then take the largest 3 primes to calculate the sum.\n\nIf there are fewer than 3 primes in the hash table, return the sum of all primes.\n\nThe time complexity is $O(n^2 \\times \\sqrt{M})$, and the space complexity is $O(n^2)$, where $n$ is the length of the string and $M$ is the value of the largest substring." }, "is_english": true, "time_complexity": "O(n^2 \\times \\sqrt{M})", "space_complexity": "O(n^2)" }, { "problem_id": 3557, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3558, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3559, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3560, "explanations": { "1": "If the lengths of both logs do not exceed the truck's maximum load $k$, then no cutting is needed, and we simply return $0$.\n\nOtherwise, it means that only one log has a length greater than $k$, and we need to cut it into two pieces. Let the longer log have length $x$, then the cutting cost is $k \\times (x - k)$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 3561, "explanations": { "1": "We can use a stack to simulate the process of removing adjacent characters. Iterate through each character in the string. If the character at the top of the stack and the current character are consecutive (i.e., their ASCII values differ by 1 or 25), pop the top character from the stack; otherwise, push the current character onto the stack. Finally, the characters remaining in the stack are those that can no longer be removed. Join the characters in the stack into a string and return it.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the string." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3562, "explanations": { "1": "For each node $u$, we maintain a 2D array $f_u[j][pre]$, representing the maximum profit that can be obtained in the subtree rooted at $u$ with a budget not exceeding $j$ and whether $u$'s manager purchased stocks (where $pre=1$ means purchased, and $pre=0$ means not purchased). The answer is $f_1[\\text{budget}][0]$.\n\nFor node $u$, the function $\\text{dfs}(u)$ returns a $(\\text{budget}+1) \\times 2$ 2D array $f$, representing the maximum profit that can be obtained in the subtree rooted at $u$ with a budget not exceeding $j$ and whether $u$'s manager purchased stocks.\n\nFor $u$, we need to consider two things:\n\n1. Whether node $u$ itself buys stocks (which will consume part of the budget $\\text{cost}$, where $\\text{cost} = \\lfloor \\text{present}[u] / (pre + 1) \\rfloor$), and increase the profit by $\\text{future}[u] - \\text{cost}$.\n2. How to allocate the budget among node $u$'s child nodes $v$ to maximize profit. We treat each child node's $\\text{dfs}(v)$ as an \"item\" and use a knapsack approach to merge the subtree profits into the current $u$'s $\\text{nxt}$ array.\n\nIn the specific implementation, we first initialize a $(\\text{budget}+1) \\times 2$ 2D array $\\text{nxt}$, representing the profits that have been merged from child nodes. Then for each child node $v$, we recursively call $\\text{dfs}(v)$ to get the profit array $\\text{fv}$ of the child node, and use a knapsack approach to merge $\\text{fv}$ into $\\text{nxt}$.\n\nThe merge formula is:\n\n$$\n\\text{nxt}[j][pre] = \\max(\\text{nxt}[j][pre], \\text{nxt}[j - j_v][pre] + \\text{fv}[j_v][pre])\n$$\n\nwhere $j_v$ represents the budget allocated to child node $v$.\n\nAfter merging all child nodes, $\\text{nxt}[j][pre]$ represents the maximum profit that can be obtained by allocating the entire budget $j$ to child nodes when $u$ itself has not yet decided whether to buy stocks, and $u$'s manager's purchase state is $pre$.\n\nFinally, we decide whether $u$ purchases stocks.\n\n- If $j \\lt \\text{cost}$, then $u$ cannot purchase stocks, in which case $f[j][pre] = \\text{nxt}[j][0]$.\n- If $j \\geq \\text{cost}$, then $u$ can choose to purchase or not purchase stocks, in which case $f[j][pre] = \\max(\\text{nxt}[j][0], \\text{nxt}[j - \\text{cost}][1] + (\\text{future}[u] - \\text{cost}))$.\n\nFinally, return $f$.\n\nThe answer is $\\text{dfs}(1)[\\text{budget}][0]$.\n\nThe time complexity is $O(n \\times \\text{budget}^2)$, and the space complexity is $O(n \\times \\text{budget})$." }, "is_english": true, "time_complexity": "O(n \\times \\text{budget}^2)", "space_complexity": "O(n \\times \\text{budget})" }, { "problem_id": 3563, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3564, "explanations": { "1": "We can perform an equi join between the `sales` table and the `products` table to obtain the product category for each sales record. Next, we determine the season based on the month of the sales date, and then group by season and category to calculate the total quantity sold and total revenue. Finally, we use a window function to rank the categories within each season and select the top-ranked category." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3565, "explanations": { "1": "Note that the matrix size does not exceed $6 \\times 6$, so we can use state compression to represent the visited cells. We can use an integer $\\textit{st}$ to represent the visited cells, where the $i$-th bit being 1 means cell $i$ has been visited, and 0 means it has not been visited.\n\nNext, we iterate through each cell as a starting point. If the cell is 0 or 1, we start a depth-first search (DFS) from that cell. In the DFS, we add the current cell to the path and mark it as visited. Then, we check the value of the current cell. If it equals $v$, we increment $v$ by 1. Next, we try to move in four directions to adjacent cells. If the adjacent cell has not been visited and its value is 0 or $v$, we continue the DFS.\n\nIf the DFS successfully finds a complete path, we return that path. If a complete path cannot be found, we backtrack, undo the visit mark for the current cell, and try other directions.\n\nThe time complexity is $O(m^2 \\times n^2)$, and the space complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns of the matrix, respectively." }, "is_english": true, "time_complexity": "O(m^2 \\times n^2)", "space_complexity": "O(m \\times n)" }, { "problem_id": 3566, "explanations": { "1": "We can use binary enumeration to check all possible subset partitions. For each subset partition, we can calculate the product of the two subsets and check whether both are equal to the target value.\n\nSpecifically, we can use an integer $i$ to represent the state of the subset partition, where the binary bits of $i$ indicate whether each element belongs to the first subset. For each possible $i$, we calculate the product of the two subsets and check whether both are equal to the target value.\n\nThe time complexity is $O(2^n \\times n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(2^n \\times n)", "space_complexity": "O(1)" }, { "problem_id": 3567, "explanations": { "1": "We can enumerate all possible $k \\times k$ submatrices by their top-left coordinates $(i, j)$. For each submatrix, we extract all its elements into a list $\\textit{nums}$. Then, we sort $\\textit{nums}$ and compute the absolute differences between adjacent distinct elements to find the minimum absolute difference. Finally, we store the result in a 2D array.\n\nThe time complexity is $O((m - k + 1) \\times (n - k + 1) \\times k^2 \\log(k))$, where $m$ and $n$ are the number of rows and columns of the matrix, and $k$ is the size of the submatrix. The space complexity is $O(k^2)$, used to store the elements of each submatrix." }, "is_english": true, "time_complexity": "O((m - k + 1) \\times (n - k + 1) \\times k^2 \\log(k))", "space_complexity": "O(k^2)" }, { "problem_id": 3568, "explanations": { "1": "We can use Breadth-First Search (BFS) to solve this problem. First, we need to find the student's starting position and record the locations of all garbage. Then, we can use BFS to explore all possible paths starting from the initial position, while tracking the current energy and the collected garbage.\n\nIn BFS, we need to maintain a state that includes the current position, remaining energy, and a bitmask representing the collected garbage. We can use a queue to store these states and a set to record visited states to avoid revisiting them.\n\nWe start from the initial position and try to move in four directions. If we move to a garbage cell, we update the collected garbage bitmask. If we move to a reset area, we restore the energy to its maximum value. Each move consumes 1 unit of energy.\n\nIf we find a state in BFS where the garbage bitmask is 0 (meaning all garbage has been collected), we return the current number of moves. If BFS completes without finding such a state, we return -1.\n\nThe time complexity is $O(m \\times n \\times \\textit{energy} \\times 2^{\\textit{count}})$, and the space complexity is $O(m \\times n \\times \\textit{energy} \\times 2^{\\textit{count}})$, where $m$ and $n$ are the number of rows and columns in the grid, and $\\textit{count}$ is the number of garbage cells." }, "is_english": true, "time_complexity": "O(m \\times n \\times \\textit{energy} \\times 2^{\\textit{count}})", "space_complexity": "O(m \\times n \\times \\textit{energy} \\times 2^{\\textit{count}})" }, { "problem_id": 3569, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3570, "explanations": { "1": "First, we count the current number of borrowers for each book, then join this result with the book information table to filter out books where the current number of borrowers equals the total number of copies. Finally, we sort the results by the number of current borrowers in descending order, and if there is a tie, by book title in ascending order." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3571, "explanations": { "1": "We can construct the shortest string containing both `s1` and `s2` as substrings by enumerating the overlapping parts of the two strings.\n\nOur goal is to build the shortest string that contains both `s1` and `s2` as substrings. Since substrings must be contiguous, we try to overlap the **suffix** of one string with the **prefix** of the other, thereby reducing the total length when concatenating.\n\nSpecifically, there are several cases:\n\n1. **Containment**: If `s1` is a substring of `s2`, then `s2` itself satisfies the condition, so just return `s2`; vice versa as well.\n2. **s1 concatenated before s2**: Enumerate whether a suffix of `s1` matches a prefix of `s2`, and concatenate after finding the maximum overlap.\n3. **s2 concatenated before s1**: Enumerate whether a prefix of `s1` matches a suffix of `s2`, and concatenate after finding the maximum overlap.\n4. **No overlap**: If there is no overlap between the suffix/prefix of the two strings, simply return `s1 + s2`.\n\nWe try both concatenation orders and return the shorter one (if the lengths are equal, either is acceptable).\n\nThe time complexity is $O(n^2)$ and the space complexity is $O(n)$, where $n$ is the maximum length of `s1` and `s2`." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 3572, "explanations": { "1": "We pair the elements of arrays $x$ and $y$ into a 2D array $\\textit{arr}$, and then sort $\\textit{arr}$ in descending order by the value of $y$. Next, we use a hash table to record the $x$ values that have already been selected, and iterate through $\\textit{arr}$, each time selecting an $x$ value and its corresponding $y$ value that has not been chosen yet, until we have selected three distinct $x$ values.\n\nIf we manage to select three different $x$ values during the iteration, we return the sum of their corresponding $y$ values; if we finish iterating without selecting three distinct $x$ values, we return -1.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$, where $n$ is the length of arrays $\\textit{x}$ and $\\textit{y}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3573, "explanations": { "1": "We define $f[i][j][k]$ to represent the maximum profit on the first $i$ days, with at most $j$ transactions, and the current state $k$. Here, the state $k$ has three possibilities:\n\n- If $k = 0$, it means we do not hold any stock.\n- If $k = 1$, it means we are holding a stock.\n- If $k = 2$, it means we are holding a short position.\n\nInitially, for any $j \\in [1, k]$, we have $f[0][j][1] = -prices[0]$ and $f[0][j][2] = prices[0]$. This means buying a stock or opening a short position on day 0.\n\nNext, we update $f[i][j][k]$ using state transitions. For each day $i$ and each transaction $j$, we update according to the current state $k$:\n\n- If $k = 0$, meaning no stock is held, this state can be reached from three situations:\n - No stock was held the previous day.\n - A stock was held the previous day and sold today.\n - A short position was held the previous day and bought back today.\n- If $k = 1$, meaning a stock is held, this state can be reached from two situations:\n - A stock was held the previous day.\n - No stock was held the previous day and a stock is bought today.\n- If $k = 2$, meaning a short position is held, this state can be reached from two situations:\n - A short position was held the previous day.\n - No stock was held the previous day and a short position is opened (sold) today.\n\nThat is, for $1 \\leq i < n$ and $1 \\leq j \\leq k$, we have the following state transition equations:\n\n$$\n\\begin{aligned}\nf[i][j][0] &= \\max(f[i - 1][j][0], f[i - 1][j][1] + prices[i], f[i - 1][j][2] - prices[i]) \\\\\nf[i][j][1] &= \\max(f[i - 1][j][1], f[i - 1][j - 1][0] - prices[i]) \\\\\nf[i][j][2] &= \\max(f[i - 1][j][2], f[i - 1][j - 1][0] + prices[i])\n\\end{aligned}\n$$\n\nFinally, we return $f[n - 1][k][0]$, which is the maximum profit after at most $k$ transactions and not holding any stock at the end of $n$ days.\n\nThe time complexity is $O(n \\times k)$, and the space complexity is $O(n \\times k)$, where $n$ is the length of the array $\\textit{prices}$ and $k$ is the maximum number of transactions." }, "is_english": true, "time_complexity": "O(n \\times k)", "space_complexity": "O(n \\times k)" }, { "problem_id": 3574, "explanations": { "1": "We notice that the length of the array in this problem is $n \\leq 1500$, so we can enumerate all subarrays. For each subarray, calculate its GCD score and find the maximum value as the answer.\n\nSince each number can be doubled at most once, the GCD of a subarray can be multiplied by at most $2$. Therefore, we need to count the minimum number of factors of $2$ among all numbers in the subarray, as well as the number of times this minimum occurs. If the count is greater than $k$, the GCD score is the GCD itself; otherwise, the GCD score is the GCD multiplied by $2$.\n\nThus, we can preprocess the number of factors of $2$ for each number, and when enumerating subarrays, maintain the current subarray's GCD, the minimum number of factors of $2$, and the number of times this minimum occurs.\n\nThe time complexity is $O(n^2 \\times \\log n)$ and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n^2 \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3575, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3576, "explanations": { "1": "According to the problem description, to make all elements in the array equal, all elements must be either $\\textit{nums}[0]$ or $-\\textit{nums}[0]$. Therefore, we design a function $\\textit{check}$ to determine whether the array can be transformed into all elements equal to $\\textit{target}$ with at most $k$ operations.\n\nThe idea of this function is to traverse the array and count the number of operations needed. Each element is either modified once or not at all. If the current element is equal to the target value, no modification is needed and we continue to the next element. If the current element is not equal to the target value, an operation is needed, increment the counter, and flip the sign, indicating that subsequent elements need the opposite operation.\n\nAfter the traversal, if the counter is less than or equal to $k$ and the sign of the last element matches the target value, return $\\textit{true}$; otherwise, return $\\textit{false}$.\n\nThe final answer is the result of $\\textit{check}(\\textit{nums}[0], k)$ or $\\textit{check}(-\\textit{nums}[0], k)$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3577, "explanations": { "1": "Since the password for computer number $0$ is already unlocked, for any other computer $i$, if $\\text{complexity}[i] \\leq \\text{complexity}[0]$, it is impossible to unlock computer $i$, so we return $0$. Otherwise, any permutation is valid, and there are exactly $(n - 1)!$ possible permutations.\n\nThe time complexity is $O(n)$, where $n$ is the length of the $\\text{complexity}$ array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3578, "explanations": { "1": "We define $f[i]$ as the number of ways to partition the first $i$ elements. If an array satisfies that the difference between its maximum and minimum values does not exceed $k$, then any of its subarrays also satisfies this condition. Therefore, we can use two pointers to maintain a sliding window representing the current subarray.\n\nWhen we reach the $r$-th element, we need to find the left pointer $l$ such that the subarray from $l$ to $r$ satisfies that the difference between the maximum and minimum values does not exceed $k$. We can use an ordered set to maintain the elements in the current window, so that we can quickly get the maximum and minimum values.\n\nEach time we add a new element, we insert it into the ordered set and check the difference between the maximum and minimum values in the current window. If it exceeds $k$, we move the left pointer $l$ until the condition is satisfied. The number of partition ways ending at the $r$-th element is $f[l - 1] + f[l] + \\ldots + f[r - 1]$. We can use a prefix sum array to quickly calculate this value.\n\nThe answer is $f[n]$, where $n$ is the length of the array.\n\nThe time complexity is $O(n \\times \\log n)$ and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3579, "explanations": { "1": "We define $f[i]$ as the minimum number of operations required to convert the first $i$ characters of $\\textit{word1}$ to the first $i$ characters of $\\textit{word2}$. The answer is $f[n]$, where $n$ is the length of both $\\textit{word1}$ and $\\textit{word2}$.\n\nWe can compute $f[i]$ by enumerating all possible split points. For each split point $j$, we need to calculate the minimum number of operations required to convert $\\textit{word1}[j:i]$ to $\\textit{word2}[j:i]$.\n\nWe can use a helper function $\\text{calc}(l, r, \\text{rev})$ to compute the minimum number of operations needed to convert $\\textit{word1}[l:r]$ to $\\textit{word2}[l:r]$, where $\\text{rev}$ indicates whether to reverse the substring. Since the result of performing other operations before or after a reversal is the same, we only need to consider not reversing, and reversing once before other operations. Therefore, $f[i] = \\min_{j < i} (f[j] + \\min(\\text{calc}(j, i-1, \\text{false}), 1 + \\text{calc}(j, i-1, \\text{true})))$.\n\nNext, we need to implement the $\\text{calc}(l, r, \\text{rev})$ function. We use a 2D array $cnt$ to record the pairing status of characters between $\\textit{word1}$ and $\\textit{word2}$. For each character pair $(a, b)$, if $a \\neq b$, we check whether $cnt[b][a] > 0$. If so, we can pair them and reduce one operation; otherwise, we need to add one operation and increment $cnt[a][b]$ by $1$.\n\nThe time complexity is $O(n^3 + |\\Sigma|^2)$ and the space complexity is $O(n + |\\Sigma|^2)$, where $n$ is the length of the string and $|\\Sigma|$ is the size of the character set (which is $26$ in this problem)." }, "is_english": true, "time_complexity": "O(n^3 + |\\Sigma|^2)", "space_complexity": "O(n + |\\Sigma|^2)" }, { "problem_id": 3580, "explanations": { "1": "First, we extract the most recent three performance review records for each employee and calculate the difference in rating between each review and the previous one. Next, we filter out employees whose ratings are strictly increasing, and compute their improvement score (i.e., the last rating minus the first rating among the last three reviews). Finally, we sort the results by improvement score in descending order and by name in ascending order." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3581, "explanations": { "1": "We can convert each number into its corresponding English word, then count the frequency of each letter. Since the number of letters is limited, we can use an integer $\\textit{mask}$ to represent the occurrence of each letter. Specifically, we can map each letter to a binary bit of the integer. If a letter appears an odd number of times, the corresponding binary bit is 1; otherwise, it's 0. Finally, we only need to count the number of bits that are 1 in $\\textit{mask}$, which is the answer.\n\nThe time complexity is $O(\\log n)$, where $n$ is the input integer. And the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 3582, "explanations": { "1": "We first split the title string into words, then process each word. The first word should be all lowercase, while for the subsequent words, the first letter is capitalized and the rest are lowercase. Next, we concatenate all the processed words and add a # symbol at the beginning. Finally, if the generated tag exceeds 100 characters in length, we truncate it to the first 100 characters.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the title string." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3583, "explanations": { "1": "We can enumerate the middle number $\\textit{nums}[j]$, and use two hash tables, $\\textit{left}$ and $\\textit{right}$, to record the occurrence counts of numbers to the left and right of $\\textit{nums}[j]$, respectively.\n\nFirst, we add all numbers to $\\textit{right}$. Then, we traverse each number $\\textit{nums}[j]$ from left to right. During the traversal:\n\n1. Remove $\\textit{nums}[j]$ from $\\textit{right}$.\n2. Count the occurrences of the number $\\textit{nums}[i] = \\textit{nums}[j] * 2$ to the left of $\\textit{nums}[j]$, denoted as $\\textit{left}[\\textit{nums}[j] * 2]$.\n3. Count the occurrences of the number $\\textit{nums}[k] = \\textit{nums}[j] * 2$ to the right of $\\textit{nums}[j]$, denoted as $\\textit{right}[\\textit{nums}[j] * 2]$.\n4. Multiply $\\textit{left}[\\textit{nums}[j] * 2]$ and $\\textit{right}[\\textit{nums}[j] * 2]$ to get the number of special triplets with $\\textit{nums}[j]$ as the middle number, and add the result to the answer.\n5. Add $\\textit{nums}[j]$ to $\\textit{left}$.\n\nFinally, return the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3584, "explanations": { "1": "We can enumerate the last element of the subsequence, assuming it is $\\textit{nums}[i]$. Then the first element of the subsequence can be $\\textit{nums}[j]$, where $j \\leq i - m + 1$. Therefore, we use two variables $\\textit{mi}$ and $\\textit{mx}$ to maintain the prefix minimum and maximum values respectively. When traversing to $\\textit{nums}[i]$, we update $\\textit{mi}$ and $\\textit{mx}$, then calculate the products of $\\textit{nums}[i]$ with $\\textit{mi}$ and $\\textit{mx}$, taking the maximum value.\n\nThe time complexity is $O(n)$, where $n$ is the length of array $\\textit{nums}$. And the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3585, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3586, "explanations": { "1": "We can first find the date of the first positive test for each patient and record this in table first_positive. Next, we can find the date of the first negative test for each patient after their first positive test in the covid_tests table, and record this in table first_negative_after_positive. Finally, we join these two tables with the patients table, calculate the recovery time, and sort according to requirements." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3587, "explanations": { "1": "For a valid arrangement, the number of odd and even numbers can only differ by 1 or be equal. Therefore, if the difference between the number of odd and even numbers is greater than 1, it is impossible to form a valid arrangement, and we should return -1 directly.\n\nWe use an array $\\text{pos}$ to store the indices of odd and even numbers, where $\\text{pos}[0]$ stores the indices of even numbers and $\\text{pos}[1]$ stores the indices of odd numbers.\n\nIf the number of odd and even numbers is equal, there are two valid arrangements: odd numbers before even numbers, or even numbers before odd numbers. We can calculate the number of swaps required for both arrangements and take the minimum.\n\nIf the number of odd numbers is greater than the number of even numbers, there is only one valid arrangement, which is odd numbers before even numbers. In this case, we only need to calculate the number of swaps for this arrangement.\n\nTherefore, we define a function $\\text{calc}(k)$, where $k$ indicates the parity of the first element (0 for even, 1 for odd). This function calculates the number of swaps needed to transform the current arrangement into a valid arrangement starting with $k$. We just need to iterate over the indices in $\\text{pos}[k]$ and sum the differences between each index and its position in the valid arrangement.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $\\text{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3588, "explanations": { "1": "The problem asks for twice the area of the triangle, so we can directly calculate the product of the base and height of the triangle.\n\nSince the triangle must have at least one side parallel to the $x$-axis or $y$-axis, we can enumerate sides parallel to the $x$-axis and calculate the double area for all possible triangles, then swap the coordinates in $\\textit{coords}$ and repeat the process to calculate the double area for triangles with sides parallel to the $y$-axis.\n\nTherefore, we design a function $\\textit{calc}$ to calculate the double area for all possible triangles with sides parallel to the $y$-axis.\n\nWe use two hash maps $\\textit{f}$ and $\\textit{g}$ to record the minimum and maximum $y$-coordinates for each $x$-coordinate. Then we iterate through $\\textit{coords}$, updating $\\textit{f}$ and $\\textit{g}$, and also record the minimum and maximum $x$-coordinates. Finally, we iterate through $\\textit{f}$, calculate the double area for each $x$-coordinate, and update the answer.\n\nIn the main function, we first call the $\\textit{calc}$ function to calculate the double area for triangles with sides parallel to the $y$-axis, then swap the coordinates in $\\textit{coords}$ and repeat the process to calculate the double area for triangles with sides parallel to the $x$-axis. Finally, we return the answer; if the answer is 0, we return -1.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of $\\textit{coords}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3589, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3590, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3591, "explanations": { "1": "We use a hash table $\\text{cnt}$ to count the frequency of each element. Then, we iterate through the values in $\\text{cnt}$ and check if any of them is a prime number. If there is a prime, return `true`; otherwise, return `false`.\n\nThe time complexity is $O(n \\times \\sqrt{M})$, and the space complexity is $O(n)$, where $n$ is the length of the array $\\text{nums}$ and $M$ is the maximum" }, "is_english": true, "time_complexity": "O(n \\times \\sqrt{M})", "space_complexity": "O(n)" }, { "problem_id": 3592, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3593, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3594, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3595, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3596, "explanations": { "1": "Due to the movement rules given in the problem, in fact, only the following three cases can reach the target cell:\n\n1. A $1 \\times 1$ grid, with a cost of $1$.\n2. A grid with $2$ rows and $1$ column, with a cost of $3$.\n3. A grid with $1$ row and $2$ columns, with a cost of $3$.\n\nFor all other cases, it is impossible to reach the target cell, so return $-1$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 3597, "explanations": { "1": "We can use a hash table $\\textit{vis}$ to record the segments that have already appeared. Then, we traverse the string $s$, building the current segment $t$ character by character until this segment has not appeared before. Each time we construct a new segment, we add it to the result list and mark it as seen.\n\nAfter the traversal, we simply return the result list.\n\nThe time complexity is $O(n \\times \\sqrt{n})$, and the space complexity is $O(n)$, where $n$ is the length of the string $s$.", "2": "We can use string hashing to speed up the lookup of segments. Specifically, we can compute a hash value for each segment and store it in a hash table. In this way, we can determine in constant time whether a segment has already appeared.\n\nIn detail, we first create a string hashing class $\\textit{Hashing}$ based on the string $s$, which supports computing the hash value of any substring. Then, we traverse the string $s$ using two pointers $l$ and $r$ to represent the start and end positions of the current segment (indices starting from $1$). Each time we extend $r$, we compute the hash value $x$ of the current segment. If this hash value is not in the hash table, we add the segment to the result list and mark its hash value as seen. Otherwise, we continue to extend $r$ until we find a new segment.\n\nAfter the traversal, we return the result list.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n \\times \\sqrt{n})", "space_complexity": "O(n)" }, { "problem_id": 3598, "explanations": { "1": "We define a function $\\textit{calc}(s, t)$, which calculates the length of the longest common prefix between strings $s$ and $t$. We can use an ordered set to maintain the longest common prefix lengths of all adjacent string pairs.\n\nDefine a function $\\textit{add}(i, j)$, which adds the longest common prefix length of the string pair at indices $i$ and $j$ to the ordered set. Define a function $\\textit{remove}(i, j)$, which removes the longest common prefix length of the string pair at indices $i$ and $j$ from the ordered set.\n\nFirst, we compute the longest common prefix lengths for all adjacent string pairs and store them in the ordered set. Then, for each index $i$, we perform the following steps:\n\n1. Remove the longest common prefix length of the string pair at indices $i$ and $i + 1$.\n2. Remove the longest common prefix length of the string pair at indices $i - 1$ and $i$.\n3. Add the longest common prefix length of the string pair at indices $i - 1$ and $i + 1$.\n4. Add the current maximum value in the ordered set (if it exists and is greater than 0) to the answer.\n5. Remove the longest common prefix length of the string pair at indices $i - 1$ and $i + 1$.\n6. Add the longest common prefix length of the string pair at indices $i - 1$ and $i$.\n7. Add the longest common prefix length of the string pair at indices $i$ and $i + 1$.\n\nIn this way, after removing each string, we can quickly compute the longest common prefix length between adjacent string pairs.\n\nThe time complexity is $O(L + n \\times \\log n)$, and the space complexity is $O(n)$, where $L$ is the total length of all strings and $n$ is the number of strings." }, "is_english": true, "time_complexity": "O(L + n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3599, "explanations": { "1": "We define $f[i][j]$ as the minimum possible value of the maximum XOR among all ways to partition the first $i$ elements into $j$ subarrays. Initially, set $f[0][0] = 0$, and all other $f[i][j] = +\\infty$.\n\nTo quickly compute the XOR of a subarray, we can use a prefix XOR array $g$, where $g[i]$ represents the XOR of the first $i$ elements. For the subarray $[h + 1...i]$ (with indices starting from $1$), its XOR value is $g[i] \\oplus g[h]$.\n\nNext, we iterate $i$ from $1$ to $n$, $j$ from $1$ to $\\min(i, k)$, and $h$ from $j - 1$ to $i - 1$, where $h$ represents the end position of the previous subarray (indices starting from $1$). We update $f[i][j]$ using the following state transition equation:\n\n$$\nf[i][j] = \\min_{h \\in [j - 1, i - 1]} \\max(f[h][j - 1], g[i] \\oplus g[h])\n$$\n\nFinally, we return $f[n][k]$, which is the minimum possible value of the maximum XOR when partitioning the entire array into $k$ subarrays.\n\nThe time complexity is $O(n^2 \\times k)$, and the space complexity is $O(n \\times k)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n^2 \\times k)", "space_complexity": "O(n \\times k)" }, { "problem_id": 3600, "explanations": { "1": "According to the problem description, the stability of a spanning tree is determined by the minimum strength edge in it. If a stability $x$ is feasible, then for any $y < x$, stability $y$ is also feasible. Therefore, we can use binary search to find the maximum stability.\n\nWe first add all required edges into the Union-Find and record the minimum strength $mn$ among them. If there is a cycle among the required edges, return $-1$ directly. Then we add all edges into the Union-Find; if the final number of connected components is greater than $1$, it means not all nodes can be connected, and we return $-1$.\n\nNext, we perform binary search in the range $[1, mn]$. We define a function $\\text{check}(lim)$ to check whether there exists a spanning tree with stability at least $lim$. In the $\\text{check}$ function, we first add all edges with strength no less than $lim$ into the Union-Find. Then we try to use the upgrade count to connect the remaining edges, with the condition that the edge strength is at least $lim/2$ (since upgrading doubles the strength). If the final number of connected components in the Union-Find is $1$, a spanning tree satisfying the condition exists.\n\nThe time complexity is $O((m \\times \\alpha(n) + n) \\times \\log M)$, and the space complexity is $O(n)$. Here, $m$ is the number of edges, $n$ is the number of nodes, and $M$ is the maximum edge strength." }, "is_english": true, "time_complexity": "O((m \\times \\alpha(n) + n) \\times \\log M)", "space_complexity": "O(n)" }, { "problem_id": 3601, "explanations": { "1": "First, we perform group aggregation on the `trips` table to calculate the average fuel efficiency for each driver in the first half and the second half of the year.\n\nThen, we join the results with the `drivers` table, filter out the drivers whose fuel efficiency has improved, and calculate the amount of improvement." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3602, "explanations": { "1": "We define a function $\\textit{f}(x, k)$, which converts an integer $x$ to its string representation in base $k$. This function constructs the result string by repeatedly taking the modulus and dividing.\n\nFor a given integer $n$, we compute $n^2$ and $n^3$, then convert them to hexadecimal and base-36 strings, respectively. Finally, we concatenate these two strings and return the result.\n\nThe time complexity is $O(\\log n)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 3603, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3604, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3605, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3606, "explanations": { "1": "We can directly simulate the conditions described in the problem to filter out valid coupons. The specific steps are as follows:\n\n1. **Check Identifier**: For each coupon's identifier, check whether it is non-empty and contains only letters, digits, and underscores.\n2. **Check Business Category**: Check whether each coupon's business category belongs to one of the four valid categories.\n3. **Check Activation Status**: Check whether each coupon is active.\n4. **Collect Valid Coupons**: Collect the ids of all coupons that satisfy the above conditions.\n5. **Sort**: Sort the valid coupons by business category and identifier.\n6. **Return Result**: Return the list of identifiers of the sorted valid coupons.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$, where $n$ is the number of coupons." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3607, "explanations": { "1": "We can use Union-Find to maintain the connection relationships between power stations, thereby determining which grid each station belongs to. For each grid, we use a sorted set (such as `SortedList` in Python, `TreeSet` in Java, or `std::set` in C++) to store all online station IDs in that grid, allowing efficient querying and deletion of stations.\n\nThe specific steps are as follows:\n\n1. Initialize the Union-Find structure and process all connection relationships, merging connected stations into the same set.\n2. Create a sorted set for each grid, initially adding all station IDs to their corresponding grid's set.\n3. Iterate through the query list:\n - For query $[1, x]$, first find the root node of the grid that station $x$ belongs to, then check that grid's sorted set:\n - If station $x$ is online (exists in the set), return $x$.\n - Otherwise, return the station with the smallest ID in the set (if the set is non-empty), otherwise return -1.\n - For query $[2, x]$, find the root node of the grid that station $x$ belongs to, and remove station $x$ from that grid's sorted set, indicating that the station is offline.\n4. Finally, return all query results of type $[1, x]$.\n\nThe time complexity is $O((c + n + q) \\log c)$ and the space complexity is $O(c)$, where $c$ is the number of stations, and $n$ and $q$ are the number of connections and queries, respectively." }, "is_english": true, "time_complexity": "O((c + n + q) \\log c)", "space_complexity": "O(c)" }, { "problem_id": 3608, "explanations": { "1": "We can sort the edges by time in ascending order, then starting from the edge with the largest time, add edges to the graph one by one, while using a union-find data structure to maintain the number of connected components in the current graph. When the number of connected components is less than $k$, the current time is the minimum time we are looking for.\n\nThe time complexity is $O(n \\times \\alpha(n))$, and the space complexity is $O(n)$, where $\\alpha$ is the inverse Ackermann function." }, "is_english": true, "time_complexity": "O(n \\times \\alpha(n))", "space_complexity": "O(n)" }, { "problem_id": 3609, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3610, "explanations": { "1": "We can first preprocess to obtain the first $1000$ prime numbers, and then use dynamic programming to solve the problem.\n\nDefine $f[i]$ as the minimum number of primes needed to sum up to $i$. Initially, set $f[0] = 0$ and all other $f[i] = \\infty$. For each prime $p$, we can update $f[i]$ from $f[i - p]$ as follows:\n\n$$\nf[i] = \\min(f[i], f[i - p] + 1)\n$$\n\nIf $f[n]$ is still $\\infty$, it means it is impossible to obtain $n$ as the sum of the first $m$ primes, so return -1; otherwise, return $f[n]$.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(n + M)$, where $M$ is the number of preprocessed primes (here it is $1000$)." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(n + M)" }, { "problem_id": 3611, "explanations": { "1": "First, we group the data by `employee_id`, `year`, and `week` to calculate the total meeting hours for each employee in each week. Then, we filter out the weeks where the meeting hours exceed 20 and count the number of meeting-heavy weeks for each employee. Finally, we join the result with the employees table, filter out employees with at least 2 meeting-heavy weeks, and sort the results as required." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3612, "explanations": { "1": "We can directly simulate the operations described in the problem. We use a list $\\text{result}$ to store the current result string. For each character in the input string $s$, we perform the corresponding operation based on the character type:\n\n- If the character is a lowercase English letter, add it to $\\text{result}$.\n- If the character is `*`, delete the last character in $\\text{result}$ (if it exists).\n- If the character is `#`, copy $\\text{result}$ and append it to itself.\n- If the character is `%`, reverse $\\text{result}$.\n\nFinally, we convert $\\text{result}$ to a string and return it.\n\nThe time complexity is $O(2^n)$, where $n$ is the length of string $s$. In the worst case, the `#` operation may cause the length of $\\text{result}$ to double each time, resulting in exponential time complexity. Ignoring the space consumption of the answer, the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(2^n)", "space_complexity": "O(1)" }, { "problem_id": 3613, "explanations": { "1": "If $k = n$, it means all edges can be removed. In this case, all connected components are isolated nodes, and the maximum cost is 0.\n\nOtherwise, we can sort all edges by weight in ascending order, then use a union-find data structure to maintain connected components.\n\nWe assume that initially all nodes are not connected, with each node being an independent connected component. Starting from the edge with the smallest weight, we try to add it to the current connected components. If the number of connected components becomes less than or equal to $k$ after adding the edge, it means all remaining edges can be removed, and the weight of the current edge is the maximum cost we are looking for. We return this weight. Otherwise, we continue processing the next edge.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$, where $n$ is the number of nodes." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3614, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3615, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3616, "explanations": { "1": "We use a variable $\\text{cur}$ to record the rank of the currently selected student. We iterate through the array $\\text{ranks}$, and if we encounter a student with a better rank (i.e., $\\text{ranks}[i] < \\text{cur}$), we update $\\text{cur}$ and increment the answer by one.\n\nAfter the iteration, we return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the number of students. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3617, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3618, "explanations": { "1": "We can use the Sieve of Eratosthenes to preprocess all prime numbers in the range $[0, 10^5]$. Then we iterate through the array $\\textit{nums}$. For $\\textit{nums}[i]$, if $i$ is a prime number, we add $\\textit{nums}[i]$ to the answer; otherwise, we add $-\\textit{nums}[i]$ to the answer. Finally, we return the absolute value of the answer.\n\nIgnoring the preprocessing time and space, the time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3619, "explanations": { "1": "We define a function $\\textit{dfs}(i, j)$, which performs DFS traversal starting from position $(i, j)$ and returns the total value of that island. We add the current position's value to the total value, then mark that position as visited (for example, by setting its value to 0). Next, we recursively visit the adjacent positions in four directions (up, down, left, right). If an adjacent position has a value greater than 0, we continue the DFS and add its value to the total value. Finally, we return the total value.\n\nIn the main function, we traverse the entire grid. For each unvisited position $(i, j)$, if its value is greater than 0, we call $\\textit{dfs}(i, j)$ to calculate the total value of that island. If the total value is divisible by $k$, we increment the answer by one.\n\nThe time complexity is $O(m \\times n)$, and the space complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns of the grid, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" }, { "problem_id": 3620, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3621, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3622, "explanations": { "1": "We can iterate through each digit of the integer $n$, calculating the digit sum $s$ and digit product $p$. Finally, we check whether $n$ is divisible by $s + p$.\n\nThe time complexity is $O(\\log n)$, where $n$ is the value of the integer $n$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 3623, "explanations": { "1": "According to the problem description, horizontal edges have the same $y$ coordinate. Therefore, we can group points by their $y$ coordinates and count the number of points for each $y$ coordinate.\n\nWe use a hash table $\\textit{cnt}$ to store the number of points for each $y$ coordinate. For each $y$ coordinate $y_i$, assuming the number of corresponding points is $v$, the number of ways to select two points from these points as a horizontal edge is $\\binom{v}{2} = \\frac{v(v-1)}{2}$, denoted as $t$.\n\nWe use a variable $s$ to record the sum of the number of horizontal edges for all previous $y$ coordinates. Then, we can multiply the number of horizontal edges $t$ for the current $y$ coordinate by the sum $s$ of the number of horizontal edges for all previous $y$ coordinates to get the number of trapezoids with the current $y$ coordinate as one pair of horizontal edges, and add it to the answer. Finally, we add the number of horizontal edges $t$ for the current $y$ coordinate to $s$ for subsequent calculations.\n\nNote that since the answer may be very large, we need to take the modulo $10^9 + 7$.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the number of points." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3624, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3625, "explanations": { "1": "We can combine all points pairwise, calculate the slope and intercept of the line corresponding to each pair of points, record them using a hash table, and calculate the sum of the number of pairs formed by lines with the same slope but different intercepts. Note that for parallelograms, we will count them twice in the above calculation, so we need to subtract them.\n\nThe diagonals of a parallelogram share the same midpoint. Therefore, we also combine all points pairwise, calculate the midpoint coordinates and slope of each pair of points, record them using a hash table, and calculate the sum of the number of pairs formed by point pairs with the same slope and the same midpoint coordinates.\n\nSpecifically, we use two hash tables $\\textit{cnt1}$ and $\\textit{cnt2}$ to record the following information:\n\n- $\\textit{cnt1}$ records the number of occurrences of slope $k$ and intercept $b$, with the key being the slope $k$ and the value being another hash table that records the number of occurrences of intercept $b$;\n- $\\textit{cnt2}$ records the number of occurrences of the midpoint coordinates and slope $k$ of point pairs, with the key being the midpoint coordinates $p$ of the point pair and the value being another hash table that records the number of occurrences of slope $k$.\n\nFor a point pair $(x_1, y_1)$ and $(x_2, y_2)$, we denote $dx = x_2 - x_1$ and $dy = y_2 - y_1$. If $dx = 0$, it means the two points are on the same vertical line, and we denote the slope $k = +\\infty$ and the intercept $b = x_1$; otherwise, the slope $k = \\frac{dy}{dx}$ and the intercept $b = \\frac{y_1 \\cdot dx - x_1 \\cdot dy}{dx}$. The midpoint coordinates $p$ of the point pair can be expressed as $p = (x_1 + x_2 + 2000) \\cdot 4000 + (y_1 + y_2 + 2000)$, where the offset is added to avoid negative numbers.\n\nNext, we iterate through all point pairs, calculate the corresponding slope $k$, intercept $b$, and midpoint coordinates $p$, and update the hash tables $\\textit{cnt1}$ and $\\textit{cnt2}$.\n\nThen, we iterate through the hash table $\\textit{cnt1}$. For each slope $k$, we calculate the sum of all pairwise combinations of the occurrence counts of intercept $b$ and add it to the answer. Finally, we iterate through the hash table $\\textit{cnt2}$. For each midpoint coordinate $p$, we calculate the sum of all pairwise combinations of the occurrence counts of slope $k$ and subtract it from the answer.\n\nThe time complexity is $O(n^2)$ and the space complexity is $O(n^2)$, where $n$ is the number of points." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n^2)" }, { "problem_id": 3626, "explanations": { "1": "We can use window functions to calculate the most expensive and cheapest products for each store, and use joins to filter out stores with inventory imbalance. The specific steps are as follows:\n\n1. **Calculate the most expensive product for each store**: Use the `RANK()` window function to sort by price in descending order, and in case of the same price, sort by quantity in descending order, selecting the product ranked first.\n2. **Calculate the cheapest product for each store**: Use the `RANK()` window function to sort by price in ascending order, and in case of the same price, sort by quantity in descending order, selecting the product ranked first.\n3. **Filter stores with at least 3 different products**: Use the `COUNT()` window function to count the number of products for each store, and filter out stores with a count greater than or equal to 3.\n4. **Join most expensive and cheapest products**: Join the results of the most expensive and cheapest products, ensuring that the quantity of the most expensive product is less than the quantity of the cheapest product.\n5. **Calculate imbalance ratio**: Calculate the ratio of the cheapest product quantity to the most expensive product quantity, and round it to two decimal places.\n6. **Join store information**: Join the results with the store information table to get store names and locations.\n7. **Sort results**: Sort by imbalance ratio in descending order, then by store name in ascending order." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3627, "explanations": { "1": "To maximize the sum of medians, we need to select larger elements as medians whenever possible. Since each operation can only select three elements, we can sort the array and then start from index $n / 3$, selecting every other element (skipping one) until the end of the array. This ensures that we select the largest possible medians.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 3628, "explanations": { "1": "We can first calculate the number of \"LCT\" subsequences in the original string, then consider the case of inserting one letter.\n\nThe number of \"LCT\" subsequences can be calculated by traversing the string. We can enumerate the middle \"C\" and use two variables $l$ and $r$ to maintain the counts of \"L\" on the left and \"T\" on the right respectively. For each \"C\", we can calculate the number of \"L\"s on its left and the number of \"T\"s on its right, thus obtaining the number of \"LCT\" subsequences with this \"C\" as the middle character as $l \\times r$, and accumulate it to the total count.\n\nNext, we need to consider the case of inserting one letter. Consider inserting an \"L\", \"C\", or \"T\":\n\n- Insert an \"L\": we only need to count the number of \"CT\" subsequences in the original string.\n- Insert a \"T\": we only need to count the number of \"LC\" subsequences in the original string.\n- Insert a \"C\": we only need to count the number of \"LT\" subsequences in the original string. In this case, during the enumeration process above, we can maintain a variable $\\textit{mx}$ representing the current maximum value of $l \\times r$.\n\nFinally, we add the number of \"LCT\" subsequences in the original string to the maximum number of subsequences after inserting one letter to get the final result.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3629, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3630, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3631, "explanations": { "1": "We can directly sort the array according to the requirements of the problem. Note that the score is a long integer, so we need to use long integers when comparing to avoid overflow.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$, where $n$ is the length of the array $\\text{threats}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 3632, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3633, "explanations": { "1": "We can consider two orders of rides: first land rides then water rides, or first water rides then land rides.\n\nFor each order, we first calculate the earliest end time $\\textit{minEnd}$ of the first type of ride, then enumerate the second type of ride and calculate the earliest end time of the second type of ride as $\\max(\\textit{minEnd}, \\textit{startTime}) + \\textit{duration}$, where $\\textit{startTime}$ is the start time of the second type of ride. We take the minimum value among all possible earliest end times as the answer.\n\nFinally, we return the minimum value between the answers of the two orders.\n\nThe time complexity is $O(n + m)$, where $n$ and $m$ are the numbers of land rides and water rides respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(1)" }, { "problem_id": 3634, "explanations": { "1": "We first sort the array, then enumerate each element $\\textit{nums}[i]$ from small to large as the minimum value of the balanced array. The maximum value $\\textit{max}$ of the balanced array must satisfy $\\textit{max} \\leq \\textit{nums}[i] \\times k$. Therefore, we can use binary search to find the index $j$ of the first element greater than $\\textit{nums}[i] \\times k$. At this point, the length of the balanced array is $j - i$. We record the maximum length $\\textit{cnt}$, and the final answer is the array length minus $\\textit{cnt}$.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$, where $n$ is the length of the array $\\textit{nums}$.", "2": "We first sort the array, then use two pointers to maintain a sliding window. The left pointer $l$ enumerates each element $\\textit{nums}[l]$ from left to right as the minimum value of the balanced array. The right pointer $r$ keeps moving right until $\\textit{nums}[r]$ is greater than $\\textit{nums}[l] \\times k$. At this point, the length of the balanced array is $r - l$, and the number of elements to be removed is $n - (r - l)$. We record the minimum number of removals as the answer.\n\nThe time complexity is $O(n \\times \\log n)$ and the space complexity is $O(\\log n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 3635, "explanations": { "1": "We can consider two orders of rides: first land rides then water rides, or first water rides then land rides.\n\nFor each order, we first calculate the earliest end time $\\textit{minEnd}$ of the first type of ride, then enumerate the second type of ride and calculate the earliest end time of the second type of ride as $\\max(\\textit{minEnd}, \\textit{startTime}) + \\textit{duration}$, where $\\textit{startTime}$ is the start time of the second type of ride. We take the minimum value among all possible earliest end times as the answer.\n\nFinally, we return the minimum value between the answers of the two orders.\n\nThe time complexity is $O(n + m)$, where $n$ and $m$ are the numbers of land rides and water rides respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n + m)", "space_complexity": "O(1)" }, { "problem_id": 3636, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3637, "explanations": { "1": "We first define a pointer $p$, initially $p = 0$, pointing to the first element of the array. We move $p$ to the right until we find the first element that doesn't satisfy strict increasing order, i.e., $nums[p] \\geq nums[p + 1]$. If $p = 0$ at this point, it means the first part of the array doesn't have a strictly increasing section, so we return $\\text{false}$ directly.\n\nNext, we define another pointer $q$, initially $q = p$, pointing to the first element of the second part of the array. We move $q$ to the right until we find the first element that doesn't satisfy strict decreasing order, i.e., $nums[q] \\leq nums[q + 1]$. If $q = p$ or $q = n - 1$ at this point, it means the second part of the array doesn't have a strictly decreasing section or there's no third part, so we return $\\text{false}$ directly.\n\nIf all the above conditions are satisfied, it means the array is trionic, and we return $\\text{true}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$, using only constant extra space." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3638, "explanations": { "1": "We maintain the maximum value $\\text{mx}$ of the currently traversed array, and iterate through each element $x$ in the array. If $x < \\text{mx}$, it means the current element can serve as the last parcel of a balanced shipment, so we increment the answer by one and reset $\\text{mx}$ to 0. Otherwise, we update $\\text{mx}$ to the value of the current element $x$.\n\nAfter the traversal, we return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$, using only constant extra space." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3639, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3640, "explanations": { "1": "We can traverse the array to find all possible maximal trionic subarrays, calculate their sums, and update the maximum value.\n\nWe define a pointer $i$, initially $i = 0$, representing the current position pointing to the first element of the array. We move $i$ to the right until we find the first element that does not satisfy strict increase, i.e., $nums[i-1] \\geq nums[i]$. If at this point $i = l + 1$, it means this segment has only one element and cannot form an increasing sequence, so we continue to the next iteration.\n\nNext, we define pointer $p$, representing the end position of the current increasing segment. Then we find the second strictly decreasing part. If this segment has only one element, or reaches the end of the array, or encounters equal elements, we continue to the next iteration.\n\nThen we define pointer $q$, representing the end position of the current decreasing segment. Next, we find the third strictly increasing part. At this point, we have found a maximal trionic subarray. The maximum sum of this trionic subarray consists of the following parts:\n\n- The sum of elements in the index range $[p-2,..,q+1]$\n- The sum of the maximum increasing subarray extending left from $p-3$, or 0 if it doesn't exist\n- The sum of the maximum increasing subarray extending right from $q+2$, or 0 if it doesn't exist.\n\nAfter calculating the sum of this trionic subarray, we update the answer. Then we move pointer $i$ to position $q$, because the increasing part of the third segment can serve as the first increasing segment of the next iteration.\n\nAfter the traversal is complete, we return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$, using only constant-level extra space." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3641, "explanations": { "1": "We use two pointers $l$ and $r$ to maintain a sliding window, where the right pointer continuously moves to the right, and we use a hash table $\\textit{cnt}$ to record the number of occurrences of each element within the current window.\n\nWhen the occurrence count of an element changes from $1$ to $2$, it indicates that there is a new repeating element, so we increment the repeating element counter $\\textit{cur}$ by $1$. When the repeating element counter exceeds $k$, it means the current window does not satisfy the condition, and we need to move the left pointer until the repeating element counter is no greater than $k$. During the process of moving the left pointer, if the occurrence count of an element changes from $2$ to $1$, it indicates that there is one less repeating element, so we decrement the repeating element counter by $1$. Then, we update the answer, i.e., $\\textit{ans} = \\max(\\textit{ans}, r - l + 1)$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3642, "explanations": { "1": "We can implement this by joining the `books` table with the `reading_sessions` table, then grouping and aggregating the results.\n\nFirst, we need to calculate the rating range, the number of extreme ratings, and the proportion of extreme ratings for each book.\n\nThen, we can filter out books that meet the criteria based on these metrics.\n\nFinally, sort the results by extreme rating proportion and book title in descending order." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3643, "explanations": { "1": "We start from row $x$ and flip a total of $\\lfloor \\frac{k}{2} \\rfloor$ rows.\n\nFor each row $i$, we need to swap it with the corresponding row $i_2$, where $i_2 = x + k - 1 - (i - x)$.\n\nDuring the swap, we need to traverse $j \\in [y, y + k)$ and swap $\\text{grid}[i][j]$ with $\\text{grid}[i_2][j]$.\n\nFinally, return the updated matrix.\n\nThe time complexity is $O(k^2)$, where $k$ is the side length of the submatrix. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(k^2)", "space_complexity": "O(1)" }, { "problem_id": 3644, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3645, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3646, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3647, "explanations": { "1": "We define $f[i][j][k]$ to represent the maximum total weight when placing the first $i$ items into two bags, where bag 1 has a maximum capacity of $j$ and bag 2 has a maximum capacity of $k$. Initially, $f[0][j][k] = 0$, indicating that no items can be placed in the bags.\n\nThe state transition equation is:\n\n$$\nf[i][j][k] = \\max(f[i-1][j][k], f[i-1][j-w_i][k], f[i-1][j][k-w_i]) \\quad (w_i \\leq j \\text{ or } w_i \\leq k)\n$$\n\nwhere $w_i$ represents the weight of the $i$-th item.\n\nThe final answer is $f[n][w1][w2]$, where $n$ is the number of items.\n\nWe notice that the state transition equation only depends on the previous layer's state, so we can compress the three-dimensional DP array into a two-dimensional DP array. When enumerating $j$ and $k$, we use reverse traversal.\n\nTime complexity $O(n \\times w1 \\times w2)$, space complexity $O(w1 \\times w2)$. Where $n$ is the length of the array $\\textit{weights}$." }, "is_english": true, "time_complexity": "O(n \\times w1 \\times w2)", "space_complexity": "O(w1 \\times w2)" }, { "problem_id": 3648, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3649, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3650, "explanations": { "1": "According to the problem description, we can construct a directed graph $g$ where each edge $(u, v)$ allows for two types of traversal:\n\n- Direct traversal with cost $w$, corresponding to edge $(u, v)$.\n- Reverse traversal with cost $2w$, corresponding to edge $(v, u)$.\n\nThen, we can use Dijkstra's algorithm on graph $g$ to find the shortest path from node $0$ to node $n-1$, which corresponds to the minimum total cost required.\n\nSpecifically, we define a priority queue $pq$, where each element is a tuple $(d, u)$, indicating that the current minimum cost to reach node $u$ is $d$. We also define an array $\\textit{dist}$, where $\\textit{dist}[u]$ represents the minimum cost from node $0$ to node $u$. Initially, we set $\\textit{dist}[0] = 0$, and the costs for all other nodes to infinity, then push $(0, 0)$ into the queue.\n\nIn each iteration, we extract the node $(d, u)$ with the minimum cost from the priority queue. If $d$ is greater than $\\textit{dist}[u]$, we skip this node. Otherwise, we traverse all neighbors $v$ of node $u$, calculating the new cost $nd = d + w$ to reach node $v$ via node $u$. If $nd$ is less than $\\textit{dist}[v]$, we update $\\textit{dist}[v] = nd$ and push $(nd, v)$ into the queue.\n\nWhen we extract node $n-1$, the current $d$ is the minimum total cost from node $0$ to node $n-1$. If the priority queue becomes empty and node $n-1$ has not been extracted, it implies that node $n-1$ is unreachable, so we return -1.\n\nThe time complexity is $O(n + m \\times \\log m)$, and the space complexity is $O(n + m)$. Here, $n$ and $m$ refer to the number of nodes and edges, respectively." }, "is_english": true, "time_complexity": "O(n + m \\times \\log m)", "space_complexity": "O(n + m)" }, { "problem_id": 3651, "explanations": { "1": "We define $f[t][i][j]$ as the minimum cost to reach cell $(i, j)$ using exactly $t$ teleportations. Initially, $f[0][0][0] = 0$, and all other states are infinity.\n\nFirst, we need to initialize $f[0][i][j]$. Without using teleportation, we can only reach cell $(i, j)$ by moving right or down.\n\nIf $i > 0$, we can move from the cell above $(i-1, j)$, updating the state as:\n\n$$f[0][i][j] = \\min(f[0][i][j], f[0][i-1][j] + grid[i][j])$$\n\nIf $j > 0$, we can move from the cell to the left $(i, j-1)$, updating the state as:\n\n$$f[0][i][j] = \\min(f[0][i][j], f[0][i][j-1] + grid[i][j])$$\n\nTo handle teleportation, we need to group the cells in the grid by their values. We use a hash map $g$, where the key is the cell value and the value is a list of coordinates of cells with that value.\n\nFor each teleportation count $t$ from $1$ to $k$, we process each group in descending order of cell values. For each cell $(i, j)$ in a group, we first update a global minimum $mn$, representing the minimum cost to reach these cells using $t-1$ teleportations:\n\n$$mn = \\min(mn, f[t-1][i][j])$$\n\nThen, we update the state of all cells in the group to $mn$, representing the minimum cost to reach these cells via teleportation.\n\nNext, we traverse the entire grid again to update $f[t][i][j]$, considering moves from the top or left cells:\n\nIf $i > 0$, then:\n\n$$f[t][i][j] = \\min(f[t][i][j], f[t][i-1][j] + grid[i][j])$$\n\nIf $j > 0$, then:\n\n$$f[t][i][j] = \\min(f[t][i][j], f[t][i][j-1] + grid[i][j])$$\n\nFinally, our answer is $\\min(f[t][m-1][n-1])$, where $t$ ranges from $0$ to $k$.\n\nThe time complexity is $O((k + \\log mn) \\times mn)$, and the space complexity is $O(k \\times mn)$. Here, $m$ and $n$ are the number of rows and columns of the grid, respectively, and $k$ is the maximum allowed number of teleportations." }, "is_english": true, "time_complexity": "O((k + \\log mn) \\times mn)", "space_complexity": "O(k \\times mn)" }, { "problem_id": 3652, "explanations": { "1": "We use an array $\\textit{s}$ to represent the prefix sum, where $\\textit{s}[i]$ is the total profit for the first $i$ days, i.e., $\\textit{s}[i] = \\sum_{j=0}^{i-1} \\textit{prices}[j] \\times \\textit{strategy}[j]$. We also use an array $\\textit{t}$ to represent the prefix sum of stock prices, where $\\textit{t}[i] = \\sum_{j=0}^{i-1} \\textit{prices}[j]$.\n\nInitially, the maximum profit is $\\textit{s}[n]$. We enumerate the right endpoint $i$ of the subarray to be modified, with the left endpoint being $i-k$. After modification, the first $k/2$ days of the subarray have strategy $0$, and the last $k/2$ days have strategy $1$, so the profit change is:\n\n$$\\Delta = -(\\textit{s}[i] - \\textit{s}[i-k]) + (\\textit{t}[i] - \\textit{t}[i-k/2])$$\n\nTherefore, we can update the maximum profit by enumerating all possible $i$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3653, "explanations": { "1": "We can directly simulate the operations described in the problem by iterating through each query and updating the corresponding elements in the array $\\textit{nums}$. Finally, we calculate the bitwise XOR of all elements in the array and return the result.\n\nThe time complexity is $O(q \\times \\frac{n}{k})$, where $n$ is the length of the array $\\textit{nums}$ and $q$ is the number of queries. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(q \\times \\frac{n}{k})", "space_complexity": "O(1)" }, { "problem_id": 3654, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3655, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3656, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3657, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3658, "explanations": { "1": "The sum of the first $n$ odd numbers is $n^2$, while the sum of the first $n$ even numbers is $n(n + 1)$. The greatest common divisor of these two is at least $n$. Since $n$ and $n + 1$ are coprime, the answer is $n$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 3659, "explanations": { "1": "We denote the length of the array as $n$. If $n$ is not divisible by $k$, then we cannot partition the array into groups where each group contains $k$ elements, so we directly return $\\text{false}$.\n\nNext, we calculate the size of each group $m = n / k$ and count the occurrence of each element in the array. If the occurrence count of any element exceeds $m$, then it cannot be distributed to any group, so we directly return $\\text{false}$.\n\nFinally, if the occurrence count of all elements does not exceed $m$, then we can partition the array into groups where each group contains $k$ elements, and we return $\\text{true}$.\n\nTime complexity $O(n)$, space complexity $O(n)$ or $O(M)$. Where $n$ is the length of the array, and $M$ is the maximum value of elements in the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3660, "explanations": { "1": "If $i = n - 1$, then it can jump to the maximum value in $\\textit{nums}$, so $\\textit{ans}[i] = \\max(\\textit{nums})$. For other positions $i$, we can calculate by maintaining a prefix maximum array and a suffix minimum variable.\n\nThe specific steps are as follows:\n\n1. Create an array $\\textit{preMax}$, where $\\textit{preMax}[i]$ represents the maximum value in the interval $[0, i]$ when traversing from left to right.\n2. Create a variable $\\textit{sufMin}$, which represents the minimum value to the right of the current element when traversing from right to left. Initially $\\textit{sufMin} = \\infty$.\n3. First preprocess the $\\textit{preMax}$ array.\n4. Next, traverse the array from right to left. For each position $i$, if $\\textit{preMax}[i] > \\textit{sufMin}$, it means we can jump from $i$ to the position where $\\textit{preMax}$ is located, then jump to the position where $\\textit{sufMin}$ is located, and finally jump to $i + 1$. Therefore, the numbers that can be reached from $i + 1$ can also be reached from $i$, so $\\textit{ans}[i] = \\textit{ans}[i + 1]$; otherwise update to $\\textit{preMax}[i]$. Then update $\\textit{sufMin}$.\n5. Finally return the result array $\\textit{ans}$.\n\nTime complexity $O(n)$, space complexity $O(n)$. Where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3661, "explanations": { "1": "We first store each robot with its range in an array and sort them by robot position. We also sort the wall positions. Next, we use depth-first search (DFS) to calculate the number of walls each robot can destroy, and use memoized search to avoid redundant calculations.\n\nWe design a function $\\text{dfs}(i, j)$, where $i$ represents the index of the current robot being considered, and $j$ represents the firing direction of the next robot (0 for left, 1 for right), and returns the number of walls that can be destroyed. The answer is $\\text{dfs}(n - 1, 1)$, where $j$ can be 0 or 1 in the boundary state.\n\nThe execution logic of function $\\text{dfs}(i, j)$ is as follows:\n\nIf $i \\lt 0$, it means all robots have been considered, return 0.\n\nOtherwise, for the current robot, there are two firing directions to choose from.\n\nIf choosing to fire **left**, we need to calculate the left range $[\\text{left}, \\text{robot}[i][0]]$, and use binary search to calculate the number of walls that can be destroyed in this range. In this case, a total of $\\text{dfs}(i - 1, 0) + \\text{count}$ walls can be destroyed, where $\\text{count}$ is the number of walls destroyed when the current robot fires left.\n\nIf choosing to fire **right**, we need to calculate the right range $[\\text{robot}[i][0], \\text{right}]$, and use binary search to calculate the number of walls that can be destroyed in this range. In this case, a total of $\\text{dfs}(i - 1, 1) + \\text{count}$ walls can be destroyed, where $\\text{count}$ is the number of walls destroyed when the current robot fires right.\n\nThe return value of the function is the maximum number of walls that can be destroyed by the two firing directions.\n\nTime complexity $O(n \\times \\log n + m \\times \\log m)$, space complexity $O(n)$. Where $n$ and $m$ are the numbers of robots and walls respectively." }, "is_english": true, "time_complexity": "O(n \\times \\log n + m \\times \\log m)", "space_complexity": "O(n)" }, { "problem_id": 3662, "explanations": { "1": "First, we iterate through the string $s$ and count the frequency of each character, storing the results in a hash table or array $\\textit{cnt}$.\n\nThen, we iterate through the string $s$ again, adding characters whose frequency is less than $k$ to the result string. Finally, we return the result string.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(|\\Sigma|)$, where $\\Sigma$ is the size of the character set." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 3663, "explanations": { "1": "We use an array $\\textit{cnt}$ to count the frequency of each digit. We iterate through each digit of the number $n$ and update the $\\textit{cnt}$ array.\n\nThen, we use a variable $f$ to record the current lowest frequency among the digits, and a variable $\\textit{ans}$ to record the corresponding digit.\n\nNext, we iterate through the $\\textit{cnt}$ array. If $0 < \\textit{cnt}[x] < f$, it means we have found a digit with a lower frequency, so we update $f = \\textit{cnt}[x]$ and $\\textit{ans} = x$.\n\nAfter the iteration, we return $\\textit{ans}$ as the answer.\n\nThe time complexity is $O(\\log n)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 3664, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3665, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3666, "explanations": { "1": "We denote the length of string $s$ as $n$, and the current number of '0's in the string as $\\textit{cur}$. In each operation, we select $k$ indices to flip, where $x$ indices flip from '0' to '1', and $k-x$ indices flip from '1' to '0'. Then the number of '0's in the string after flipping is $\\textit{cur} + k - 2x$.\n\nThe value of $x$ needs to satisfy the following conditions:\n\n1. At most $\\min(\\textit{cur}, k)$ '0's can be taken, because we cannot flip more than $\\textit{cur}$ '0's, so $0 \\leq x \\leq \\min(\\textit{cur}, k)$.\n2. At most $n - \\textit{cur}$ '1's can be taken, because we cannot flip more than $n - \\textit{cur}$ '1's, so $k - x \\leq n - \\textit{cur}$, i.e., $x \\geq k - n + \\textit{cur}$.\n\nTherefore, the range of $x$ is $[\\max(k - n + \\textit{cur}, 0), \\min(\\textit{cur}, k)]$, and the range of the number of '0's in the string after flipping is $[\\textit{cur} + k - 2 \\cdot \\min(\\textit{cur}, k), \\textit{cur} + k - 2 \\cdot \\max(k - n + \\textit{cur}, 0)]$.\n\nWe notice that the parity of the number of '0's in the string after flipping is the same as the parity of the number of '0's in the string before flipping. Therefore, we can use two ordered sets to store states where the number of '0's is even and odd, respectively.\n\nWe use BFS to search the state transition graph, where the initial state is the number of '0's in the string, and the target state is 0. Each time we dequeue a state $\\textit{cur}$, we calculate the range $[l, r]$ of the number of '0's in the string after flipping, find all states in the range $[l, r]$ in the ordered set, add them to the queue, and remove them from the ordered set.\n\nIf we visit state 0 during the BFS process, we return the current number of operations; if state 0 is not visited after BFS ends, we return -1.\n\nThe time complexity is $O(n \\log n)$, and the space complexity is $O(n)$, where $O(n)$ is the number of states that may be visited during the BFS process, and $O(\\log n)$ is the time complexity of inserting and deleting elements in the ordered set." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3667, "explanations": { "1": "We can use a custom sorting function to sort the array, where the sorting criterion is the absolute value of each element.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 3668, "explanations": { "1": "First, we build a mapping from the order array to record the finishing position of each ID. Then, we sort the friends array based on the finishing order of these IDs in the order array.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$, where $n$ is the length of the order array." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3669, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3670, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3671, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3672, "explanations": { "1": "We use a hash map $\\textit{cnt}$ to record the frequency of each number in the current window. We use a priority queue $\\textit{pq}$ to store the frequency and value of each number in the current window, with priority given to higher frequency, and for equal frequency, to smaller numbers.\n\nWe design a function $\\textit{get_mode()}$ to obtain the mode and its frequency in the current window. Specifically, we repeatedly pop the top element from the priority queue until its frequency matches the frequency recorded in the hash map; at that point, the top element is the mode and its frequency for the current window.\n\nWe use a variable $\\textit{ans}$ to record the sum of weights for all windows. Initially, we add the first $k$ numbers of the array to the hash map and priority queue, then call $\\textit{get_mode()}$ to get the mode and its frequency for the first window, and add its weight to $\\textit{ans}$.\n\nNext, starting from the $k$-th number, we add each number to the hash map and priority queue, and decrement the frequency of the leftmost number in the window in the hash map. Then, we call $\\textit{get_mode()}$ to get the mode and its frequency for the current window, and add its weight to $\\textit{ans}$.\n\nFinally, we return $\\textit{ans}$.\n\nThe time complexity is $O(n \\log k)$, and the space complexity is $O(k)$." }, "is_english": true, "time_complexity": "O(n \\log k)", "space_complexity": "O(k)" }, { "problem_id": 3673, "explanations": { "1": "We can group the sessions by session_id, calculate the session duration, the number of scroll events, click events, and purchase events for each session, then filter according to the conditions given in the problem. Finally, we sort by the number of scroll events in descending order and by session ID in ascending order." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3674, "explanations": { "1": "If all elements in $\\textit{nums}$ are equal, no operations are needed; otherwise, we can select the entire array as a subarray and perform one operation.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3675, "explanations": { "1": "According to the problem description, we always start from the character 'b' and successively change each character to the next one until it becomes 'a'. Therefore, we only need to find the character in the string that is farthest from 'a' and calculate its distance to 'a' to get the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3676, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3677, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3678, "explanations": { "1": "We use a hash map $\\textit{s}$ to record the elements that appear in the array $\\textit{nums}$.\n\nThen, we calculate the average value $\\textit{avg}$ of the array $\\textit{nums}$, and initialize the answer $\\textit{ans}$ as $\\max(1, \\lfloor \\textit{avg} \\rfloor + 1)$.\n\nIf $\\textit{ans}$ appears in $\\textit{s}$, we increment $\\textit{ans}$ until it no longer appears in $\\textit{s}$.\n\nFinally, we return $\\textit{ans}$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3679, "explanations": { "1": "We use a hash map $\\textit{cnt}$ to record the quantity of each item type in the current window, and an array $\\textit{marked}$ to record whether each item is kept.\n\nWe iterate through the array from left to right. For each item $x$:\n\n1. If the current day $i$ is greater than or equal to the window size $w$, we subtract $\\textit{marked}[i - w]$ from the count of the leftmost item in the window (if that item was kept).\n2. If the quantity of the current item in the window exceeds $m$, we discard the item.\n3. Otherwise, we keep the item and increment its count.\n\nFinally, the answer is the number of items discarded.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3680, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3681, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3682, "explanations": { "1": "We initialize a variable $\\textit{ans}$ as infinity, representing the current minimum index sum, and use a hash map $\\textit{d}$ to store the first occurrence index of each element in array $\\textit{nums2}$.\n\nThen we iterate through array $\\textit{nums1}$. For each element $\\textit{nums1}[i]$, if it exists in $\\textit{d}$, we calculate the index sum $i + \\textit{d}[\\textit{nums1}[i]]$ and update $\\textit{ans}$.\n\nFinally, if $\\textit{ans}$ is still infinity, it means no common element was found, so we return -1; otherwise, we return $\\textit{ans}$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3683, "explanations": { "1": "We iterate through the $\\textit{tasks}$ array and, for each task, calculate its completion time $s_i + t_i$. The minimum of all task completion times is the earliest time to finish at least one task.\n\nThe time complexity is $O(n)$, where $n$ is the length of the $\\textit{tasks}$ array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3684, "explanations": { "1": "We first sort the array $\\textit{nums}$, then iterate from the end to the beginning, selecting the largest $k$ distinct elements. Since we require a strictly decreasing order, we skip duplicate elements during selection.\n\nThe time complexity is $O(n \\times \\log n)$, where $n$ is the length of the $\\textit{nums}$ array. Ignoring the space used for the answer, the space complexity is $O(\\log n)$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 3685, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3686, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3687, "explanations": { "1": "We define a function $\\text{f}(x)$ to calculate the late fee for each book:\n\n$$\n\\text{f}(x) = \\begin{cases}\n1 & x = 1 \\\\\n2x & 2 \\leq x \\leq 5 \\\\\n3x & x > 5\n\\end{cases}\n$$\n\nThen, for each element $x$ in the array $\\textit{daysLate}$, we compute $\\text{f}(x)$ and sum them up to get the total late fee.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{daysLate}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3688, "explanations": { "1": "We define a variable $\\textit{ans}$ with an initial value of 0. Then, we iterate through each element $x$ in the array $\\textit{nums}$; if $x$ is even, we update $\\textit{ans}$ with the bitwise OR of $\\textit{ans}$ and $x$.\n\nFinally, we return $\\textit{ans}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3689, "explanations": { "1": "We can observe that the value of a subarray only depends on the global maximum and minimum values. Therefore, we just need to find the global maximum and minimum, then multiply their difference by $k$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3690, "explanations": { "1": "We can use Breadth-First Search (BFS) to solve this problem. Since the array length is at most 6, we can enumerate all possible split and merge operations to find the minimum number of operations.\n\nFirst, we define a queue $\\textit{q}$ to store the current array states, and use a set $\\textit{vis}$ to record the visited array states to avoid duplicate computations. Initially, the queue contains only the array $\\textit{nums1}$.\n\nThen, we perform the following steps:\n\n1. Remove the current array state $\\textit{cur}$ from the queue.\n2. If $\\textit{cur}$ equals the target array $\\textit{nums2}$, return the current number of operations.\n3. Otherwise, enumerate all possible split positions $(l, r)$, remove the subarray $\\textit{cur}[l..r]$ to obtain the remaining array $\\textit{remain}$ and the subarray $\\textit{sub}$.\n4. Insert the subarray $\\textit{sub}$ into all possible positions of the remaining array $\\textit{remain}$ to generate new array states $\\textit{nxt}$.\n5. If a new array state $\\textit{nxt}$ has not been visited, add it to the queue and the visited set.\n6. Repeat the above steps until the target array is found or the queue is empty.\n\nThe time complexity is $O(n! \\times n^4)$, and the space complexity is $O(n! \\times n)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n! \\times n^4)", "space_complexity": "O(n! \\times n)" }, { "problem_id": 3691, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3692, "explanations": { "1": "我们先用一个数组或哈希表 $\\textit{cnt}$ 统计字符串中每个字符的出现频率。然后,我们再用一个哈希表 $\\textit{f}$,将出现频率 $k$ 相同的字符放在同一个列表中,即 $\\textit{f}[k]$ 存储所有出现频率为 $k$ 的字符。\n\n接下来,我们遍历哈希表 $\\textit{f}$,找到组大小最大的频率组。如果有多个频率组的大小并列最大,则选择其频率 $k$ 较大的那个组。最后,我们将该频率组中的所有字符连接成一个字符串并返回。\n\n时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为字符串 $\\textit{s}$ 的长度。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3693, "explanations": { "1": "We define $f[i]$ as the minimum total cost required to reach the $i$-th stair, initially $f[0] = 0$, and all other $f[i] = +\\infty$.\n\nFor each stair $i$, we can jump from the $(i-1)$-th, $(i-2)$-th, or $(i-3)$-th stair, so we have the following state transition equation:\n\n$$\nf[i] = \\min_{j=i-3}^{i-1} (f[j] + \\textit{costs}[i - 1] + (i - j)^2)\n$$\n\nWhere $\\textit{costs}[i]$ is the cost of the $i$-th stair, and $(i - j)^2$ is the jump cost from the $j$-th stair to the $i$-th stair. Note that we need to ensure $j$ is not less than $0$.\n\nThe final answer is $f[n]$.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the number of stairs." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3694, "explanations": { "1": "We can use prefix sum arrays to track position changes after each move. Specifically, we use two prefix sum arrays $f$ and $g$ to record the position changes on the $x$-axis and $y$-axis respectively after each move.\n\nInitialize $f[0] = 0$ and $g[0] = 0$, representing the initial position at $(0, 0)$. Then, we iterate through the string $s$, and for each character:\n\n- If the character is 'U', then $g[i] = g[i-1] + 1$.\n- If the character is 'D', then $g[i] = g[i-1] - 1$.\n- If the character is 'L', then $f[i] = f[i-1] - 1$.\n- If the character is 'R', then $f[i] = f[i-1] + 1$.\n\nNext, we use a hash set to store the distinct final coordinates. For each possible substring removal position $i$ (from $k$ to $n$), we calculate the final coordinates $(a, b)$ after removing the substring, where $a = f[n] - (f[i] - f[i-k])$ and $b = g[n] - (g[i] - g[i-k])$. Add the coordinates $(a, b)$ to the hash set.\n\nFinally, the size of the hash set is the number of distinct final coordinates.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3695, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3696, "explanations": { "1": "我们可以发现,最大距离的两个单词中至少有一个单词在数组的两端(即下标为 $0$ 或 $n - 1$)。否则,假设最大距离的两个单词分别在下标 $i$ 和 $j$ 处,即 $0 < i < j < n - 1$,那么单词 $\\textit{words}[0]$ 和 $\\textit{words}[j]$ 相同,而单词 $\\textit{words}[n - 1]$ 和 $\\textit{words}[i]$ 也相同(否则距离会更大),因此单词 $\\textit{words}[0]$ 和 $\\textit{words}[n - 1]$ 不同,且它们的距离 $n - 1 - 0 + 1 = n$ 一定大于 $j - i + 1$,与假设矛盾。因此,最大距离的两个单词中至少有一个单词在数组的两端。\n\n所以,我们只需要遍历数组,计算每个单词与数组两端单词的距离,并更新最大距离。\n\n时间复杂度 $O(n)$,其中 $n$ 是数组 $\\textit{words}$ 的长度。空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3697, "explanations": { "1": "We can repeatedly perform modulo and division operations on $n$. Each modulo result multiplied by the current position value $p$ represents a decimal component. If the modulo result is not $0$, we add this component to our answer. Then we multiply $p$ by $10$ and continue processing the next position.\n\nFinally, we reverse the answer to arrange it in descending order.\n\nThe time complexity is $O(\\log n)$, where $n$ is the input positive integer. The space complexity is $O(\\log n)$ for storing the answer." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 3698, "explanations": { "1": "We use a prefix sum array $s$ to record the prefix sum of the array, where $s[i]$ represents the sum of the array $[0,..i]$. Then we use two boolean arrays $f$ and $g$ to record the monotonicity of prefixes and suffixes respectively, where $f[i]$ indicates whether the array $[0,..i]$ is strictly increasing, and $g[i]$ indicates whether the array $[i,..n-1]$ is strictly decreasing.\n\nFinally, we traverse array positions $i$ where $0 \\leq i < n-1$. If both $f[i]$ and $g[i+1]$ are true, then we can calculate the sums of $left$ and $right$, which are $s[i]$ and $s[n-1]-s[i]$ respectively, and update the answer.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3699, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3700, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3701, "explanations": { "1": "We can directly traverse the array $\\textit{nums}$. For each index $i$, if $i$ is even, we add $\\textit{nums}[i]$ to the answer; otherwise, we subtract $\\textit{nums}[i]$ from the answer.\n\nFinally, we return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3702, "explanations": { "1": "If the bitwise XOR of all elements in the array is non-zero, then the entire array is the desired longest subsequence, with length equal to the array length.\n\nIf all elements in the array are zero, then there is no subsequence with non-zero bitwise XOR, so we return $0$.\n\nOtherwise, we can remove one non-zero element from the array to make the bitwise XOR of the remaining elements non-zero. The length of the longest subsequence is the array length minus $1$.\n\nThe time complexity is $O(n)$, where $n$ is the length of array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3703, "explanations": { "1": "We use a stack to maintain the current state of the string. Each element in the stack is a pair representing a character and its consecutive count.\n\nTraverse each character in the string:\n\n- If the stack is not empty and the character of the top element matches the current character, increment the count of the top element.\n- Otherwise, push the current character with count 1 as a new element onto the stack.\n- If the current character is `')'`, and there are at least two elements in the stack, and the count of the top element equals $k$, and the count of the previous element is greater than or equal to $k$, then pop the top element and subtract $k$ from the count of the previous element. If the count of the previous element becomes 0, pop it as well.\n\nAfter traversal, the remaining elements in the stack represent the final state of the string. We concatenate these elements in order to get the result string.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3704, "explanations": { "1": "We do a digit DP over the decimal representation of $n$ from the least-significant digit to the most-significant digit.\n\nState: `dp[pos][carry][aliveA][aliveB]` = number of ways for the processed suffix.\n\n- `carry` is the carry into the current digit (0 or 1).\n- `aliveA/aliveB` indicates whether the number still has digits in higher positions. If `aliveX = 0`, all remaining higher digits must be leading zeros (digit 0), which are not part of the decimal representation.\n\nTransition: choose digits `da` and `db`:\n\n- If `aliveX = 1`, digit is in `[1..9]` (no-zero).\n- Otherwise digit is `0`.\n\nThey must satisfy `(da + db + carry) % 10 == digit_n[pos]`. After that, `aliveA`/`aliveB` can stay `1` or become `0` (ending the number at this digit).\n\nWe append one extra leading digit `0` to $n$ so the last carry is fully handled. The answer is `dp[last][0][0][0]`.\n\nTime complexity is $O(L \\cdot 9^2)$ and space complexity is $O(1)$, where $L$ is the number of digits of $n$." }, "is_english": true, "time_complexity": "O(L \\cdot 9^2)", "space_complexity": "O(1)" }, { "problem_id": 3705, "explanations": { "1": "We can group the orders by `customer_id` and calculate the total number of orders, number of orders during peak hours, number of rated orders, and average rating for each customer. Then we filter based on the conditions in the problem and sort by average rating in descending order, followed by customer ID in descending order." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3706, "explanations": { "1": "我们可以发现,最大距离的两个单词中至少有一个单词在数组的两端(即下标为 $0$ 或 $n - 1$)。否则,假设最大距离的两个单词分别在下标 $i$ 和 $j$ 处,即 $0 < i < j < n - 1$,那么单词 $\\textit{words}[0]$ 和 $\\textit{words}[j]$ 相同,而单词 $\\textit{words}[n - 1]$ 和 $\\textit{words}[i]$ 也相同(否则距离会更大),因此单词 $\\textit{words}[0]$ 和 $\\textit{words}[n - 1]$ 不同,且它们的距离 $n - 1 - 0 + 1 = n$ 一定大于 $j - i + 1$,与假设矛盾。因此,最大距离的两个单词中至少有一个单词在数组的两端。\n\n所以,我们只需要遍历数组,计算每个单词与数组两端单词的距离,并更新最大距离。\n\n时间复杂度 $O(n)$,其中 $n$ 是数组 $\\textit{words}$ 的长度。空间复杂度 $O(1)$。" }, "is_english": false, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3707, "explanations": { "1": "We first calculate the total score of the string, denoted as $r$. Then we traverse the first $n-1$ characters from left to right, calculating the prefix score $l$ and updating the suffix score $r$. If at some position $i$, the prefix score $l$ equals the suffix score $r$, it means there exists an index $i$ that can split the string into two substrings with equal scores, so we return $\\textit{true}$. If we finish traversing without finding such an index, we return $\\textit{false}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3708, "explanations": { "1": "We can use a variable $f$ to record the length of the longest Fibonacci subarray ending at the current element. Initially, $f=2$, indicating that any two elements can form a Fibonacci subarray.\n\nThen we traverse the array starting from index $2$. For each element $nums[i]$, if it equals the sum of the previous two elements, i.e., $nums[i] = nums[i-1] + nums[i-2]$, it means the current element can be appended to the previous Fibonacci subarray, so we increment $f$ by $1$. Otherwise, it means the current element cannot be appended to the previous Fibonacci subarray, so we reset $f$ to $2$. During the traversal, we continuously update the answer $\\textit{ans} = \\max(\\textit{ans}, f)$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3709, "explanations": { "1": "We use an array $\\textit{times}$ to store the time points of each exam, and another array $\\textit{pre}$ to store the prefix sums, where $\\textit{pre}[i]$ represents the total score of the first $i$ exams. For each call to $\\texttt{record}(time, score)$, we add $time$ to $\\textit{times}$ and add the last element of $\\textit{pre}$ plus $score$ to $\\textit{pre}$.\n\nFor each call to $\\texttt{totalScore}(startTime, endTime)$, we use binary search to find the first position $l$ in $\\textit{times}$ that is greater than or equal to $startTime$ and the first position $r$ that is greater than $endTime$, then return $\\textit{pre}[r-1] - \\textit{pre}[l-1]$.\n\nThe time complexity is $O(\\log n)$, where $n$ is the number of exams. The space complexity is $O(n)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(n)" }, { "problem_id": 3710, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3711, "explanations": { "1": "We use an ordered set (such as C++'s multiset, Java's TreeMap, Python's SortedList) to store the selected transaction amounts, and maintain a variable $s$ to record the current balance. Initially $s=0$, and the answer $\\textit{ans}$ is initialized to the number of transactions.\n\nThen we traverse each transaction amount $x$:\n\n1. Add $x$ to the balance $s$ and add $x$ to the ordered set.\n2. If the balance $s$ becomes negative at this point, it means some negative amounts among the currently selected transaction amounts have caused insufficient balance. To retain as many transactions as possible, we should remove the smallest amount among the currently selected transaction amounts (because removing the smallest amount can maximize the balance). We remove the smallest amount $y$ from the ordered set, subtract $y$ from the balance $s$, and decrement the answer $\\textit{ans}$ by $1$.\n3. Repeat step 2 until the balance $s$ is no longer negative.\n\nAfter traversal is complete, the answer $\\textit{ans}$ is the maximum number of transactions that can be performed.\n\nThe time complexity is $O(n \\times \\log n)$, where $n$ is the number of transactions. The space complexity is $O(n)$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3712, "explanations": { "1": "We use a hash table $\\textit{cnt}$ to record the frequency of each number. We traverse the array $\\textit{nums}$, and for each number $x$, we increment $\\textit{cnt}[x]$ by $1$.\n\nThen, we traverse the hash table $\\textit{cnt}$. For each element $x$, if its frequency $\\textit{cnt}[x]$ is divisible by $k$, we add $x$ multiplied by its frequency to the result.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(m)$, where $m$ is the number of distinct elements in the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(m)" }, { "problem_id": 3713, "explanations": { "1": "We can enumerate the starting position $i$ of substrings in the range $[0,..n-1]$, then enumerate the ending position $j$ of substrings in the range $[i,..,n-1]$, and use a hash table $\\textit{cnt}$ to record the frequency of each character in substring $s[i..j]$. We use variable $\\textit{mx}$ to record the maximum frequency of characters in the substring, and use variable $v$ to record the number of distinct characters in the substring. If at some position $j$, we have $\\textit{mx} \\times v = j - i + 1$, it means substring $s[i..j]$ is a balanced substring, and we update the answer $\\textit{ans} = \\max(\\textit{ans}, j - i + 1)$.\n\nThe time complexity is $O(n^2)$, where $n$ is the length of the string. The space complexity is $O(|\\Sigma|)$, where $|\\Sigma|$ is the size of the character set, which is $|\\Sigma| = 26$ in this problem." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 3714, "explanations": { "1": "The answer is divided into the following three cases:\n\n1. Balanced substring with only one character, such as `\"aaa\"`.\n2. Balanced substring with two characters, such as `\"aabb\"`.\n3. Balanced substring with three characters, such as `\"abc\"`.\n\nWe define three functions $\\text{calc1}(s)$, $\\text{calc2}(s, a, b)$, and $\\text{calc3}(s)$ to calculate the longest balanced substring length for the above three cases respectively, and finally return the maximum of the three.\n\nFor $\\text{calc1}(s)$, we only need to traverse the string $s$, count the length of each consecutive character, and take the maximum value.\n\nFor $\\text{calc2}(s, a, b)$, we can use prefix sum and hash table to calculate the longest balanced substring length. Specifically, we maintain a variable $d$ to represent the number of character $a$ minus the number of character $b$ in the current substring, and use a hash table to record the first occurrence position of each $d$ value. When we encounter the same $d$ value again, it means that the number of character $a$ and character $b$ in the substring from the last occurrence position to the current position are equal, i.e., the substring is balanced, and we update the answer.\n\nFor $\\text{calc3}(s)$, we also use prefix sum and hash table to calculate the longest balanced substring length. We define an array $\\textit{cnt}$ to record the counts of characters $a$, $b$, and $c$, and use a hash table to record the first occurrence position of each $(\\textit{cnt}[a] - \\textit{cnt}[b], \\textit{cnt}[b] - \\textit{cnt}[c])$ value. When we encounter the same value again, it means that the counts of characters $a$, $b$, and $c$ in the substring from the last occurrence position to the current position are equal, i.e., the substring is balanced, and we update the answer.\n\nFinally, we calculate the values of $\\text{calc1}(s)$, $\\text{calc2}(s, 'a', 'b')$, $\\text{calc2}(s, 'b', 'c')$, $\\text{calc2}(s, 'a', 'c')$, and $\\text{calc3}(s)$ respectively, and return their maximum value.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3715, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3716, "explanations": { "1": "We first use a window function to get the last record for each user sorted by event date and event ID in descending order, obtaining the latest event information for each user. Then, we group and aggregate the subscription history information for each user, including the subscription start date, last event date, historical maximum subscription fee, and the number of downgrade events. Finally, we join the latest event information with the historical statistics and filter according to the conditions specified in the problem to get the list of customers at risk of churn." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3717, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3718, "explanations": { "1": "We first use a hash table $\\textit{s}$ to store the numbers that appear in the array $\\textit{nums}$. Then, starting from the first positive multiple of $k$, which is $k \\times 1$, we enumerate each positive multiple in sequence until we find the first multiple that does not appear in the hash table $\\textit{s}$, which is the answer.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3719, "explanations": { "1": "We can enumerate the left endpoint $i$ of the subarray, and then enumerate the right endpoint $j$ from the left endpoint. During the enumeration process, we use a hash table $\\textit{vis}$ to record the numbers that have appeared in the subarray, and use an array $\\textit{cnt}$ of length $2$ to record the count of distinct even numbers and distinct odd numbers in the subarray respectively. When $\\textit{cnt}[0] = \\textit{cnt}[1]$, we update the answer $\\textit{ans} = \\max(\\textit{ans}, j - i + 1)$.\n\nThe time complexity is $O(n^2)$ and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 3720, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3721, "explanations": { "1": "We can transform the problem into a prefix sum problem. Define a prefix sum variable $\\textit{now}$, representing the difference between odd and even numbers in the current subarray:\n\n$$\n\\textit{now} = \\text{distinct odd numbers} - \\text{distinct even numbers}\n$$\n\nFor odd elements, record as $+1$, and for even elements, record as $-1$. Use a hash table $\\textit{last}$ to record the last occurrence position of each number. If a number appears repeatedly, we need to revoke its previous contribution.\n\nTo efficiently calculate the subarray length each time a right endpoint element is added, we use a segment tree to maintain the minimum and maximum values of the interval prefix sum, while supporting interval addition operations and binary search queries on the segment tree. When iterating to right endpoint $i$, first update the contribution of the current element, then use the segment tree to query the earliest position $pos$ where the current prefix sum $\\textit{now}$ appears. The current subarray length is $i - pos$, and we update the answer:\n\n$$\n\\textit{ans} = \\max(\\textit{ans}, i - pos)\n$$\n\nThe time complexity is $O(n \\log n)$, where $n$ is the length of the array. Each segment tree modification and query operation takes $O(\\log n)$, and enumerating the right endpoint $n$ times gives a total time complexity of $O(n \\log n)$. The space complexity is $O(n)$, where segment tree nodes and the hash table each occupy $O(n)$ space." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3722, "explanations": { "1": "We can enumerate all possible values of $k$ ($1 \\leq k \\leq n$). For each $k$, we compute the string obtained by reversing the first $k$ characters and the string obtained by reversing the last $k$ characters, then take the lexicographically smallest string among them as the final answer.\n\nThe time complexity is $O(n^2)$ and the space complexity is $O(n)$, where $n$ is the length of the string." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 3723, "explanations": { "1": "If $\\text{num} \\times 9 < \\text{sum}$, then there is no valid good integer, so we return an empty string.\n\nOtherwise, we can use as many digits $9$ as possible to form the good integer, since $9^2$ is the largest and will maximize the score. Specifically, we calculate how many $9$s are contained in $\\text{sum}$, denoted as $k$, and the remaining part $s = \\text{sum} - 9 \\times k$. Then, we construct the good integer with the first $k$ digits as $9$. If $s > 0$, we append a digit $s$ at the end, and finally pad with $0$s to reach a total of $\\text{num}$ digits.\n\nThe time complexity is $O(\\text{num})$ and the space complexity is $O(\\text{num})$, where $\\text{num}$ is the number of digits in the good integer." }, "is_english": true, "time_complexity": "O(\\text{num})", "space_complexity": "O(\\text{num})" }, { "problem_id": 3724, "explanations": { "1": "We define an answer variable $\\text{ans}$ to record the minimum number of operations, with an initial value of $1$, representing the operation needed to append the last element to the end of the array.\n\nThen we iterate through the first $n$ elements of the array. For each pair of corresponding elements $(\\text{nums1}[i], \\text{nums2}[i])$, we calculate their difference and add it to $\\text{ans}$.\n\nDuring the iteration, we also need to check whether $\\min(\\text{nums1}[i], \\text{nums2}[i]) \\leq \\text{nums2}[n] \\leq \\max(\\text{nums1}[i], \\text{nums2}[i])$ holds. If it does, it means we can directly adjust $\\text{nums1}[i]$ to reach $\\text{nums2}[n]$. Otherwise, we need to record a minimum difference $d$, which represents the minimum number of operations required to adjust some element to $\\text{nums2}[n]$.\n\nFinally, if no element satisfying the condition is found after the iteration, we need to add $d$ to $\\text{ans}$, indicating that we need extra operations to adjust some element to $\\text{nums2}[n]$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3725, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3726, "explanations": { "1": "We start from the lowest digit of $n$ and check each digit one by one. If the digit is not zero, we add it to the result. We also need a variable to keep track of the current digit position in order to correctly construct the final integer.\n\nSpecifically, we can use a variable $k$ to represent the current digit position, then check each digit from the lowest to the highest. If the digit is not zero, we multiply it by $k$ and add it to the result, and then multiply $k$ by 10 for the next digit.\n\nIn the end, we obtain an integer without any zeros.\n\nThe time complexity is $O(d)$, where $d$ is the number of digits in $n$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(d)", "space_complexity": "O(1)" }, { "problem_id": 3727, "explanations": { "1": "We can sort the elements of the array by their squared values, then place the elements with larger squared values at even indices and those with smaller squared values at odd indices.\n\nThe final alternating score is the sum of the squared values of the larger elements minus the sum of the squared values of the smaller elements, that is, the sum of the squares of the latter half of the sorted array $\\text{nums}$ minus the sum of the squares of the first half.\n\nThe time complexity is $O(n \\log n)$ and the space complexity is $O(\\log n)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 3728, "explanations": { "1": "We define a prefix sum array $\\textit{s}$, where $s[i]$ represents the sum of the first $i$ elements in the array $\\text{capacity}$, that is, $s[i] = \\text{capacity}[0] + \\text{capacity}[1] + \\ldots + \\text{capacity}[i-1]$. Initially, $s[0] = 0$.\n\nAccording to the problem statement, a subarray $\\text{capacity}[l..r]$ is a stable array if:\n\n$$\n\\text{capacity}[l] = \\text{capacity}[r] = \\text{capacity}[l + 1] + \\text{capacity}[l + 2] + \\ldots + \\text{capacity}[r - 1]\n$$\n\nThat is:\n\n$$\n\\text{capacity}[l] = \\text{capacity}[r] = s[r] - s[l + 1]\n$$\n\nWe can enumerate the right endpoint $r$. For each $r$, we calculate the left endpoint $l = r - 2$, and store the information of the left endpoints that meet the condition in a hash table. Specifically, we use a hash table $\\text{cnt}$ to record the number of occurrences of each key-value pair $(\\text{capacity}[l], \\text{capacity}[l] + s[l + 1])$.\n\nWhen we enumerate the right endpoint $r$, we can query the hash table $\\text{cnt}$ to get the number of left endpoints that meet the condition, that is, the number of occurrences of the key-value pair $(\\text{capacity}[r], s[r])$, and add it to the answer.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3729, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3730, "explanations": { "1": "According to the problem statement, the order of jumps affects the total calories burned. To maximize calorie consumption, we can use a greedy strategy by prioritizing jumps with the largest height differences.\n\nTherefore, we can first sort the block heights, then start jumping from the highest block, then to the lowest block, and so on, until all blocks have been jumped on.\n\nThe specific steps are as follows:\n\n1. Sort the array $\\text{heights}$.\n1. Initialize the variable $\\text{pre} = 0$ to represent the height of the previous block, and $\\text{ans} = 0$ to represent the total calories burned.\n1. Use two pointers: the left pointer $\\text{l}$ points to the beginning of the array, and the right pointer $\\text{r}$ points to the end of the array.\n1. While $\\text{l} < \\text{r}$, do the following:\n 1. Calculate the calories burned from the previous block to the block pointed to by the right pointer and add it to $\\text{ans}$.\n 1. Calculate the calories burned from the block pointed to by the right pointer to the block pointed to by the left pointer and add it to $\\text{ans}$.\n 1. Update $\\text{pre}$ to the height of the block pointed to by the left pointer.\n 1. Move the left pointer one step to the right and the right pointer one step to the left.\n1. Finally, calculate the calories burned from the previous block to the middle block and add it to $\\text{ans}$.\n\nThe time complexity is $O(n \\log n)$ and the space complexity is $O(\\log n)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 3731, "explanations": { "1": "We first find the minimum and maximum values in the array $\\textit{nums}$, denoted as $\\textit{mn}$ and $\\textit{mx}$. Then we use a hash table to store all elements in the array $\\textit{nums}$.\n\nNext, we iterate through the interval $[\\textit{mn} + 1, \\textit{mx} - 1]$. For each integer $x$, if $x$ is not in the hash table, we add it to the answer list.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3732, "explanations": { "1": "According to the problem description, we can replace one element in the array with any integer in the range $[-10^5, 10^5]$. To maximize the product of three elements, we can consider the following cases:\n\n1. Select the two smallest elements in the array and replace the third element with $10^5$.\n2. Select the two largest elements in the array and replace the third element with $10^5$.\n3. Select the smallest element and the two largest elements in the array, and replace the middle element with $-10^5$.\n\nThe maximum product among these three cases is the answer.\n\nTherefore, we can first sort the array, then calculate the products for the above three cases, and return the maximum value among them.\n\nThe time complexity is $O(n \\log n)$ and the space complexity is $O(\\log n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 3733, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3734, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3735, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3736, "explanations": { "1": "This problem requires making all elements in the array equal, with each operation only able to increase a single element by 1. To minimize the number of operations, we should make all elements equal to the maximum value in the array.\n\nTherefore, we can first calculate the maximum value $\\textit{mx}$ and the sum of array elements $\\textit{s}$. The number of operations required to make all elements equal to $\\textit{mx}$ is $\\textit{mx} \\times n - \\textit{s}$, where $n$ is the length of the array.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3737, "explanations": { "1": "We can enumerate all subarrays and use a hash table to record the occurrence count of each element in the subarray, then determine whether the target element is the majority element of that subarray.\n\nSpecifically, we enumerate the starting position $i$ of the subarray in the range $[0, n-1]$, then enumerate the ending position $j$ in the range $[i, n-1]$. For each subarray $nums[i..j]$, we update the hash table $\\textit{cnt}$. If $\\textit{cnt}[\\textit{target}] > \\frac{(j-i+1)}{2}$, we increment the answer by $1$.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 3738, "explanations": { "1": "We can use two arrays $\\textit{left}$ and $\\textit{right}$ to record the length of the longest non-decreasing subarray ending and starting at each position, respectively. Initially, $\\textit{left}[i] = 1$ and $\\textit{right}[i] = 1$.\n\nThen, we traverse the array in the range $[1, n-1]$. If $\\textit{nums}[i] \\geq \\textit{nums}[i-1]$, we update $\\textit{left}[i]$ to $\\textit{left}[i-1] + 1$. Similarly, we traverse the array backwards in the range $[n-2, 0]$. If $\\textit{nums}[i] \\leq \\textit{nums}[i+1]$, we update $\\textit{right}[i]$ to $\\textit{right}[i+1] + 1$.\n\nNext, we can compute the final answer by enumerating each position. For each position $i$, we can calculate the length of the longest non-decreasing subarray centered at $i$ in the following way:\n\n1. If the elements on the left and right sides of $i$ do not satisfy $\\textit{nums}[i-1] \\leq \\textit{nums}[i+1]$, we can only choose the non-decreasing subarray from either the left or right side, so the answer is $\\max(\\textit{left}[i-1], \\textit{right}[i+1]) + 1$.\n2. Otherwise, we can replace position $i$ with an appropriate value so that the non-decreasing subarrays on the left and right can be connected, so the answer is $\\textit{left}[i-1] + \\textit{right}[i+1] + 1$.\n\nFinally, we take the maximum value across all positions as the final answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3739, "explanations": { "1": "According to the problem description, we can treat elements equal to $\\textit{target}$ in the array as $1$, and elements not equal to $\\textit{target}$ as $-1$. This way, $\\textit{target}$ being the majority element of a subarray is equivalent to the number of $1$s in the subarray being strictly greater than the number of $-1$s, i.e., the sum of the subarray is strictly greater than $0$.\n\nWe can enumerate subarrays ending at each position. Let the prefix sum at the current position be $\\textit{s}$. Then the number of subarrays ending at this position with a sum greater than $0$ is equivalent to the count of prefix sums that are less than $\\textit{s}$. We can use a Binary Indexed Tree to maintain the occurrence count of prefix sums, allowing us to efficiently calculate the answer. The range of prefix sums is $[-n, n]$. We can shift all prefix sums right by $n+1$ units to transform the range to $[1, 2n+1]$.\n\nThe time complexity is $O(n \\log n)$, and the space complexity is $O(n)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3740, "explanations": { "1": "We can use a hash table $\\textit{g}$ to store the list of indices for each number in the array. While traversing the array, we add each number's index to its corresponding list in the hash table. Define a variable $\\textit{ans}$ to store the answer, with an initial value of infinity $\\infty$.\n\nNext, we iterate through each index list in the hash table. If the length of an index list for a particular number is greater than or equal to $3$, it means there exists a valid triplet. To minimize the distance, we can choose three consecutive indices $i$, $j$, and $k$ from that number's index list, where $i < j < k$. The distance of this triplet is $j - i + k - j + k - i = 2 \\times (k - i)$. We traverse all combinations of three consecutive indices in the list, calculate the distance, and update the answer.\n\nFinally, if the answer is still the initial value $\\infty$, it means no valid triplet exists, so we return $-1$; otherwise, we return the calculated minimum distance.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3741, "explanations": { "1": "We can use a hash table $\\textit{g}$ to store the list of indices for each number in the array. While traversing the array, we add each number's index to its corresponding list in the hash table. Define a variable $\\textit{ans}$ to store the answer, with an initial value of infinity $\\infty$.\n\nNext, we iterate through each index list in the hash table. If the length of an index list for a particular number is greater than or equal to $3$, it means there exists a valid triplet. To minimize the distance, we can choose three consecutive indices $i$, $j$, and $k$ from that number's index list, where $i < j < k$. The distance of this triplet is $j - i + k - j + k - i = 2 \\times (k - i)$. We traverse all combinations of three consecutive indices in the list, calculate the distance, and update the answer.\n\nFinally, if the answer is still the initial value $\\infty$, it means no valid triplet exists, so we return $-1$; otherwise, we return the calculated minimum distance.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3742, "explanations": { "1": "We define a function $\\textit{dfs}(i, j, k)$ that represents the maximum score achievable when starting from position $(i, j)$ and reaching the endpoint $(0, 0)$ with remaining cost not exceeding $k$. We use memoization search to avoid redundant calculations.\n\nSpecifically, the implementation steps of function $\\textit{dfs}(i, j, k)$ are as follows:\n\n1. If the current coordinate $(i, j)$ is out of bounds or the remaining cost $k$ is less than $0$, return negative infinity to indicate that the endpoint cannot be reached.\n2. If the current coordinate is the starting point $(0, 0)$, return $0$, indicating that the endpoint has been reached (the problem guarantees the starting point has value $0$).\n3. Calculate the score contribution $\\textit{res}$ of the current cell. If the current cell's value is not $0$, decrement the remaining cost $k$ by $1$.\n4. Recursively calculate the maximum scores achievable from the upper cell $(i-1, j)$ and the left cell $(i, j-1)$ when reaching the endpoint with remaining cost not exceeding $k$, denoted as $\\textit{a}$ and $\\textit{b}$ respectively.\n5. Add the current cell's score contribution $\\textit{res}$ to $\\max(\\textit{a}, \\textit{b})$ to get the maximum score achievable from the current cell, and return this value.\n\nFinally, we call $\\textit{dfs}(m-1, n-1, k)$ to calculate the maximum score achievable when starting from the bottom-right corner and reaching the top-left corner with remaining cost not exceeding $k$. If the result is less than $0$, return $-1$ to indicate no valid path exists; otherwise, return the result.\n\nThe time complexity is $O(m \\times n \\times k)$, and the space complexity is $O(m \\times n \\times k)$, where $m$ and $n$ are the number of rows and columns in the grid, and $k$ is the maximum allowed cost." }, "is_english": true, "time_complexity": "O(m \\times n \\times k)", "space_complexity": "O(m \\times n \\times k)" }, { "problem_id": 3743, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3744, "explanations": { "1": "We first split the string $\\textit{s}$ into multiple words by spaces. For each word $\\textit{w}$, we can calculate the length it occupies in the expanded string $\\textit{t}$ as $m=\\frac{(1+|\\textit{w}|)\\cdot |\\textit{w}|}{2}$.\n\nIf $k = m$, it means the $k$-th character is a space, and we can directly return a space.\n\nIf $k > m$, it means the $k$-th character is not in the expanded part of the current word. We subtract the expanded length $m$ of the current word and the space length $1$ from $k$, and continue processing the next word.\n\nOtherwise, the $k$-th character is in the expanded part of the current word. We can find the $k$-th character by simulating the expansion process:\n\n- Initialize a variable $\\textit{cur} = 0$ to represent the number of characters that have been expanded so far.\n- Iterate through each character $\\textit{w}[i]$ of the word $\\textit{w}$:\n - Increase $\\textit{cur}$ by $i + 1$.\n - If $k < \\textit{cur}$, it means the $k$-th character is $\\textit{w}[i]$, and we return this character.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of the string $\\textit{s}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3745, "explanations": { "1": "According to the problem description, we need to choose three elements $a$, $b$, and $c$ at distinct indices such that the value of the expression $a + b - c$ is maximized.\n\nWe only need to traverse the array to find the largest two elements $a$ and $b$ and the smallest element $c$. Then we can calculate the value of the expression.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3746, "explanations": { "1": "According to the problem description, as long as adjacent characters are different, we can remove them. Therefore, the final remaining string will only contain the same character, either all 'a' or all 'b'. So we only need to count the number of 'a' and 'b' in the string, and the final minimum length is the absolute difference between their counts.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3747, "explanations": { "1": "The problem essentially asks us to count the number of integers in the range $[1, n]$ that do not contain the digit 0. We can solve this problem using digit DP.\n\nWe design a function $\\text{dfs}(i, \\text{zero}, \\text{lead}, \\text{limit})$, which represents the number of valid solutions when we are currently processing the $i$-th digit of the number. We use $\\text{zero}$ to indicate whether a non-zero digit has appeared in the current number, $\\text{lead}$ to indicate whether we are still processing leading zeros, and $\\text{limit}$ to indicate whether the current number is constrained by the upper bound. The answer is $\\text{dfs}(0, 0, 1, 1)$.\n\nIn the function $\\text{dfs}(i, \\text{zero}, \\text{lead}, \\text{limit})$, if $i$ is greater than or equal to the length of the number, we can check $\\text{zero}$ and $\\text{lead}$. If $\\text{zero}$ is false and $\\text{lead}$ is false, it means the current number does not contain 0, so we return $1$; otherwise, we return $0$.\n\nFor $\\text{dfs}(i, \\text{zero}, \\text{lead}, \\text{limit})$, we can enumerate the value of the current digit $d$, then recursively calculate $\\text{dfs}(i+1, \\text{nxt\\_zero}, \\text{nxt\\_lead}, \\text{nxt\\_limit})$, where $\\text{nxt\\_zero}$ indicates whether a non-zero digit has appeared in the current number, $\\text{nxt\\_lead}$ indicates whether we are still processing leading zeros, and $\\text{nxt\\_limit}$ indicates whether the current number is constrained by the upper bound. If $\\text{limit}$ is true, then $up$ is the upper bound of the current digit; otherwise, $up$ is $9$.\n\nThe time complexity is $O(\\log_{10} n \\times D)$ and the space complexity is $O(\\log_{10} n)$, where $D$ represents the count of digits from 0 to 9." }, "is_english": true, "time_complexity": "O(\\log_{10} n \\times D)", "space_complexity": "O(\\log_{10} n)" }, { "problem_id": 3748, "explanations": { "1": "According to the problem description, a stable subarray is defined as a subarray without inversion pairs, meaning the elements in the subarray are arranged in non-decreasing order. Therefore, we can divide the array into several non-decreasing segments, using an array $\\text{seg}$ to record the starting position of each segment. At the same time, we need a prefix sum array $\\text{s}$ to record the number of stable subarrays within each segment.\n\nThen, for each query $[l, r]$, there may be 3 cases:\n\n1. The query interval $[l, r]$ is completely contained within a single segment. In this case, the number of stable subarrays can be directly calculated using the formula $\\frac{(k + 1) \\cdot k}{2}$, where $k = r - l + 1$.\n2. The query interval $[l, r]$ spans multiple segments. In this case, we need to separately calculate the number of stable subarrays in the left incomplete segment, the right incomplete segment, and the complete segments in the middle, then add them together to get the final result.\n\nThe time complexity is $O((n + q) \\log n)$, where $n$ is the length of the array and $q$ is the number of queries. The space complexity is $O(n)$." }, "is_english": true, "time_complexity": "O((n + q) \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3749, "explanations": { "1": "We define a recursive function $\\text{parse}(i)$ to parse the subexpression starting from index $i$ and return the computed result along with the next unprocessed index position. The answer is $\\text{parse}(0)[0]$.\n\nThe implementation of the function $\\text{parse}(i)$ is as follows:\n\n1. If the current position $i$ is a digit or a negative sign `-`, continue scanning forward until a non-digit character is encountered, parse an integer, and return that integer along with the next unprocessed index position.\n2. Otherwise, the current position $i$ is the starting position of an operator `op`. We continue scanning forward until we encounter a left parenthesis `(`, parsing the operator string `op`. Then we skip the left parenthesis, recursively call $\\text{parse}$ to parse the first parameter $a$, skip the comma, recursively call $\\text{parse}$ to parse the second parameter $b$, and finally skip the right parenthesis `)`.\n3. Based on the operator `op`, calculate the result of $a$ and $b$, and return that result along with the next unprocessed index position.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of the expression string." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3750, "explanations": { "1": "We first convert the integer $n$ into a binary string $s$. Then we use two pointers to traverse from both ends of the string towards the center, counting the number of positions where the characters differ, denoted as $cnt$. Since each flip can only affect one bit, the total number of flips is $cnt \\times 2$.\n\nThe time complexity is $O(\\log n)$ and the space complexity is $O(\\log n)$, where $n$ is the input integer." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 3751, "explanations": { "1": "We define a helper function $f(x)$ to calculate the waviness value of integer $x$. In this function, we store each digit of integer $x$ in an array $\\textit{nums}$. If the number has fewer than 3 digits, the waviness value is 0. Otherwise, we iterate through each non-leading and non-trailing digit in the array $\\textit{nums}$, determine whether it is a peak or valley, and count the waviness value.\n\nThen, we iterate through each integer $x$ in the range $[\\textit{num1}, \\textit{num2}]$ and accumulate its waviness value $f(x)$ to obtain the final result.\n\nThe time complexity is $O((\\textit{num2} - \\textit{num1} + 1) \\cdot \\log \\textit{num2})$ and the space complexity is $O(\\log \\textit{num2})$." }, "is_english": true, "time_complexity": "O((\\textit{num2} - \\textit{num1} + 1) \\cdot \\log \\textit{num2})", "space_complexity": "O(\\log \\textit{num2})" }, { "problem_id": 3752, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3753, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3754, "explanations": { "1": "We can simulate the required operation by processing the number digit by digit. While processing each digit, we concatenate non-zero digits to form a new integer $x$ and calculate the digit sum $s$. Finally, we return $x \\times s$.\n\nThe time complexity is $O(\\log n)$ and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 3755, "explanations": { "1": "We use a hash table to record the first occurrence position of each state $(a, b)$, where $a$ represents the prefix XOR sum, and $b$ represents the prefix even count minus the prefix odd count. When we encounter the same state $(a, b)$ while traversing the array, it means that the subarray from the last occurrence of this state to the current position satisfies both bitwise XOR equals 0 and equal counts of even and odd numbers. We can then update the answer by taking the maximum length. Otherwise, we store this state and the current position in the hash table.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3756, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3757, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3758, "explanations": { "1": "We first establish a mapping relationship between number words and their corresponding digits, recorded in array $d$, where $d[i]$ represents the word corresponding to digit $i$.\n\nThen we traverse the string $s$ from left to right. For each position $i$, we enumerate the number words $d[j]$ in order and check whether the substring starting from position $i$ matches $d[j]$. If a match is found, we add digit $j$ to the result and move position $i$ forward by $|d[j]|$ positions. Otherwise, we move position $i$ forward by 1 position.\n\nWe repeat this process until we have traversed the entire string $s$. Finally, we concatenate the digits in the result into a string and return it.\n\nThe time complexity is $O(n \\times |d|)$ and the space complexity is $O(|d|)$, where $n$ is the length of string $s$ and $|d|$ is the number of digit words." }, "is_english": true, "time_complexity": "O(n \\times |d|)", "space_complexity": "O(|d|)" }, { "problem_id": 3759, "explanations": { "1": "If $k = 0$, then all elements in the array are qualified elements, and we can directly return the length of the array.\n\nOtherwise, we sort the array, and let $n$ be the length of the sorted array. For each index $i$ satisfying $0 \\leq i < n - k$, if the element at index $i$ is strictly less than the element at index $n - k$, then it is a qualified element. We just need to count the number of such elements and return it.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 3760, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3761, "explanations": { "1": "We can use a hash table $\\textit{pos}$ to record the last occurrence position of each reversed number.\n\nWe first initialize the answer $\\textit{ans} = n + 1$, where $n$ is the length of the array $\\textit{nums}$.\n\nNext, we iterate through the array $\\textit{nums}$. For each index $i$ and its corresponding number $x = \\textit{nums}[i]$, if the key $x$ exists in $\\textit{pos}$, it means there exists an index $j$ such that $\\textit{nums}[j]$ reversed equals $x$. In this case, we update the answer to $\\min(\\textit{ans}, i - \\textit{pos}[x])$. Then, we update $\\textit{pos}[\\text{reverse}(x)]$ to $i$. Continue this process until we finish iterating through the entire array.\n\nFinally, if the answer $\\textit{ans}$ is still equal to $n + 1$, it means no mirror pair exists, and we return $-1$; otherwise, we return the answer $\\textit{ans}$.\n\nThe time complexity is $O(n \\times \\log M)$, where $n$ is the length of the array $\\textit{nums}$, and $M$ is the maximum value in the array. The space complexity is $O(n)$, which is used to store the hash table $\\textit{pos}$." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(n)" }, { "problem_id": 3762, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3763, "explanations": { "1": "We observe that at each step, we want to select the largest number among those that satisfy the condition to add to the total sum. Therefore, we can use a greedy approach to solve this problem.\n\nWe first sort an index array $\\textit{idx}$ of length $n$ in ascending order by their corresponding thresholds. Then, we use a sorted set or priority queue (max heap) to maintain the numbers that currently satisfy the condition. At each step, we add all numbers whose thresholds are less than or equal to the current step number into the sorted set or priority queue, and then select the largest number among them to add to the total sum. If the sorted set or priority queue is empty at this point, it means there are no numbers that satisfy the condition, and we end the process.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3764, "explanations": { "1": "We first filter out all top students, denoted as `top_students`, i.e., students who have completed at least 5 courses with an average rating of at least 4. Then for each top student, we sort by completion time and find all consecutive course pairs, denoted as `course_pairs`. Finally, we group and count all course pairs, calculate the occurrence count of each course pair, and output the results sorted as required." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3765, "explanations": { "1": "We define a function $\\text{is\\_prime}(x)$ to determine whether a number $x$ is prime. Specifically, if $x < 2$, then $x$ is not prime; otherwise, we check all integers $i$ from $2$ to $\\sqrt{x}$. If there exists some $i$ that divides $x$, then $x$ is not prime; otherwise, $x$ is prime.\n\nNext, we convert the integer $\\textit{num}$ to a string $s$, and sequentially check whether the integer corresponding to each prefix and suffix of $s$ is prime. For prefixes, we construct the integer $x$ from left to right; for suffixes, we construct the integer $x$ from right to left. If during the checking process we find that the integer corresponding to some prefix or suffix is not prime, we return $\\text{false}$; if all integers corresponding to prefixes and suffixes are prime, we return $\\text{true}$.\n\nThe time complexity is $O(\\sqrt{n} \\times \\log n)$, and the space complexity is $O(\\log n)$, where $n$ is the value of the integer $\\textit{num}$." }, "is_english": true, "time_complexity": "O(\\sqrt{n} \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 3766, "explanations": { "1": "We observe that the range of numbers given in the problem is only $[1, 5000]$. Therefore, we directly preprocess all binary palindromic numbers in the range $[0, 2^{14})$ and store them in an array, denoted as $\\textit{p}$.\n\nNext, for each number $x$, we use binary search to find the first palindromic number greater than or equal to $x$ in the array $\\textit{p}$, denoted as $\\textit{p}[i]$, as well as the first palindromic number less than $x$, denoted as $\\textit{p}[i - 1]$. Then, we calculate the number of operations required to convert $x$ to these two palindromic numbers and take the minimum value as the answer.\n\nThe time complexity is $O(n \\times \\log M)$, and the space complexity is $O(M)$. Where $n$ is the length of the array $\\textit{nums}$, and $M$ is the number of preprocessed binary palindromic numbers." }, "is_english": true, "time_complexity": "O(n \\times \\log M)", "space_complexity": "O(M)" }, { "problem_id": 3767, "explanations": { "1": "We can first assign all tasks to technique 2, so the initial total score is $\\sum_{i=0}^{n-1} technique2[i]$.\n\nThen, we calculate the score increase for each task if it were completed using technique 1 instead, denoted as $\\text{diff}[i] = technique1[i] - technique2[i]$. We sort this in descending order to obtain a sorted array of task indices $\\text{idx}$.\n\nNext, we select the first $k$ tasks to be completed using technique 1 and add their score differences to the total score. For the remaining tasks, if a task can increase the score by using technique 1 (i.e., $\\text{diff}[i] \\geq 0$), we also choose to complete it using technique 1.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Where $n$ is the number of tasks." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3768, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3769, "explanations": { "1": "We define a function $f(x)$ to calculate the binary reflection value of integer $x$. Specifically, we continuously extract the lowest bit of $x$ and add it to the end of the result $y$ until $x$ becomes $0$.\n\nThen, we sort the array $\\textit{nums}$ with the sorting key being the tuple $(f(x), x)$ of each element's binary reflection value and original value. This ensures that when two elements have the same binary reflection value, the smaller original value will be placed first.\n\nFinally, we return the sorted array.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$. Where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 3770, "explanations": { "1": "We can preprocess a list of all prime numbers less than or equal to $5 \\times 10^5$, then calculate the consecutive prime sums starting from 2, and store those sums that are prime numbers in an array $s$.\n\nFor each query, we simply need to use binary search in array $s$ to find the maximum value less than or equal to $n$.\n\nIn terms of time complexity, preprocessing the primes takes $O(M \\log \\log M)$ time, and each query takes $O(\\log k)$ time, where $M$ is the upper limit of preprocessing, and $k$ is the length of array $s$. In this problem, $k \\leq 40$." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3771, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3772, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3773, "explanations": { "1": "We can use a hash table $\\textit{cnt}$ to record the number of occurrences of each run length. We traverse the string $s$, and for each run, we calculate its length $m$ and increment $\\textit{cnt}[m]$ by $1$. Finally, the answer is the maximum value in $\\textit{cnt}$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3774, "explanations": { "1": "We first sort the array $\\textit{nums}$. Then we calculate the sum of the first $k$ elements and the sum of the last $k$ elements in the array, and finally return the difference between them.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(\\log n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(\\log n)" }, { "problem_id": 3775, "explanations": { "1": "We first split the string by spaces into a word list $\\textit{words}$. Then we calculate the number of vowels $\\textit{cnt}$ in the first word. Next, we iterate through each subsequent word, calculate its number of vowels, and if it equals $\\textit{cnt}$, reverse the word. Finally, we rejoin the processed word list into a string and return it.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3776, "explanations": { "1": "We first calculate the sum of the array $\\textit{balance}$. If the sum is less than $0$, it is impossible to make all balances non-negative, so we directly return $-1$. Then we find the minimum balance in the array and its index. If the minimum balance is greater than or equal to $0$, all balances are already non-negative, so we directly return $0$.\n\nNext, we calculate the amount of balance needed $\\textit{need}$, which is the opposite of the minimum balance. Then starting from the index of the minimum balance, we traverse the array to the left and right, taking as much balance as possible from each position to fill $\\textit{need}$, and calculate the number of moves. We continue until $\\textit{need}$ becomes $0$, and return the total number of moves.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{balance}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3777, "explanations": { "1": "We can convert the string $s$ into an array $\\textit{nums}$ of length $n$, where $\\textit{nums}[0] = 0$, and for $1 \\leq i < n$, if $s[i] = s[i-1]$, then $\\textit{nums}[i] = 1$, otherwise $\\textit{nums}[i] = 0$. This way $\\textit{nums}[i]$ represents whether there are adjacent and equal characters at index $i$. Then calculating the minimum number of character deletions required to make the substring $s[l..r]$ an alternating string in the interval $[l, r]$ is equivalent to calculating the sum of elements in the $\\textit{nums}$ array over the interval $[l+1, r]$.\n\nTo handle queries efficiently, we can use a Binary Indexed Tree to maintain the prefix sum of the $\\textit{nums}$ array. For queries of type $[1, j]$, we need to flip $\\textit{nums}[j]$ and $\\textit{nums}[j+1]$ (if $j+1 < n$), and update the Binary Indexed Tree. For queries of type $[2, l, r]$, we can quickly calculate the sum of elements over the interval $[l+1, r]$ through the Binary Indexed Tree.\n\nThe time complexity is $O((n + q) \\log n)$, and the space complexity is $O(n)$, where $n$ is the length of the string $s$, and $q$ is the number of queries." }, "is_english": true, "time_complexity": "O((n + q) \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3778, "explanations": { "1": "The problem is essentially equivalent to finding a path from node $0$ to node $n-1$, where we have one opportunity to treat the weight of a traversed edge as $0$, in order to minimize the sum of path weights.\n\nWe first convert $\\textit{edges}$ into an adjacency list $\\textit{g}$, where $\\textit{g}[u]$ stores all edges $(v, w)$ connected to node $u$, indicating that there is an edge with weight $w$ between node $u$ and node $v$.\n\nNext, we use Dijkstra's algorithm to find the shortest path. We define a 2D array $\\textit{dist}$, where $\\textit{dist}[u][0]$ represents the minimum sum of path weights from node $0$ to node $u$ without using the opportunity to treat an edge weight as $0$; $\\textit{dist}[u][1]$ represents the minimum sum of path weights from node $0$ to node $u$ having already used the opportunity to treat an edge weight as $0$.\n\nWe use a priority queue $\\textit{pq}$ to store pending nodes. Initially, we enqueue $(0, 0, 0)$, indicating that we start from node $0$, with a current path weight sum of $0$, and haven't used the opportunity.\n\nIn each iteration, we dequeue the node $(\\textit{cur}, u, \\textit{used})$ with the minimum path weight sum from the priority queue. If the current path weight sum $\\textit{cur}$ is greater than $\\textit{dist}[u][\\textit{used}]$, we skip this node.\n\nIf the current node $u$ is node $n-1$ and we have already used the opportunity $\\textit{used} = 1$, we return the current path weight sum $\\textit{cur}$.\n\nFor each edge $(v, w)$ of node $u$, we calculate the path weight sum to reach node $v$ without using the opportunity: $\\textit{nxt} = \\textit{cur} + w$. If $\\textit{nxt} < \\textit{dist}[v][\\textit{used}]$, we update $\\textit{dist}[v][\\textit{used}]$ and enqueue $(\\textit{nxt}, v, \\textit{used})$.\n\nIf we haven't used the opportunity yet $\\textit{used} = 0$, we calculate the path weight sum to reach node $v$ when using the opportunity: $\\textit{nxt} = \\textit{cur}$. If $\\textit{nxt} < \\textit{dist}[v][1]$, we update $\\textit{dist}[v][1]$ and enqueue $(\\textit{nxt}, v, 1)$.\n\nAfter the traversal ends, we return $\\textit{dist}[n-1][1]$ as the answer.\n\nThe time complexity is $O(m \\times \\log n)$, and the space complexity is $O(n + m)$, where $n$ and $m$ are the number of nodes and edges, respectively." }, "is_english": true, "time_complexity": "O(m \\times \\log n)", "space_complexity": "O(n + m)" }, { "problem_id": 3779, "explanations": { "1": "We can traverse the array $\\textit{nums}$ in reverse order and use a hash table $\\textit{st}$ to record the elements we have already traversed. When we traverse to element $\\textit{nums}[i]$, if $\\textit{nums}[i]$ is already in the hash table $\\textit{st}$, it means we need to remove all elements in $\\textit{nums}[0..i]$, and the number of operations required is $\\left\\lfloor \\frac{i}{3} \\right\\rfloor + 1$. Otherwise, we add $\\textit{nums}[i]$ to the hash table $\\textit{st}$ and continue to traverse the next element.\n\nAfter the traversal is complete, if no duplicate elements are found, then all elements in the array are already distinct, no operations are needed, and the answer is $0$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3780, "explanations": { "1": "We first sort the array $\\textit{nums}$, then divide the elements in the array into three groups based on their modulo $3$ results, denoted as $\\textit{g}[0]$, $\\textit{g}[1]$, and $\\textit{g}[2]$. Where $\\textit{g}[i]$ stores all elements that satisfy $\\textit{nums}[j] \\bmod 3 = i$.\n\nNext, we enumerate the cases of selecting one element each from $\\textit{g}[a]$ and $\\textit{g}[b]$, where $a, b \\in \\{0, 1, 2\\}$. Based on the modulo $3$ results of the two selected elements, we can determine which group the third element should be selected from to ensure that the sum of the triplet is divisible by $3$. Specifically, the third element should be selected from $\\textit{g}[c]$, where $c = (3 - (a + b) \\bmod 3) \\bmod 3$.\n\nFor each combination of $(a, b)$, we try to take out the largest element from both $\\textit{g}[a]$ and $\\textit{g}[b]$, then take out the largest element from $\\textit{g}[c]$, calculate the sum of these three elements, and update the answer.\n\nThe time complexity is $O(n \\log n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(n)$." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3781, "explanations": { "1": "According to the problem statement, each `'1'` can be swapped left any number of times, so each `'1'` can choose the largest unpicked number to its left. We can maintain these candidates with a max-heap.\n\nTraverse the string $s$: for each position $i$, push the corresponding number $\\textit{nums}[i]$ into the max-heap; if $s[i] = '1'$, pop the maximum from the heap and add it to the answer.\n\nAfter the traversal, the accumulated sum is the maximum score.\n\nThe time complexity is $O(n \\log n)$ and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3782, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3783, "explanations": { "1": "We define a function $\\text{reverse}(x)$ to reverse the digits of integer $x$. Specifically, we initialize a variable $y$ to $0$, then repeatedly append the last digit of $x$ to the end of $y$, and remove the last digit from $x$, until $x$ becomes $0$. Finally, $y$ is the reversed integer.\n\nNext, we compute the mirror distance of integer $n$, which is $\\text{abs}(n - \\text{reverse}(n))$, and return the result.\n\nThe time complexity is $O(\\log n)$ and the space complexity is $O(1)$, where $n$ is the size of the input integer." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 3784, "explanations": { "1": "We calculate the total deletion cost for each character in the string and store it in a hash table $g$, where the key is the character and the value is the corresponding total deletion cost. We also calculate the total cost $\\textit{tot}$ of deleting all characters.\n\nNext, we iterate through the hash table $g$. For each character $c$, we calculate the minimum deletion cost required to keep that character, which is $\\textit{tot} - g[c]$. The final answer is the minimum of all the minimum deletion costs corresponding to each character.\n\nThe time complexity is $O(n)$ and the space complexity is $O(|\\Sigma|)$, where $n$ is the length of the string $s$, and $\\Sigma$ is the set of distinct characters in the string." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 3785, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3786, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3787, "explanations": { "1": "We first convert the array $\\text{edges}$ into an adjacency list representation of an undirected graph, where $g[u]$ represents all nodes adjacent to node $u$.\n\nNext, we can use Breadth-First Search (BFS) to find the diameter endpoints of the tree. The specific steps are as follows:\n\n1. Starting from any node (e.g., node $0$), use BFS to find the farthest node $a$ from that node.\n2. Starting from node $a$, use BFS again to find the farthest node $b$ from node $a$, as well as the distance array $\\text{dist1}$ from node $a$ to all other nodes.\n3. Starting from node $b$, use BFS to find the distance array $\\text{dist2}$ from node $b$ to all other nodes.\n4. The diameter length of the tree is $\\text{dist1}[b]$. For each node $i$, if $\\text{dist1}[i]$ or $\\text{dist2}[i]$ equals the diameter length, then node $i$ is a special node.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3788, "explanations": { "1": "We first define an array $\\textit{suf}$ of length $n$, where $\\textit{suf}[i]$ represents the minimum value of the array $\\textit{nums}$ from index $i$ to index $n - 1$. We can traverse the array $\\textit{nums}$ from back to front to compute the array $\\textit{suf}$.\n\nNext, we define a variable $\\textit{pre}$ to represent the prefix sum of the array $\\textit{nums}$. We traverse the first $n - 1$ elements of the array $\\textit{nums}$. For each index $i$, we add $\\textit{nums}[i]$ to $\\textit{pre}$ and calculate the split score $\\textit{score}(i) = \\textit{pre} - \\textit{suf}[i + 1]$. We use a variable $\\textit{ans}$ to maintain the maximum value among all split scores.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3789, "explanations": { "1": "We can divide the purchasing strategy into three cases:\n\n1. Only buy Type 1 and Type 2 items. The total cost is $a = \\textit{need1} \\times \\textit{cost1} + \\textit{need2} \\times \\textit{cost2}$.\n2. Only buy Type 3 items. The total cost is $b = \\textit{costBoth} \\times \\max(\\textit{need1}, \\textit{need2})$.\n3. Buy some Type 3 items, and purchase Type 1 and Type 2 items separately for the remaining needs. Let $\\textit{mn} = \\min(\\textit{need1}, \\textit{need2})$, then the total cost is $c = \\textit{costBoth} \\times \\textit{mn} + (\\textit{need1} - \\textit{mn}) \\times \\textit{cost1} + (\\textit{need2} - \\textit{mn}) \\times \\textit{cost2}$.\n\nFinally, we return the minimum value among the three cases, $\\min(a, b, c)$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 3790, "explanations": { "1": "First, if $k$ is even, there is no valid $n$ that satisfies the condition, so we directly return $-1$.\n\nNext, we can simulate the process of constructing an all-ones number $n$ while taking the modulo with $k$ to determine whether a valid $n$ exists.\n\nWe loop $k$ times to check whether there exists an all-ones number $n$ divisible by $k$ within these $k$ iterations. In each iteration, we multiply the current remainder by $10$, add $1$, and then take the modulo with $k$. If the remainder becomes $0$ in some iteration, it means we have found a valid $n$, and we return the current iteration count (i.e., the number of digits in the all-ones number). If no valid $n$ is found after the loop ends, we return $-1$.\n\nThe time complexity is $O(k)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(k)", "space_complexity": "O(1)" }, { "problem_id": 3791, "explanations": { "1": "First, if $\\textit{high} < 11$, there are no balanced integers in the range, so we directly return $0$. Otherwise, we update $\\textit{low}$ to $\\max(\\textit{low}, 11)$.\n\nThen we design a function $\\textit{dfs}(\\textit{pos}, \\textit{diff}, \\textit{lim})$, which represents processing the $\\textit{pos}$-th digit of the number, where $\\textit{diff}$ is the difference between the sum of digits at odd positions and the sum of digits at even positions, and $\\textit{lim}$ indicates whether the current digit is constrained by the upper bound. The function returns the number of balanced integers that can be constructed from the current state.\n\nThe execution logic of the function is as follows:\n\n- If $\\textit{pos}$ exceeds the length of the number, it means all digits have been processed. If $\\textit{diff} = 0$, the current number is a balanced integer, return $1$; otherwise, return $0$.\n- Calculate the upper bound $\\textit{up}$ for the current digit. If constrained, it equals the current digit of the number; otherwise, it is $9$.\n- Iterate through all possible digits $i$ for the current position. For each digit $i$, recursively call $\\textit{dfs}(\\textit{pos} + 1, \\textit{diff} + i \\times (\\text{1 if pos \\% 2 == 0 else -1}), \\textit{lim} \\&\\& i == \\textit{up})$, and accumulate the results.\n- Return the accumulated result.\n\nWe first calculate the number of balanced integers $\\textit{a}$ in the range $[1, \\textit{low} - 1]$, then calculate the number of balanced integers $\\textit{b}$ in the range $[1, \\textit{high}]$, and finally return $\\textit{b} - \\textit{a}$.\n\nTo avoid redundant calculations, we use memoization to store previously computed states.\n\nThe time complexity is $O(\\log^2 M \\times D^2)$, and the space complexity is $O(\\log^2 M \\times D)$. Here, $M$ is the value of $\\textit{high}$, and $D = 10$." }, "is_english": true, "time_complexity": "O(\\log^2 M \\times D^2)", "space_complexity": "O(\\log^2 M \\times D)" }, { "problem_id": 3792, "explanations": { "1": "We can directly simulate the product of each block and accumulate it to the answer. Note that since the product can be very large, we need to take the modulo at each step of the calculation.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(1)" }, { "problem_id": 3793, "explanations": { "1": "We first group the prompts by `user_id` and calculate for each user the total number of prompts `prompt_count`, the average tokens `avg_tokens`, and the maximum tokens `max_tokens`. Then we filter users who meet the criteria, i.e., those who have submitted at least 3 prompts and have at least one prompt with tokens greater than their average token usage. Finally, we sort the results by `avg_tokens` in descending order and by `user_id` in ascending order." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3794, "explanations": { "1": "We reverse the first $k$ characters of the string according to the problem description, and then concatenate them with the remaining characters.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of the string." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3795, "explanations": { "1": "We use a hash table $\\textit{cnt}$ to record the occurrence count of each element in the current window, and a variable $\\textit{s}$ to record the sum of distinct elements in the current window. We use two pointers $l$ and $r$ to represent the left and right boundaries of the current window, both initially pointing to the beginning of the array. We initialize a variable $\\textit{ans}$ to record the minimum length of a window that satisfies the condition, with an initial value of $n + 1$, where $n$ is the length of the array.\n\nWe continuously move the right pointer $r$, adding new elements into the window and updating $\\textit{cnt}$ and $\\textit{s}$. When $\\textit{s}$ is greater than or equal to $k$, we try to move the left pointer $l$ to shrink the window, updating $\\textit{cnt}$ and $\\textit{s}$ accordingly, until $\\textit{s}$ is less than $k$. During this process, we record the minimum length of windows that satisfy the condition.\n\nFinally, if $\\textit{ans} \\gt n$, it means no valid window exists, and we return $-1$; otherwise we return $\\textit{ans}$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3796, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3797, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3798, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3799, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3800, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3801, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3802, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3803, "explanations": { "1": "We use a hash table $\\textit{st}$ to record the set of distinct characters that have appeared in the current prefix. We iterate through each character $c$ in the string $s$, add it to the set $\\textit{st}$, and then check if the length of the current prefix modulo $3$ equals the size of the set $\\textit{st}$. If they are equal, it means the current prefix is a residue prefix, and we increment the answer by $1$.\n\nAfter the iteration, we return the answer.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3804, "explanations": { "1": "We enumerate all starting indices $i$ of subarrays, then starting from index $i$, we enumerate the ending index $j$ of the subarray, calculate the sum $s$ of elements in the subarray $nums[i \\ldots j]$, and add all elements in the subarray to the hash table $\\textit{st}$. After each enumeration, we check if $s$ appears in the hash table $\\textit{st}$. If it does, it means the subarray $nums[i \\ldots j]$ is a centered subarray, and we increment the answer by $1$.\n\nThe time complexity is $O(n^2)$ and the space complexity is $O(n)$, where $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 3805, "explanations": { "1": "We can transform each string into a unified form. Specifically, we convert the first character of the string to `'z'`, and then transform the other characters in the string with the same offset. This way, all similar strings will be transformed into the same form. We use a hash table $\\textit{cnt}$ to record the number of occurrences of each transformed string.\n\nFinally, we iterate through the hash table, calculate the combination number $\\frac{v(v-1)}{2}$ for each string's occurrence count $v$, and add it to the answer.\n\nThe time complexity is $O(n \\times m)$ and the space complexity is $O(n \\times m)$, where $n$ is the length of the string array and $m$ is the length of the strings." }, "is_english": true, "time_complexity": "O(n \\times m)", "space_complexity": "O(n \\times m)" }, { "problem_id": 3806, "explanations": { "1": "We enumerate each bit from the highest bit, attempting to include that bit in the final bitwise AND result. For the currently attempted bitwise AND result $\\textit{target}$, we calculate the minimum number of operations required to increase each element in the array to at least $\\textit{target}$.\n\nSpecifically, we find the position $j - 1$ where $\\textit{target}$ has the first bit set to $1$ from high to low, while the current element has the corresponding bit set to $0$. Then we only need to increase the current element to the value of $\\textit{target}$ in the lower $j$ bits. The required number of operations is $(\\textit{target} \\& 2^{j} - 1) - (\\textit{nums}[i] \\& 2^{j} - 1)$. We store the required number of operations for all elements in the array $\\textit{cost}$, sort it, and take the sum of the first $m$ elements. If it does not exceed $k$, it means we can include this bit in the final bitwise AND result.\n\nThe time complexity is $O(n \\times \\log n \\times \\log M)$ and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$ and $M$ is the maximum value in the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n \\times \\log n \\times \\log M)", "space_complexity": "O(n)" }, { "problem_id": 3807, "explanations": { "1": "We observe that the higher the repair cost, the more edges become available, making it easier to satisfy the requirement of reaching node $n - 1$ from node $0$ using at most $k$ edges. Moreover, the minimum repair cost must be among the costs in $\\textit{edges}$. Therefore, we first sort $\\textit{edges}$ by repair cost, then use binary search to find the minimum repair cost that satisfies the requirement.\n\nWe perform binary search on the index of the repair cost, defining the left boundary as $l = 0$ and the right boundary as $r = |\\textit{edges}| - 1$. For the middle position $mid = \\lfloor (l + r) / 2 \\rfloor$, we add all edges with repair cost less than or equal to $\\textit{edges}[mid][2]$ to the graph, then use BFS to determine whether we can reach node $n - 1$ from node $0$ using at most $k$ edges. If possible, we update the right boundary to $r = mid$; otherwise, we update the left boundary to $l = mid + 1$. After the binary search completes, we need to perform one more BFS to check if $\\textit{edges}[l][2]$ satisfies the requirement. If it does, we return $\\textit{edges}[l][2]$; otherwise, we return $-1$.\n\nThe time complexity is $O((m + n) \\times \\log m)$ and the space complexity is $O(n)$, where $n$ and $m$ are the number of nodes and edges, respectively." }, "is_english": true, "time_complexity": "O((m + n) \\times \\log m)", "space_complexity": "O(n)" }, { "problem_id": 3808, "explanations": { "1": "We first count the number of each reaction for every user and record it in a temporary table $t$. Then, based on the temporary table $t$, we calculate the maximum reaction count and total reaction count for each user, compute the reaction ratio, and filter out the users who meet the conditions, recording them in a temporary table $s$. Finally, we join the temporary tables $s$ and $t$ to find the dominant reaction for each user and sort the results as required." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3809, "explanations": { "1": "We define a variable $\\textit{idx}$ to record the index of the current best tower, initially $\\textit{idx} = -1$. Then, we traverse each tower and calculate the Manhattan distance $\\textit{dist}$ between it and $\\textit{center}$:\n\n$$\n\\textit{dist} = |x_i - cx| + |y_i - cy|\n$$\n\nIf $\\textit{dist} > \\textit{radius}$, the tower is unreachable, so we skip it. Otherwise, we compare the quality factor $q$ of the current tower with that of the best tower:\n\n- If $\\textit{idx} = -1$, it means no reachable tower has been found yet, so we update $\\textit{idx}$ to the current tower's index.\n- If the current tower's quality factor $q_i$ is greater than the best tower's quality factor $q_{\\textit{idx}}$, we update $\\textit{idx}$ to the current tower's index.\n- If the current tower's quality factor $q_i$ is equal to the best tower's quality factor $q_{\\textit{idx}}$, we compare the coordinates of the two towers and choose the one with the smaller lexicographical order.\n\nAfter the traversal ends, if $\\textit{idx} = -1$, it means there are no reachable towers, so we return $[-1, -1]$. Otherwise, we return the coordinates of the best tower.\n\nThe time complexity is $O(n)$, where $n$ is the number of towers. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3810, "explanations": { "1": "According to the problem description, we only need to count the number of distinct $\\text{nums}[i]$ where $\\text{nums}[i] \\ne \\text{target}[i]$. Therefore, we can use a hash table to store these distinct $\\text{nums}[i]$ and finally return the size of the hash table.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3811, "explanations": { "1": "We define two hash tables $\\textit{cnt1}$ and $\\textit{cnt2}$, where $\\textit{cnt1}[x]$ represents the number of partition schemes where the bitwise XOR result is $x$ and the partition ends with $\\textit{target1}$, while $\\textit{cnt2}[x]$ represents the number of partition schemes where the bitwise XOR result is $x$ and the partition ends with $\\textit{target2}$. Initially, $\\textit{cnt2}[0] = 1$, representing an empty partition.\n\nWe use the variable $\\textit{pre}$ to record the bitwise XOR result of the current prefix, and the variable $\\textit{ans}$ to record the final answer. Then we traverse the array $\\textit{nums}$. For each element $x$, we update $\\textit{pre}$ and calculate:\n\n$$\na = \\textit{cnt2}[\\textit{pre} \\oplus \\textit{target1}]\n$$\n\n$$\nb = \\textit{cnt1}[\\textit{pre} \\oplus \\textit{target2}]\n$$\n\nThen we update the answer:\n\n$$\n\\textit{ans} = (a + b) \\mod (10^9 + 7)\n$$\n\nNext, we update the hash tables:\n\n$$\n\\textit{cnt1}[\\textit{pre}] = (\\textit{cnt1}[\\textit{pre}] + a) \\mod (10^9 + 7)\n$$\n\n$$\n\\textit{cnt2}[\\textit{pre}] = (\\textit{cnt2}[\\textit{pre}] + b) \\mod (10^9 + 7)\n$$\n\nFinally, we return $\\textit{ans}$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3812, "explanations": { "1": "We define an adjacency list $g$ to represent the tree, where $g[a]$ stores all adjacent nodes of node $a$ and the indices of the corresponding edges.\n\nWe design a function $\\text{dfs}(a, \\text{fa})$, which indicates whether the edge between node $a$ and $\\text{fa}$ needs to be toggled in the subtree rooted at node $a$ with parent $\\text{fa}$. The logic of the function $\\text{dfs}(a, \\text{fa})$ is as follows:\n\n1. Initialize a boolean variable $\\text{rev}$, indicating whether node $a$ needs to be toggled. The initial value is $\\text{start}[a] \\ne \\text{target}[a]$.\n2. Iterate through all adjacent nodes $b$ of node $a$ and the corresponding edge index $i$:\n - If $b \\ne \\text{fa}$, recursively call $\\text{dfs}(b, a)$.\n - If the recursive call returns true, it means the edge $[a, b]$ in the subtree needs to be toggled. We add the edge index $i$ to the answer list and toggle $\\text{rev}$.\n3. Return $\\text{rev}$.\n\nFinally, we call $\\text{dfs}(0, -1)$. If the return value is true, it means it is impossible to convert $\\text{start}$ to $\\text{target}$, so we return $[-1]$. Otherwise, we sort the answer list and return it.\n\nThe time complexity is $O(n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the tree." }, "is_english": true, "time_complexity": "O(n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3813, "explanations": { "1": "We iterate through the string to count the number of vowels and consonants, denoted as $v$ and $c$, respectively. Finally, we calculate the score based on the problem description.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3814, "explanations": { "1": "We first filter out all machines with costs less than the budget and sort them by cost in ascending order, recording them in the array $\\textit{arr}$, where $\\textit{arr}[i] = (\\textit{costs}[i], \\textit{capacity}[i])$. If $\\textit{arr}$ is empty, we cannot buy any machine, so we return $0$.\n\nOtherwise, we can obtain the machine with the maximum capacity in $\\textit{arr}$ and initialize the answer with this capacity.\n\nNext, we use a two-pointer approach to iterate through pairs of machines in $\\textit{arr}$, using an ordered set $\\textit{remain}$ to maintain the capacities of all currently available machines. Initially, $\\textit{remain}$ contains the capacities of all machines in $\\textit{arr}$.\n\nWe use pointers $i$ and $j$ pointing to the beginning and end of $\\textit{arr}$, respectively. For each $i$, we remove $\\textit{arr}[i]$ from $\\textit{remain}$, and then move pointer $j$ until $\\textit{arr}[i].\\textit{cost} + \\textit{arr}[j].\\textit{cost} < \\textit{budget}$. During this process, we remove the machines that do not satisfy the condition from $\\textit{remain}$. At this point, any machine in $\\textit{remain}$ can be bought together with $\\textit{arr}[i]$. We take the machine with the maximum capacity from $\\textit{remain}$, add its capacity to $\\textit{arr}[i]$'s capacity, and update the answer. Finally, we return the answer.\n\nThe time complexity is $O(n \\log n)$, and the space complexity is $O(n)$, where $n$ is the number of machines." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3815, "explanations": { "1": "We define two hash tables. `items` is used to store all bid information for each item, where `items[itemId]` stores an ordered set. Each element in the set is a tuple `(bidAmount, userId)`, representing a user's bid amount for that item. Since we need to quickly retrieve the user with the highest bid, this ordered set needs to be sorted by bid amount in ascending order. If bid amounts are identical, they are sorted by user ID in ascending order. The other hash table `users` is used to store the bid information of each user for each item, where `users[userId][itemId]` stores the user's bid amount for that item.\n\nFor the `addBid(userId, itemId, bidAmount)` operation, we first check if the user has already placed a bid on the item. If they have, we call the `removeBid(userId, itemId)` method to remove the original bid; then we add the new bid information to `users` and `items`.\n\nFor the `updateBid(userId, itemId, newAmount)` operation, we first retrieve the user's original bid amount for the item from `users`, then remove the corresponding tuple `(oldAmount, userId)` from `items`, add the new bid information to `items`, and update the bid amount in `users`.\n\nFor the `removeBid(userId, itemId)` operation, we first retrieve the user's original bid amount for the item from `users`, then remove the corresponding tuple `(oldAmount, userId)` from `items`, and finally delete the user's bid information for that item from `users`.\n\nFor the `getHighestBidder(itemId)` operation, we first check if `items[itemId]` is empty. If it is, we return -1; otherwise, we return the user ID of the last element in the ordered set, which corresponds to the highest bidder.\n\nIn terms of time complexity, each operation takes $O(\\log m)$ time, where $m$ is the number of bids for the current item. The space complexity is $O(n)$, where $n$ is the total number of bids." }, "is_english": true, "time_complexity": null, "space_complexity": "O(n)" }, { "problem_id": 3816, "explanations": { "1": "We can use a stack $\\textit{stk}$ to store the characters of the result string, and a hash table $\\textit{cnt}$ to record the number of occurrences of each character in string $s$.\n\nFirst, we initialize $\\textit{cnt}$ to count the occurrences of each character in string $s$. Then, we iterate through each character $c$ in string $s$:\n\n- If the stack is not empty, the top character of the stack is greater than $c$, and the top character will appear again in string $s$, we pop the top character and decrement its count in $\\textit{cnt}$.\n- Push character $c$ into the stack.\n\nFinally, if there are duplicate characters in the stack, we continue to pop the top character until the count of the top character in $\\textit{cnt}$ is 1.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3817, "explanations": { "1": "We observe that the maximum length of string $s$ is $10^5$, and the length of the decimal representation of index $i$ is at most $6$ (since the decimal representation of $10^5$ is $100000$, which has a length of $6$). Therefore, we only need to check for each index $i$ whether the substring corresponding to its decimal representation is equal to it.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$, ignoring the space required for the answer." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3818, "explanations": { "1": "We can traverse the array backwards from the end to find the first position $i$ that does not satisfy the strictly increasing condition, i.e., $nums[i-1] \\geq nums[i]$. At this point, the minimum length of the prefix to remove is $i$.\n\nIf the entire array is strictly increasing, we do not need to remove any prefix, so we return $0$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3819, "explanations": { "1": "We first extract all non-negative elements from the array and store them in a new array $t$.\n\nThen, we create an array $d$ of the same size as $t$ to store the rotated non-negative elements. For each element $t[i]$ in $t$, we place it in $d$ at position $((i - k) \\bmod m + m) \\bmod m$, where $m$ is the number of non-negative elements.\n\nNext, we iterate through the original array $\\textit{nums}$. For each position containing a non-negative element, we replace it with the element from the corresponding position in $d$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(m)$, where $m$ is the number of non-negative elements." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(m)" }, { "problem_id": 3820, "explanations": { "1": "We first construct an adjacency list $g$ based on the edges given in the problem, where $g[u]$ stores all nodes adjacent to node $u$.\n\nNext, we define a function $\\text{bfs}(i)$ to calculate the distances from node $i$ to all other nodes. We use a queue to implement Breadth-First Search (BFS) and maintain a distance array $\\text{dist}$, where $\\text{dist}[j]$ represents the distance from node $i$ to node $j$. Initially, $\\text{dist}[i] = 0$, and the distances to all other nodes are set to infinity. During the BFS process, we continuously update the distance array until all reachable nodes have been traversed.\n\nWe call $\\text{bfs}(x)$, $\\text{bfs}(y)$, and $\\text{bfs}(z)$ to calculate the distances from nodes $x$, $y$, and $z$ to all other nodes, obtaining three distance arrays $d_1$, $d_2$, and $d_3$ respectively.\n\nFinally, we iterate through all nodes $u$. For each node, we retrieve its distances to $x$, $y$, and $z$ as $a = d_1[u]$, $b = d_2[u]$, and $c = d_3[u]$. We sort these three distances and check if they satisfy the Pythagorean theorem condition: $a^2 + b^2 = c^2$. If the condition is met, we increment the answer count.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of nodes in the tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3821, "explanations": { "1": "We need to find the $n$-th smallest positive integer that contains exactly $k$ ones in its binary representation. We can determine each bit from the most significant to the least significant, deciding whether it is $0$ or $1$.\n\nSuppose we are currently processing the $i$-th bit (from $49$ down to $0$). If we set this bit to $0$, then the remaining $k$ ones need to be chosen from the lower $i$ bits, and the number of possible combinations is $C(i, k)$. If $n$ is greater than $C(i, k)$, it implies that the $i$-th bit of the $n$-th number must be $1$. In this case, we set this bit to $1$, subtract $C(i, k)$ from $n$, and decrement $k$ by $1$ (since we have already used one $1$). Otherwise, we set this bit to $0$.\n\nWe repeat the above process until all bits are processed or $k$ becomes $0$.\n\nThe time complexity is $O(\\log^2 M)$, and the space complexity is $O(\\log^2 M)$, where $M$ is the upper bound of the answer, $2^{50}$." }, "is_english": true, "time_complexity": "O(\\log^2 M)", "space_complexity": "O(\\log^2 M)" }, { "problem_id": 3822, "explanations": { "1": "We use a hash table $\\textit{orders}$ to store the type and price information of each order, where the key is the order ID and the value is a tuple $(\\textit{orderType}, \\textit{price})$. Additionally, we use another hash table $\\textit{t}$ to store the list of order IDs corresponding to each $(\\textit{orderType}, \\textit{price})$, where the key is a tuple $(\\textit{orderType}, \\textit{price})$ and the value is the list of order IDs.\n\nWhen calling $\\texttt{addOrder}$, we add the order information to $\\textit{orders}$ and append the order ID to the corresponding list in $\\textit{t}$.\n\nWhen calling $\\texttt{modifyOrder}$, we first retrieve the order type and old price from $\\textit{orders}$, then update the order's price information. Next, we remove the order ID from the corresponding list in $\\textit{t}$ and add it to the list corresponding to the new price.\n\nWhen calling $\\texttt{cancelOrder}$, we retrieve the order type and price information from $\\textit{orders}$, then remove the order ID from the corresponding list in $\\textit{t}$ and delete the order from $\\textit{orders}$.\n\nWhen calling $\\texttt{getOrdersAtPrice}$, we directly return the list of order IDs corresponding to the query in $\\textit{t}$.\n\nIn the above operations, the time complexity for adding and retrieving the order ID list is $O(1)$, while the time complexity for removing an order ID from the list is $O(n)$, where $n$ is the length of the corresponding list. Since the total number of orders in the problem does not exceed $2000$, this method is efficient enough in practice. The space complexity is $O(m)$, where $m$ is the total number of orders." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(m)" }, { "problem_id": 3823, "explanations": { "1": "We first store the letters and special characters from string $s$ into two separate lists $a$ and $b$ respectively. Then we traverse the string $s$. If the current position is a letter, we pop the last letter from list $a$ and place it back at that position; otherwise, we pop the last special character from list $b$ and place it back at that position.\n\nAfter the traversal is complete, we obtain the result string.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3824, "explanations": { "1": "We notice that as $k$ increases, it becomes easier to satisfy the condition. This exhibits monotonicity, so we can use binary search to find the minimum $k$.\n\nWe define the left boundary of the binary search as $l = 1$ and the right boundary as $r = 10^5$. In each binary search iteration, we calculate the middle value $mid = \\lfloor (l + r) / 2 \\rfloor$ and determine whether the condition $\\text{nonPositive}(\\text{nums}, k) \\leq k^2$ is satisfied when $k = mid$. If the condition is satisfied, we update the right boundary to $r = mid$; otherwise, we update the left boundary to $l = mid + 1$. When the binary search ends, the left boundary $l$ is the minimum $k$ we are looking for.\n\nThe time complexity is $O(n \\log M)$, where $n$ and $M$ are the length of the array $\\textit{nums}$ and the maximum range respectively. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n \\log M)", "space_complexity": "O(1)" }, { "problem_id": 3825, "explanations": { "1": "A non-zero bitwise AND result means that all numbers in the subsequence have a $1$ at a certain bit position. We can enumerate that bit position, then find the longest strictly increasing subsequence among all numbers that have a $1$ at that bit position, and take the maximum value across all enumerations as the answer.\n\nThe time complexity is $O(\\log M \\times n \\times \\log n)$, and the space complexity is $O(n)$. Here, $n$ and $M$ are the length of the array and the maximum value in the array, respectively." }, "is_english": true, "time_complexity": "O(\\log M \\times n \\times \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3826, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3827, "explanations": { "1": "According to the problem description, a Monobit integer is either $0$, or its binary representation consists of all $1$s.\n\nTherefore, we first include $0$ in the answer, then starting from $1$, we sequentially generate integers whose binary representations consist of all $1$s, until the integer exceeds $n$.\n\nThe time complexity is $O(\\log n)$ and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 3828, "explanations": { "1": "Since Alice goes first, Alice can choose to remove all elements except the first and last elements, so the answer is at least $\\max(nums[0], nums[n - 1])$.\n\nFor the cases of elements at indices $1, 2, ..., n-2$ (the middle elements), even if Alice wants to keep any of these middle elements, Bob can choose to remove it, so the answer is at most $\\max(nums[0], nums[n - 1])$.\n\nTherefore, the answer is exactly $\\max(nums[0], nums[n - 1])$.\n\nThe time complexity is $O(1)$ and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 3829, "explanations": { "1": "We use two sorted sets $\\textit{riders}$ and $\\textit{drivers}$ to store waiting riders and available drivers respectively. Each element is a tuple $(t, \\textit{id})$, representing the ID of the rider/driver and their timestamp $t$ when they joined the system. The timestamp $t$ is used to distinguish the order of arrival. Initially, $t = 0$, and each time a rider or driver is added, $t$ is incremented by $1$.\n\nAdditionally, we use a hash table $\\textit{d}$ to store the mapping between each rider's ID and their timestamp, which facilitates lookup when canceling a rider's request.\n\nSpecifically:\n\n- When adding a rider, we add $(t, \\textit{riderId})$ to $\\textit{riders}$, set $\\textit{d}[\\textit{riderId}] = t$, and then increment $t$ by $1$.\n- When adding a driver, we add $(t, \\textit{driverId})$ to $\\textit{drivers}$ and then increment $t$ by $1$.\n- When matching a driver with a rider, if either $\\textit{riders}$ or $\\textit{drivers}$ is empty, we return $[-1, -1]$. Otherwise, we remove the elements with the smallest timestamps from both $\\textit{riders}$ and $\\textit{drivers}$, namely $(t_r, \\textit{riderId})$ and $(t_d, \\textit{driverId})$, and return $[\\textit{driverId}, \\textit{riderId}]$.\n- When canceling a rider's request, we look up the rider's timestamp $t$ through $\\textit{d}$, and then remove $(t, \\textit{riderId})$ from $\\textit{riders}$.\n\nThe time complexity is $O(\\log n)$ per operation, where $n$ is the current number of riders or drivers. The space complexity is $O(n)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(n)" }, { "problem_id": 3830, "explanations": { "1": "We use two arrays $l_1$ and $l_2$ to represent the length of the longest alternating subarray ending at position $i$ with the last comparison being \"<\" and \">\", respectively. Similarly, we use $r_1$ and $r_2$ to represent the length of the longest alternating subarray starting at position $i$ with the first comparison being \"<\" and \">\", respectively.\n\nWe can compute $l_1$ and $l_2$ through a single left-to-right traversal, and then compute $r_1$ and $r_2$ through a single right-to-left traversal.\n\nNext, we initialize the answer as $\\max(\\max(l_1), \\max(l_2))$, which represents the length of the longest alternating subarray without removing any elements.\n\nThen, we enumerate the position $i$ of the element to be removed. If after removing position $i$, positions $i-1$ and $i+1$ can still form an alternating relationship, we can add $l_1[i-1]$ and $r_1[i+1]$ (or $l_2[i-1]$ and $r_2[i+1]$) together to update the answer.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3831, "explanations": { "1": "We notice that the problem requires us to find the median of node values at a certain level in a binary search tree. Since the definition of median is to sort the node values and take the middle value, and the in-order traversal of a binary search tree is inherently sorted, we can collect the node values at the specified level through in-order traversal.\n\nWe define a helper function $\\text{dfs}(root, i)$, where $root$ is the current node and $i$ is the level of the current node. In the function, if the current node is empty, we return directly. Otherwise, we recursively traverse the left subtree, check if the level of the current node equals the target level, and if so, add the value of the current node to the result list, and finally recursively traverse the right subtree.\n\nWe initialize an empty list $\\text{nums}$ to store the node values at the specified level, and call $\\text{dfs}(root, 0)$ to start the traversal. Finally, we check if $\\text{nums}$ is empty, and if so, return -1, otherwise return the value at the middle position of $\\text{nums}$.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the number of nodes in the tree." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3832, "explanations": { "1": "We first need to filter user dates with only a single action per day, then identify consecutive intervals among these dates, and finally aggregate these intervals to calculate the streak length and filter records that meet the criteria." }, "is_english": true, "time_complexity": null, "space_complexity": null }, { "problem_id": 3833, "explanations": { "1": "We can traverse the array from back to front, maintaining a suffix sum $\\text{suf}$, which represents the sum of all elements to the right of the current element. For each element, we check if it is greater than the average value of the elements to its right $\\frac{\\text{suf}}{n - i - 1}$. If so, we increment the answer by one. Finally, we return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\text{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3834, "explanations": { "1": "We can use a stack to simulate the process of merging adjacent equal elements.\n\nDefine a stack $\\textit{stk}$ to store the current processed array elements. Traverse each element $x$ of the input array $\\textit{nums}$ and push it onto the stack. Then check if the top two elements of the stack are equal. If they are equal, pop them and push their sum back onto the stack. Repeat this process until the top two elements of the stack are no longer equal. Finally, the elements in the stack are the final merged array.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(n)$, which is used to store the elements in the stack." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3835, "explanations": { "1": "We notice that if a subarray $\\text{nums}[l..r]$ has a cost less than or equal to $k$, then for any $l' \\geq l$ and $r' \\leq r$, the subarray $\\text{nums}[l'..r']$ also has a cost less than or equal to $k$. Therefore, we can enumerate the right endpoint $r$, use two pointers to maintain the minimum left endpoint $l$ that satisfies the condition, then the number of subarrays ending at $r$ that satisfy the condition is $r - l + 1$, which we accumulate to the answer.\n\nWe can use two deques to maintain the maximum and minimum values in the current window respectively.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of the array $\\text{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3836, "explanations": { "1": "We denote the lengths of arrays $\\textit{nums1}$ and $\\textit{nums2}$ as $n$ and $m$ respectively, and denote $k$ in the problem as $K$.\n\nWe define a three-dimensional array $f$, where $f[i][j][k]$ represents the maximum score of selecting exactly $k$ index pairs from the first $i$ elements of $\\textit{nums1}$ and the first $j$ elements of $\\textit{nums2}$. Initially, $f[0][0][0] = 0$, and all other values of $f[i][j][k]$ are negative infinity.\n\nWe can calculate $f[i][j][k]$ through the following state transition equation:\n\n$$\nf[i][j][k] = \\max\\begin{cases}\nf[i-1][j][k], \\\\\nf[i][j-1][k], \\\\\nf[i-1][j-1][k-1] + nums1[i-1] * nums2[j-1]\n\\end{cases}\n$$\n\nThe first case represents not selecting the $i$-th element of $\\textit{nums1}$, the second case represents not selecting the $j$-th element of $\\textit{nums2}$, and the third case represents selecting the $i$-th element of $\\textit{nums1}$ and the $j$-th element of $\\textit{nums2}$ as a pair of indices.\n\nFinally, we need to return $f[n][m][K]$.\n\nThe time complexity is $O(m \\times n \\times K)$ and the space complexity is $O(m \\times n \\times K)$, where $n$ and $m$ are the lengths of arrays $\\textit{nums1}$ and $\\textit{nums2}$ respectively, and $K$ is $k$ in the problem." }, "is_english": true, "time_complexity": "O(m \\times n \\times K)", "space_complexity": "O(m \\times n \\times K)" }, { "problem_id": 3837, "explanations": { "1": "We can use a hash table $\\textit{cnt}$ to record the number of occurrences of each number within the index range $(i + k, n - 1]$. We enumerate index $i$ in reverse order starting from index $n - k - 2$. During the enumeration, we first add the number at index $i + k + 1$ to the hash table $\\textit{cnt}$, then assign the value of $\\textit{cnt}[nums[i]]$ to the answer array $\\textit{ans}[i]$.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3838, "explanations": { "1": "We iterate through each word $w$ in $\\textit{words}$, calculate its weight $s$, which is the sum of the weights of all characters in the word. Then we calculate $s$ modulo 26, map the result to a lowercase English letter, and finally concatenate all the mapped characters and return.\n\nThe time complexity is $O(L)$, where $L$ is the sum of the lengths of all words in $\\textit{words}$. The space complexity is $O(W)$, where $W$ is the length of $\\textit{words}$." }, "is_english": true, "time_complexity": "O(L)", "space_complexity": "O(W)" }, { "problem_id": 3839, "explanations": { "1": "We use a hash table $\\textit{cnt}$ to count the number of occurrences of the prefix composed of the first $k$ characters of each string with length greater than or equal to $k$. Finally, we count the number of keys in $\\textit{cnt}$ with values greater than $1$, which is the number of connected groups.\n\nThe time complexity is $O(n \\times k)$, and the space complexity is $O(n)$, where $n$ is the length of $\\textit{words}$." }, "is_english": true, "time_complexity": "O(n \\times k)", "space_complexity": "O(n)" }, { "problem_id": 3840, "explanations": { "1": "We define two variables $f$ and $g$, where $f$ represents the maximum amount when the current house is not robbed, and $g$ represents the maximum amount when the current house is robbed. Initially, $f = 0$ and $g = nums[0]$. The answer is $\\max(f, g)$.\n\nNext, we traverse starting from the second house:\n\n- If the current house has the same color as the previous house, then $f$ is updated to $\\max(f, g)$, and $g$ is updated to $f + nums[i]$.\n- If the current house has a different color from the previous house, then $f$ is updated to $\\max(f, g)$, and $g$ is updated to $\\max(f, g) + nums[i]$.\n\nFinally, return $\\max(f, g)$.\n\nThe time complexity is $O(n)$, where $n$ is the number of houses. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3841, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3842, "explanations": { "1": "We use an array $\\textit{st}$ of length $101$ to record the state of each light bulb. Initially, all elements are $0$, indicating that all light bulbs are in the off state. For each element $\\textit{bulbs}[i]$ in the array $\\textit{bulbs}$, we toggle the value of $\\textit{st}[\\textit{bulbs}[i]]$ (i.e., $0$ becomes $1$, and $1$ becomes $0$). Finally, we traverse the $\\textit{st}$ array, add the indices with a value of $1$ to the result list, and return the result.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{bulbs}$. The space complexity is $O(M)$, where $M$ is the maximum bulb number." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(M)" }, { "problem_id": 3843, "explanations": { "1": "We use a hash table $\\textit{cnt}$ to count the occurrences of each element, and then use another hash table $\\textit{freq}$ to count the frequency of each occurrence count. Finally, we traverse the array $\\textit{nums}$ again. For each element $x$, if the value of $\\textit{freq}[\\textit{cnt}[x]]$ is 1, it means the occurrence frequency of $x$ is unique, and we return $x$. If no such element is found after traversing, return -1.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3844, "explanations": { "1": "Let's denote the length of string $s$ as $n$.\n\nWe define a function $f(l, r)$, which represents calculating the length of the longest almost-palindromic substring that can be obtained by starting from $l$ and $r$, expanding towards both sides of the string, and deleting one character.\n\nIn the function $f(l, r)$, we first expand towards both sides until the conditions $l \\geq 0$, $r \\lt n$, and $s[l] = s[r]$ are no longer satisfied. At this point, we can choose to skip $l$ or skip $r$. If we skip $l$, then we continue to expand from $(l - 1, r)$ towards both sides; if we skip $r$, then we continue to expand from $(l, r + 1)$ towards both sides. We calculate the length of the longest almost-palindromic substring for both cases and take the maximum value. Note that the length of the longest almost-palindromic substring cannot exceed $n$.\n\nFinally, we enumerate the center position $i$ of the palindrome, and calculate the length of the longest almost-palindromic substring obtained by starting from $(i, i)$ and $(i, i + 1)$, expanding towards both sides, and deleting one character, taking the maximum value among them.\n\nThe time complexity is $O(n^2)$, where $n$ is the length of string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(1)" }, { "problem_id": 3845, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3846, "explanations": { "1": "We define a hash table $\\textit{pos}$ to store the position of each character on the keyboard. For each character in string $s$, we calculate the distance from the previous character to the current character and accumulate it to the answer. Finally, we return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of string $s$. The space complexity is $O(|\\Sigma|)$, where $\\Sigma$ is the character set, which here is 26 lowercase English letters." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 3847, "explanations": { "1": "We use a variable $k$ to represent the role of the current player. Initially $k = 1$, when $k = 1$ it means the first player is the active player, and when $k = -1$ it means the second player is the active player. For each game, we update the value of $k$ according to the problem description, and add the score of the current game multiplied by $k$ to the answer. Finally, we return the answer.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3848, "explanations": { "1": "According to the problem description, no matter how the digits of number $n$ are rearranged, the sum of factorials of the digitorial number remains unchanged. Therefore, we only need to calculate the sum of factorials of each digit of number $n$, and check whether the permutation of digits of this sum equals the permutation of digits of $n$.\n\nThe time complexity is $O(\\log n)$, where $n$ is the integer given in the problem. The space complexity is $O(d)$, where $d = 10$ is the length of the factorial preprocessing array." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(d)" }, { "problem_id": 3849, "explanations": { "1": "We use an array $\\textit{cnt}$ of length $2$ to count the number of character '0' and character '1' in string $t$.\n\nThen we iterate through string $s$. For each character $s[i]$, we want to find a character in string $t$ that is different from $s[i]$ to perform the XOR operation, in order to get a larger result. If we find such a character, we set the $i$-th bit of the answer to '1' and decrement the count of that character by one; otherwise, we can only use a character that is the same as $s[i]$ for the XOR operation, the $i$-th bit of the answer remains '0', and we decrement the count of that character by one. Finally, we return the answer.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3850, "explanations": { "1": "We define a function $\\text{dfs}(i, p, q)$ that represents the number of different choice sequences when processing at index $i$ with the current rational value being $\\frac{p}{q}$. Initially, $\\text{dfs}(0, 1, 1)$ represents starting from the initial value of $1$.\n\nFor each index $i$, we have three choices:\n\n1. Keep it unchanged, i.e., $\\text{dfs}(i + 1, p, q)$.\n2. Multiply by $nums[i]$, i.e., $\\text{dfs}(i + 1, p \\cdot nums[i], q)$.\n3. Divide by $nums[i]$, i.e., $\\text{dfs}(i + 1, p, q \\cdot nums[i])$.\n\nTo avoid excessively large numbers, we simplify the numerator and denominator after each multiplication or division. Finally, when $i$ equals $n$, if $\\frac{p}{q}$ exactly equals $k$, we return $1$; otherwise, we return $0$.\n\nThe time complexity is $O(n^4 + \\log k)$, and the space complexity is $O(n^4)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n^4 + \\log k)", "space_complexity": "O(n^4)" }, { "problem_id": 3851, "explanations": { "1": "We can group the requests by user and store them in a hash table $g$, where $g[u]$ is the list of request times for user $u$. For each user, we need to remove some requests from the request time list so that within any interval of length $window$, the number of remaining requests does not exceed $k$.\n\nWe initialize the answer $\\textit{ans}$ to the total number of requests.\n\nFor the request time list $g[u]$ of user $u$, we first sort it. Then, we use a deque $kept$ to maintain the currently kept request times. We iterate through each request time $t$ in the request time list. For each request time, we need to remove all request times from $kept$ whose difference from $t$ is greater than $window$. Then, if the number of remaining requests in $kept$ is less than $k$, we add $t$ to $kept$; otherwise, we need to remove $t$ and decrement the answer by 1.\n\nFinally, return the answer $\\textit{ans}$.\n\nThe time complexity is $O(n \\log n)$ and the space complexity is $O(n)$, where $n$ is the number of requests. Each request is visited once, sorting takes $O(n \\log n)$ time, and the operations on the hash table and deque take $O(n)$ time." }, "is_english": true, "time_complexity": "O(n \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3852, "explanations": { "1": "We use a hash table $\\textit{cnt}$ to count the frequency of each value in the array. Then we find the smallest value $x$, and the smallest value $y$ that is greater than $x$ and has a different frequency from $x$. If no such $y$ exists, return $[-1, -1]$.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3853, "explanations": { "1": "We use a hash table $\\textit{last}$ to record the last occurrence position of each character. We iterate over each character in the string. If the current character has appeared before and the difference between the current index and its last occurrence index is at most $k$, we skip the character; otherwise, we add the character to the answer and update its position in the hash table.\n\nThe time complexity is $O(n)$, and the space complexity is $O(|\\Sigma|)$, where $n$ is the length of the string, and $|\\Sigma|$ is the size of the character set. In this problem, the character set consists of lowercase English letters, so $|\\Sigma|$ is a constant." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(|\\Sigma|)" }, { "problem_id": 3854, "explanations": { "1": "We can try to transform the array into two different parity-alternating forms: one where even numbers are at even indices and odd numbers are at odd indices, and another where odd numbers are at even indices and even numbers are at odd indices.\n\nFor each form, we calculate the number of operations needed and the maximum and minimum values of the resulting array. Finally, we choose the plan with fewer operations; if the operation counts are equal, we choose the plan with the smaller difference between the maximum and minimum values.\n\nWe define a function $f(k)$, where $k$ represents the desired parity of the numbers placed at even indices (where $k=0$ means even and $k=1$ means odd). The function $f(k)$ computes the number of operations needed to transform the array into the corresponding parity-alternating form, as well as the maximum and minimum values of the resulting array.\n\nIn the function $f(k)$, we iterate over each element in the array. If the parity of the current element does not match the expected parity, we perform one operation to adjust it. To minimize the difference between the maximum and minimum values, we adjust the current element to the nearest number, which is either the current element plus $1$ or minus $1$, depending on whether the current element equals the minimum or maximum value in the array. If the current element equals the minimum value, we increase it by $1$; if it equals the maximum value, we decrease it by $1$; otherwise, we can choose to either increase or decrease by $1$. We then update the current maximum and minimum values. Finally, the function $f(k)$ returns the operation count and the difference between the maximum and minimum values of the resulting array.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$, as we only use a constant amount of extra space." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3855, "explanations": { "1": "We enumerate each digit $x$ from the lowest position to the highest. Suppose the current position is the $i$-th digit (0-indexed), which contributes $x \\cdot 10^i$ to the number. The remaining $k - 1$ digits each have $r - l + 1$ choices, so the contribution of the current position is $x \\cdot 10^i \\cdot (r - l + 1)^{k - 1}$. Since $x$ ranges over $[l, r]$, the sum of all values of $x$ is $\\frac{(l + r) \\cdot (r - l + 1)}{2}$. Therefore, the total sum of all such numbers is:\n\n$$\n\\begin{aligned}\n&\\sum_{i = 0}^{k - 1} \\frac{(l + r) \\cdot (r - l + 1)}{2} \\cdot (r - l + 1)^{k - 1} \\cdot 10^i \\\\\n= &\\frac{(l + r) \\cdot (r - l + 1)}{2} \\cdot (r - l + 1)^{k - 1} \\cdot \\frac{10^k - 1}{9}\n\\end{aligned}\n$$\n\nSince $k$ can be up to $10^9$, we use fast power (binary exponentiation) to compute $(r - l + 1)^{k - 1}$ and $10^k$. Division by $9$ is handled using the modular inverse of $9$ via Fermat's little theorem.\n\nThe time complexity is $O(\\log k)$ and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log k)", "space_complexity": "O(1)" }, { "problem_id": 3856, "explanations": { "1": "We traverse the string from the end in reverse order until we encounter the first non-vowel character. Then we return the substring from the beginning of the string up to that position.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3857, "explanations": { "1": "To minimize the total cost, we first split $n$ into $1$ and $n-1$, with a cost of $1 \\cdot (n-1) = n-1$. Next, we split $n-1$ into $1$ and $n-2$, with a cost of $1 \\cdot (n-2) = n-2$.\n\nWe continue this process until we split $2$ into $1$ and $1$, with a cost of $1 \\cdot 1 = 1$. Therefore, the total cost is $(n-1) + (n-2) + \\ldots + 2 + 1 = \\frac{n(n-1)}{2}$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 3858, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3859, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3860, "explanations": { "1": "We can use a hash set $\\textit{st}$ to store the normalized result of each email address. For each email address, we normalize it according to the problem requirements:\n\n- Split the email address into a local name and a domain name.\n- For the local name, remove all dots `.`, and if a plus sign `+` exists, remove the plus sign and everything after it. Then convert the local name to lowercase.\n- For the domain name, convert it to lowercase.\n- Concatenate the normalized local name and domain name to obtain the normalized email address, and add it to the hash set $\\textit{st}$.\n\nFinally, the number of elements in the hash set $\\textit{st}$ is the number of unique email groups.\n\nThe time complexity is $O(n \\cdot m)$, where $n$ and $m$ are the number of email addresses and the average length of each email address, respectively. The space complexity is $O(n \\cdot m)$, in the worst case where all email addresses are distinct." }, "is_english": true, "time_complexity": "O(n \\cdot m)", "space_complexity": "O(n \\cdot m)" }, { "problem_id": 3861, "explanations": { "1": "We initialize a variable $\\textit{ans}$ to represent the index of the box with the smallest capacity that can hold the item, with an initial value of $-1$. We iterate over the array $\\textit{capacity}$, and for each box, if its capacity is greater than or equal to $\\textit{itemSize}$, it can hold the item. At this point, we check whether it is the smallest-capacity box found so far; if so, we update $\\textit{ans}$. Finally, we return $\\textit{ans}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{capacity}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3862, "explanations": { "1": "We first compute the total sum $s$ of all elements in the array. Then we enumerate each index $i$ from right to left, maintaining a variable $p$ to record the product of all elements to the right of index $i$. When we reach index $i$, we first subtract $nums[i]$ from $s$, then check whether $s$ equals $p$; if so, we return index $i$. Next, we multiply $p$ by $nums[i]$. If $p$ is greater than or equal to $s$, the product will only keep growing and no balanced index can be found afterwards, so we can terminate the enumeration early.\n\nIf no balanced index is found after the enumeration, we return -1.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3863, "explanations": { "1": "We first check whether the string is already sorted in ascending order; if so, return 0.\n\nOtherwise, if the string has length 2, since we cannot choose the entire string to sort, it is impossible to sort the string, so we return -1.\n\nNext, we find the minimum character $mn$ and the maximum character $mx$ in the string. If the first character of the string equals $mn$, or the last character equals $mx$, then one operation on the remaining substring is sufficient to sort the entire string, so we return 1.\n\nOtherwise, if some character in the middle of the string equals $mn$ or $mx$, we need one operation to move that character to the beginning or the end of the string, and then one more operation to sort the rest, so we return 2.\n\nFinally, if none of the above cases apply, we need one operation on the substring containing both $mn$ and $mx$, followed by one more operation on the remaining substring, so we return 3.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3864, "explanations": { "1": "We define a function $\\text{dfs}(l, r)$ that represents the minimum cost for the interval $[l, r)$ of string $s$. We can use the prefix sum array $\\text{pre}$ to calculate the number of sensitive elements $x$ in the interval $[l, r)$, thereby computing the cost without splitting.\n\nThe calculation process of function $\\text{dfs}(l, r)$ is as follows:\n\n1. Calculate the number of sensitive elements $x$ in the interval $[l, r)$.\n2. Calculate the cost without splitting: if $x > 0$, the cost is $(r - l) \\cdot x \\cdot \\text{encCost}$; if $x = 0$, the cost is $\\text{flatCost}$.\n3. If the interval length is even, we can try to split it into two consecutive segments of equal length, and calculate the cost after splitting as $\\text{dfs}(l, m) + \\text{dfs}(m, r)$, where $m = \\frac{l + r}{2}$. Finally, return the smaller of the two values.\n\nThe answer is $\\text{dfs}(0, n)$, where $n$ is the length of string $s$.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of string $s$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3865, "explanations": { "1": "Since we need to partition the array into $k$ subarrays of equal length, the length of each subarray is $m = \\frac{n}{k}$. We can use a loop to traverse the array with a step size of $m$, and in each iteration, reverse the current subarray.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$, as we only use a constant amount of extra space." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3866, "explanations": { "1": "We can use a hash table or array $\\textit{cnt}$ to count the number of occurrences of each integer in the array. Then we traverse the array again to find and return the first even number that satisfies the condition. If no such even number exists, we return -1.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(M)$, where $M$ is the range of integers in the array (100 in this problem)." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(M)" }, { "problem_id": 3867, "explanations": { "1": "We simulate according to the problem description.\n\nWe create an array $\\textit{prefixGcd}$ to store the value for each index $i$. We also maintain a variable $mx$ to track the current maximum value. For each element $nums[i]$, we update $mx$ and compute the value of $\\textit{prefixGcd}[i]$. Then we sort $\\textit{prefixGcd}$ and calculate the sum of GCDs of the formed pairs.\n\nThe time complexity is $O(n \\log M + n \\log n)$, and the space complexity is $O(n)$, where $n$ is the length of the array and $M$ is the maximum value in the array." }, "is_english": true, "time_complexity": "O(n \\log M + n \\log n)", "space_complexity": "O(n)" }, { "problem_id": 3868, "explanations": { "1": "We can use two hash tables $\\textit{cnt1}$ and $\\textit{cnt2}$ to count the occurrences of each integer in the two arrays. During the counting process, we can directly cancel out the occurrences of integers that appear in both arrays. Finally, we check whether the occurrence count of every integer in both hash tables is even. If any integer has an odd count, we return -1. Otherwise, we compute the sum of half the occurrence counts of all integers in $\\textit{cnt1}$, which gives the minimum cost.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the arrays." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3869, "explanations": { "1": "We first define a function $\\text{check}(s)$ to determine whether an integer $s$ is a good number. For $s < 100$, we only need to check whether $s$ is a multiple of 11; if so, $s$ is not a good number. For $s \\geq 100$, we need to check whether the digits of $s$ form a strictly monotonic sequence, i.e., strictly increasing or strictly decreasing. Since the range of digit sums is small, when the digit sum exceeds $100$, we only need to check the relationship between the tens digit and the units digit of the digit sum.\n\nNext, we use digit DP to count the number of fancy numbers in the interval $[l, r]$. We define a recursive function $\\text{dfs}(pos, s, prev, st, lim)$, where:\n\n- Integer $pos$ represents the current digit position being processed, from high to low.\n- Integer $s$ represents the current digit sum.\n- Integer $prev$ represents the value of the previous digit.\n- Integer $st$ represents the state of the current digit sequence, where state $0$ means there is at most one digit so far, state $1$ means strictly increasing, state $2$ means strictly decreasing, and state $3$ means not strictly monotonic.\n- Boolean $lim$ indicates whether the current digit is constrained by the upper bound.\n\nIn the recursive function, if $pos$ exceeds the length of the number, we have finished processing a number. If the state $st$ is not equal to $3$, the number is a good number and we return $1$; otherwise, we call $\\text{check}(s)$ to determine whether the digit sum is a good number, returning $1$ if it is, and $0$ otherwise.\n\nDuring the recursion, we enumerate the range of the current digit: if $lim$ is true, the range is $[0, \\text{num}[pos]]$; otherwise, it is $[0, 9]$. For each value, we update the state $st$ and recursively call $\\text{dfs}$ to process the next digit.\n\nFinally, we compute the count of fancy numbers in $[0, r]$ and $[0, l-1]$ separately, and the answer is their difference.\n\nThe time complexity is $O(D^3 \\times \\log^2 r)$ and the space complexity is $O(D^2 \\times \\log^2 r)$, where $D = 10$." }, "is_english": true, "time_complexity": "O(D^3 \\times \\log^2 r)", "space_complexity": "O(D^2 \\times \\log^2 r)" }, { "problem_id": 3870, "explanations": { "1": "Numbers from 1 to 999 contain no commas, so when $n$ is less than or equal to 999, the answer is 0.\n\nSince the range of $n$ is $[1, 10^5]$, when $n$ is greater than or equal to 1000, each number contains exactly one comma, so the answer is $n - 999$.\n\nTherefore, the answer is $\\max(0, n - 999)$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 3871, "explanations": { "1": "Based on the problem description, we can observe the following pattern:\n\n- Numbers in the range [1, 999] contain no commas;\n- Numbers in the range [1,000, 999,999] contain one comma;\n- Numbers in the range [1,000,000, 999,999,999] contain two commas;\n- And so on.\n\nTherefore, we can start from $x = 1000$ and multiply $x$ by 1000 each time until $x$ exceeds $n$. In each iteration, there are $n - x + 1$ numbers that newly gain one comma, and we accumulate their count into the answer.\n\nThe time complexity is $O(\\log n)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(\\log n)", "space_complexity": "O(1)" }, { "problem_id": 3872, "explanations": { "1": "We first compute the differences between adjacent elements of the array, stored as array $d$, where $d[i] = nums[i] - nums[i - 1]$.\n\nNext, we define two arrays $f$ and $g$, where $f[i]$ represents the length of the longest arithmetic subarray ending at the $i$-th element, and $g[i]$ represents the length of the longest arithmetic subarray starting at the $i$-th element. Initially, $f[0] = 1$, $g[n - 1] = 1$, and all other elements are initialized to $2$.\n\nWe can compute the values of $f$ and $g$ in a single pass:\n\n- For $f$: if $d[i] == d[i - 1]$, then $f[i] = f[i - 1] + 1$.\n- For $g$: if $d[i + 1] == d[i + 2]$, then $g[i] = g[i + 1] + 1$.\n\nThen we initialize the answer to $3$, since we can always form an arithmetic subarray of length $3$ by replacing one element. We then enumerate each element and try to replace it with a suitable value to form a longer arithmetic subarray:\n\n- For each element $i$, we can directly use $f[i]$ or $g[i]$ to update the answer.\n- If $i > 0$, we can replace $nums[i]$ with $nums[i - 1] + d[i - 1]$ to extend the arithmetic subarray ending at $i - 1$, updating the answer to $f[i - 1] + 1$.\n- If $i + 1 < n$, we can replace $nums[i]$ with $nums[i + 1] - d[i + 1]$ to extend the arithmetic subarray starting at $i + 1$, updating the answer to $g[i + 1] + 1$.\n- If $0 < i < n - 1$, we can replace $nums[i]$ with $nums[i - 1] + \\frac{nums[i + 1] - nums[i - 1]}{2}$ to try to bridge $f[i - 1]$ and $g[i + 1]$. If this value is an integer and matches both $d[i - 1]$ and $d[i + 1]$, we update the answer to $3 + (f[i - 1] - 1) + (g[i + 1] - 1)$.\n\nFinally, return the answer.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of the array $nums$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3873, "explanations": { "1": "We can use a Union-Find data structure to solve this problem.\n\nFirst, we map the $x$ coordinates and $y$ coordinates of all points into the same Union-Find structure. Specifically, we add a sufficiently large constant $m$ (e.g., $3 \\times 10^9$) to each $y$ coordinate to ensure that the $x$ and $y$ coordinates do not conflict.\n\nNext, we iterate over all points and union those that share the same $x$ coordinate or the same $y$ coordinate. This way, points with the same $x$ or $y$ coordinate will be grouped into the same set.\n\nFinally, we count the number of points in each set and find the sizes of the two largest sets. Since we can add one new point to connect these two sets, the final answer is the sum of the sizes of the two largest sets plus $1$.\n\nThe time complexity is $O(n \\alpha(n))$, where $n$ is the number of points and $\\alpha$ is the inverse Ackermann function. The space complexity is $O(n)$." }, "is_english": true, "time_complexity": "O(n \\alpha(n))", "space_complexity": "O(n)" }, { "problem_id": 3874, "explanations": { "1": "We first traverse the array to find all peak positions and store them in a list $\\textit{peaks}$.\n\nFor each peak position, we calculate the left and right boundaries centered at the peak with a distance not exceeding $k$. Note that if there are multiple peaks, we need to ensure the calculated subarray does not contain other peaks. Then, based on the left and right boundaries, we calculate the number of valid subarrays centered at each peak and accumulate it into the answer.\n\nThe time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3875, "explanations": { "1": "If all elements in $\\textit{nums1}$ are either all odd or all even, we can directly set $\\textit{nums2}$ equal to $\\textit{nums1}$, which satisfies the condition.\n\nIf $\\textit{nums1}$ contains both odd and even numbers, we can set each element of $\\textit{nums2}$ to the current element of $\\textit{nums1}$ minus some element in $\\textit{nums1}$ with different parity. Since odd minus even and even minus odd both yield an odd number, all elements of $\\textit{nums2}$ will be odd, satisfying the condition.\n\nTherefore, regardless of whether the elements in $\\textit{nums1}$ are all odd, all even, or a mix of both, we can always construct a valid $\\textit{nums2}$. Thus the answer is always $\\text{true}$.\n\nThe time complexity is $O(1)$, and the space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(1)", "space_complexity": "O(1)" }, { "problem_id": 3876, "explanations": { "1": "If all elements in $\\textit{nums1}$ are either all odd or all even, we can directly set $\\textit{nums2}$ equal to $\\textit{nums1}$, which satisfies the condition.\n\nIf $\\textit{nums1}$ contains both odd and even numbers, we need to find the minimum odd number $mn$, and check whether there exists an even number $x$ in $\\textit{nums1}$ such that $x < mn$. If such an even number exists, we cannot construct a valid $\\textit{nums2}$, so we return $\\text{false}$; otherwise we return $\\text{true}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums1}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3877, "explanations": { "1": "We define a 2D array $f$, where $f[i][j]$ represents the maximum number of elements we can select from the first $i$ elements such that their XOR sum equals $j$. Initially, $f[0][0] = 0$ and all other $f[0][j]$ are negative infinity.\n\nFor each element $nums[i - 1]$, we can choose not to use it, in which case $f[i][j]$ equals $f[i - 1][j]$; or we can choose to use it, in which case $f[i][j]$ equals $f[i - 1][j \\oplus nums[i - 1]] + 1$. Thus, the transition equation is:\n\n$$\n\\begin{aligned}\nf[i][j] = \\max(f[i - 1][j], f[i - 1][j \\oplus nums[i - 1]] + 1)\n\\end{aligned}\n$$\n\nFinally, if $f[n][target]$ is less than $0$, it means the target XOR value cannot be achieved, and we return $-1$; otherwise, we return $n - f[n][target]$, which is the number of elements that need to be removed.\n\nThe time complexity is $O(n \\times 2^m)$ and the space complexity is $O(n \\times 2^m)$, where $n$ is the length of the array and $m$ is the number of binary bits of the maximum element in the array." }, "is_english": true, "time_complexity": "O(n \\times 2^m)", "space_complexity": "O(n \\times 2^m)" }, { "problem_id": 3878, "explanations": { "1": "We can enumerate each element $\\textit{nums}[i]$ as the bitwise OR result of a subarray, and count how many subarrays have a bitwise OR exactly equal to $\\textit{nums}[i]$.\n\nIf the bitwise OR of a subarray is $\\textit{nums}[i]$, then every element in the subarray must satisfy:\n\n$$\n\\textit{nums}[k] \\mid \\textit{nums}[i] = \\textit{nums}[i]\n$$\n\nThat is, every element in the subarray must be a subset of $\\textit{nums}[i]$ (in terms of bits). We can use a monotonic stack to find the left boundary $l[i]$ and right boundary $r[i]$ for each element $\\textit{nums}[i]$, such that all elements in the interval $(l[i], r[i])$ satisfy the above condition, while $\\textit{nums}[l[i]]$ and $\\textit{nums}[r[i]]$ do not. The number of subarrays with $\\textit{nums}[i]$ as the bitwise OR result is then $(i - l[i]) \\cdot (r[i] - i)$.\n\nThe time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of the array." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3879, "explanations": { "1": "We can treat the tree as an undirected graph, using a hash table $g$ to store the adjacent nodes of each node, where $g[node]$ contains the parent node, left child node, and right child node of $node$.\n\nWe use depth-first search to traverse the tree and build the hash table $g$. For each node, we add its parent node, left child node, and right child node to $g[node]$.\n\nNext, we use another depth-first search to compute the maximum path sum starting from each node. During this process, we use a hash set $vis$ to record the node values already visited on the current path, ensuring all node values along the path are distinct. For each node, we first check whether it is already in $vis$; if so, we return $0$. Otherwise, we add the node value to $vis$ and compute the path sum starting from that node. We traverse the adjacent nodes in $g[node]$, recursively compute the path sum starting from each adjacent node, and update the current best. Finally, we remove the current node value from $vis$ and return the current node value plus the best path sum.\n\nWe perform the above computation for every node in the tree and track the maximum path sum. The final answer is the maximum path sum.\n\nThe time complexity is $O(n^2)$, and the space complexity is $O(n)$, where $n$ is the number of nodes in the tree." }, "is_english": true, "time_complexity": "O(n^2)", "space_complexity": "O(n)" }, { "problem_id": 3880, "explanations": { "1": "We use an array $\\textit{last}$ of length $3$ to record the last occurrence index of digits $0$, $1$, and $2$. Initially, $\\textit{last} = [-(n+1), -(n+1), -(n+1)]$. We iterate through the array $\\textit{nums}$. For the current number $x$, if $x$ is not equal to $0$, we update the answer $\\textit{ans} = \\min(\\textit{ans}, i - \\textit{last}[3 - x])$, where $i$ is the index of the current number $x$. Then we update $\\textit{last}[x] = i$.\n\nAfter the iteration, if $\\textit{ans}$ is greater than the length of the array $\\textit{nums}$, it means no valid index pair exists, so we return -1; otherwise, we return $\\textit{ans}$.\n\nThe time complexity is $O(n)$, where $n$ is the length of the array $\\textit{nums}$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3881, "explanations": { "1": "There are $\\textit{pos}$ people to the left of position $\\textit{pos}$, and $n - \\textit{pos} - 1$ people to the right.\n\nWe enumerate the number of visible people on the left, $a$, so the number of visible people on the right is $b = k - a$. If both $a$ and $b$ are valid, the answer increases by $2 \\cdot \\binom{\\textit{pos}}{a} \\cdot \\binom{n - \\textit{pos} - 1}{b}$. The factor of $2$ comes from the fact that the person at index $\\textit{pos}$ can face either 'L' or 'R'.\n\nFor the binomial coefficient $\\binom{n}{k}$, we can precompute factorials and modular inverses for fast calculation.\n\nThe time complexity is $O(n)$, where $n$ is the input integer $n$. The space complexity is $O(n)$ for storing factorials and modular inverses." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(n)" }, { "problem_id": 3882, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3883, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3884, "explanations": { "1": "We iterate over the first half of the string $s$. For each index $i$, we check whether the characters at position $i$ and position $n - i - 1$ are equal. If they are, we return index $i$. If no such index is found after the iteration, we return -1.\n\nThe time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$." }, "is_english": true, "time_complexity": "O(n)", "space_complexity": "O(1)" }, { "problem_id": 3885, "explanations": { "1": "We define a sorted set $\\textit{sl}$ to store tuples of priority and id $(-\\textit{priority}, \\textit{eventId})$ for all active events, and a hash map $\\textit{d}$ to store the priority of each event.\n\nDuring initialization, we iterate over the given event list, add the tuple of priority and id for each event into the sorted set $\\textit{sl}$, and store each event's priority in the hash map $\\textit{d}$.\n\nFor the $\\textit{updatePriority}(eventId, newPriority)$ operation, we first retrieve the old priority of the event from the hash map $\\textit{d}$, then remove the tuple of the old priority and event id from the sorted set $\\textit{sl}$, add the tuple of the new priority and event id into $\\textit{sl}$, and update the event's priority in $\\textit{d}$.\n\nFor the $\\textit{pollHighest}()$ operation, we first check whether the sorted set $\\textit{sl}$ is empty. If it is, return -1. Otherwise, we retrieve the event with the highest priority (i.e., the first element) from $\\textit{sl}$, remove its tuple, delete the event's priority information from $\\textit{d}$, and return the event's id.\n\nIn terms of time complexity, initialization takes $O(n \\log n)$ time, where $n$ is the number of initial events. Each call to $\\textit{updatePriority}$ and $\\textit{pollHighest}$ takes $O(\\log n)$ time. The space complexity is $O(n)$, where $n$ is the number of active events." }, "is_english": true, "time_complexity": null, "space_complexity": "O(n)" }, { "problem_id": 3886, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3887, "explanations": { "1": "" }, "is_english": false, "time_complexity": null, "space_complexity": null }, { "problem_id": 3888, "explanations": { "1": "Since the operation can only increase the value of elements, all elements in the final grid must be equal to some target value $T$, and $T \\ge \\max(\\textit{grid})$.\n\nStart traversing the grid from the top-left corner $(0, 0)$. For any position $(i, j)$, if its current value is less than $T$, since subsequent operations (with a more rightward or downward position as the top-left corner) cannot cover $(i, j)$, it is necessary to perform $T - \\text{current\\_val}$ operations at the current position, each using $(i, j)$ as the top-left corner of a $k \\times k$ increment operation.\n\nIf each operation traverses the $k \\times k$ region, the complexity will reach $O(m \\cdot n \\cdot k^2)$. We can use a 2D difference array $\\textit{diff}$ to record the operations. By maintaining the 2D prefix sum of $\\textit{diff}$ in real time, we can obtain the cumulative increment at the current position in $O(1)$ time, and update the future impact of a $k \\times k$ region in $O(1)$ time.\n\nIn most cases, $T = \\max(\\textit{grid})$ is sufficient. However, in some cases where $k \\times k$ regions overlap, a smaller $T$ may cause the middle positions to be passively increased beyond $T$. According to mathematical consistency, if both $T = \\max(\\textit{grid})$ and $T = \\max(\\textit{grid}) + 1$ are not feasible, then it is impossible to flatten the grid using $k \\times k$ operations.\n\nThe time complexity is $O(m \\times n)$ and the space complexity is $O(m \\times n)$, where $m$ and $n$ are the number of rows and columns of the grid, respectively." }, "is_english": true, "time_complexity": "O(m \\times n)", "space_complexity": "O(m \\times n)" } ]