Leetcodeleetcode.ca
https://leetcode.ca/
3097 - Shortest Subarray With OR at Least K II
Welcome to Subscribe On Youtube 3097. Shortest Subarray With OR at Least K II Description You are given an array nums of non-negative integers and an integer k. An array is called special if the bitwise OR of all of its elements is at least k. Return the length of the shortest special non-empty subarray of nums, or return -1 if no special subarray exists. Example 1: Input: nums = [1,2,3], k = 2 Output: 1 Explanation: The subarray [3] has OR value of 3. Hence, we return 1. Example 2: Input: nums = [2,1,8], k = 10 Output: 3 Explanation: The subarray [2,1,8] has OR value of 11. Hence, we return 3. Example 3: Input: nums = [1,2], k = 0 Output: 1 Explanation: The subarray [1] has OR value of 1. Hence, we return 1. Constraints: 1 <= nums.length <= 2 * 105 0 <= nums[i] <= 109 0 <= k <= 109 Solutions Solution 1: Two Pointers + Counting 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. Specifically, 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. In 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$. Finally, we return the minimum length. If there is no subarray that meets the conditions, we return $-1$. The 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. Java C++ Python Go TypeScript class Solution { public int minimumSubarrayLength(int[] nums, int k) { int n = nums.length; int[] cnt = new int[32]; int ans = n + 1; for (int i = 0, j = 0, s = 0; j < n; ++j) { s |= nums[j]; for (int h = 0; h < 32; ++h) { if ((nums[j] >> h & 1) == 1) { ++cnt[h]; } } for (; s >= k && i <= j; ++i) { ans = Math.min(ans,...
Wed, 17 Apr 2024 00:00:00 -0700
https://leetcode.ca/2024-04-17-3097-Shortest-Subarray-With-OR-at-Least-K-II/
https://leetcode.ca/2024-04-17-3097-Shortest-Subarray-With-OR-at-Least-K-II/3096 - Minimum Levels to Gain More Points
Welcome to Subscribe On Youtube 3096. Minimum Levels to Gain More Points Description You are given a binary array possible of length n. Alice and Bob are playing a game that consists of n levels. Some of the levels in the game are impossible to clear while others can always be cleared. In particular, if possible[i] == 0, then the ith level is impossible to clear for both the players. A player gains 1 point on clearing a level and loses 1 point if the player fails to clear it. At the start of the game, Alice will play some levels in the given order starting from the 0th level, after which Bob will play for the rest of the levels. Alice wants to know the minimum number of levels she should play to gain more points than Bob, if both players play optimally to maximize their points. Return the minimum number of levels Alice should play to gain more points. If this is not possible, return -1. Note that each player must play at least 1 level. Example 1: Input: possible = [1,0,1,0] Output: 1 Explanation: Let's look at all the levels that Alice can play up to: If Alice plays only level 0 and Bob plays the rest of the levels, Alice has 1 point, while Bob has -1 + 1 - 1 = -1 point. If Alice plays till level 1 and Bob plays the rest of the levels, Alice has 1 - 1 = 0 points, while Bob has 1 - 1 = 0 points. If Alice plays till level 2 and Bob plays the rest of the levels, Alice has 1 - 1 + 1 = 1 point, while Bob has -1 point. Alice must play a minimum of 1 level to gain more points. Example 2: Input: possible = [1,1,1,1,1] Output: 3 Explanation: Let's look at all the levels that Alice can play up to: If Alice plays only level 0 and Bob plays the rest of the levels, Alice has 1 point, while Bob has 4 points. If Alice plays till level 1 and Bob plays the rest of the levels, Alice has 2 points, while Bob has 3 points. If Alice plays till level 2 and Bob plays the rest of the levels, Alice has 3 points, while Bob has 2 points. If Alice plays till level 3 and Bob plays the rest of the levels, Alice has 4 points, while Bob has 1 point. Alice must play a minimum of 3 levels to gain more points. Example 3: Input: possible = [0,0] Output: -1 Explanation: The only possible way is for both players to play 1 level each. Alice plays level 0 and loses 1 point. Bob plays level 1 and loses 1 point. As both players have equal points, Alice can't gain more points than Bob. Constraints: 2 <= n == possible.length <= 105 possible[i] is either 0 or 1. Solutions Solution 1: Enumeration First, we calculate the...
Tue, 16 Apr 2024 00:00:00 -0700
https://leetcode.ca/2024-04-16-3096-Minimum-Levels-to-Gain-More-Points/
https://leetcode.ca/2024-04-16-3096-Minimum-Levels-to-Gain-More-Points/3095 - Shortest Subarray With OR at Least K I
Welcome to Subscribe On Youtube 3095. Shortest Subarray With OR at Least K I Description You are given an array nums of non-negative integers and an integer k. An array is called special if the bitwise OR of all of its elements is at least k. Return the length of the shortest special non-empty subarray of nums, or return -1 if no special subarray exists. Example 1: Input: nums = [1,2,3], k = 2 Output: 1 Explanation: The subarray [3] has OR value of 3. Hence, we return 1. Example 2: Input: nums = [2,1,8], k = 10 Output: 3 Explanation: The subarray [2,1,8] has OR value of 11. Hence, we return 3. Example 3: Input: nums = [1,2], k = 0 Output: 1 Explanation: The subarray [1] has OR value of 1. Hence, we return 1. Constraints: 1 <= nums.length <= 50 0 <= nums[i] <= 50 0 <= k < 64 Solutions Solution 1: Two Pointers + Counting 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. Specifically, 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. In 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$. Finally, we return the minimum length. If there is no subarray that meets the conditions, we return $-1$. The 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. Java C++ Python Go TypeScript class Solution { public int minimumSubarrayLength(int[] nums, int k) { int n = nums.length; int[] cnt = new int[32]; int ans = n + 1; for (int i = 0, j = 0, s = 0; j < n; ++j) { s |= nums[j]; for (int h = 0; h < 32; ++h) { if ((nums[j] >> h & 1) == 1) { ++cnt[h]; } } for (; s >= k && i <= j; ++i) { ans = Math.min(ans, j -...
Mon, 15 Apr 2024 00:00:00 -0700
https://leetcode.ca/2024-04-15-3095-Shortest-Subarray-With-OR-at-Least-K-I/
https://leetcode.ca/2024-04-15-3095-Shortest-Subarray-With-OR-at-Least-K-I/3094 - Guess the Number Using Bitwise Questions II
Welcome to Subscribe On Youtube 3094. Guess the Number Using Bitwise Questions II Description There is a number n between 0 and 230 - 1 (both inclusive) that you have to find. There is a pre-defined API int commonBits(int num) that helps you with your mission. But here is the challenge, every time you call this function, n changes in some way. But keep in mind, that you have to find the initial value of n. commonBits(int num) acts as follows: Calculate count which is the number of bits where both n and num have the same value in that position of their binary representation. n = n XOR num Return count. Return the number n. Note: In this world, all numbers are between 0 and 230 - 1 (both inclusive), thus for counting common bits, we see only the first 30 bits of those numbers. Example 1: Input: n = 31 Output: 31 Explanation: It can be proven that it's possible to find 31 using the provided API. Example 2: Input: n = 33 Output: 33 Explanation: It can be proven that it's possible to find 33 using the provided API. Constraints: 0 <= n <= 230 - 1 0 <= num <= 230 - 1 If you ask for some num out of the given range, the output wouldn't be reliable. Solutions Solution 1: Bit Manipulation Based on the problem description, we observe that: If we call the commonBits function twice with the same number, the value of $n$ will not change. 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. Therefore, 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$. The time complexity is $O(\log n)$, and the space complexity is $O(1)$. Java C++ Python Go /** * Definition of commonBits API (defined in the parent class Problem). * int commonBits(int num); */ public class Solution extends Problem { public int findNumber() { int n = 0; for (int i = 0; i < 32; ++i) { int count1 = commonBits(1 << i); int count2 = commonBits(1 << i); if (count1 > count2) { n |= 1 << i; } } return n; } } /** * Definition of commonBits API. * int commonBits(int num); */ class Solution { public: int findNumber() { int n = 0; for (int i = 0; i < 32; ++i) { int count1 = commonBits(1 << i); int count2 = commonBits(1 << i); if (count1 > count2) { n |= 1 << i; } } return n; } }; # Definition of commonBits API. # def commonBits(num: int) -> int: class Solution: def findNumber(self) -> int: n = 0 for i in range(32): count1 = commonBits(1 << i) count2 =...
Sun, 14 Apr 2024 00:00:00 -0700
https://leetcode.ca/2024-04-14-3094-Guess-the-Number-Using-Bitwise-Questions-II/
https://leetcode.ca/2024-04-14-3094-Guess-the-Number-Using-Bitwise-Questions-II/3093 - Longest Common Suffix Queries
Welcome to Subscribe On Youtube 3093. Longest Common Suffix Queries Description You are given two arrays of strings wordsContainer and wordsQuery. For each wordsQuery[i], you need to find a string from wordsContainer that has the longest common suffix with wordsQuery[i]. If there are two or more strings in wordsContainer that share the longest common suffix, find the string that is the smallest in length. If there are two or more such strings that have the same smallest length, find the one that occurred earlier in wordsContainer. Return an array of integers ans, where ans[i] is the index of the string in wordsContainer that has the longest common suffix with wordsQuery[i]. Example 1: Input: wordsContainer = ["abcd","bcd","xbcd"], wordsQuery = ["cd","bcd","xyz"] Output: [1,1,1] Explanation: Let's look at each wordsQuery[i] separately: For wordsQuery[0] = "cd", strings from wordsContainer that share the longest common suffix "cd" are at indices 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3. For wordsQuery[1] = "bcd", strings from wordsContainer that share the longest common suffix "bcd" are at indices 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3. For wordsQuery[2] = "xyz", there is no string from wordsContainer that shares a common suffix. Hence the longest common suffix is "", that is shared with strings at index 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3. Example 2: Input: wordsContainer = ["abcdefgh","poiuygh","ghghgh"], wordsQuery = ["gh","acbfgh","acbfegh"] Output: [2,0,2] Explanation: Let's look at each wordsQuery[i] separately: For wordsQuery[0] = "gh", strings from wordsContainer that share the longest common suffix "gh" are at indices 0, 1, and 2. Among these, the answer is the string at index 2 because it has the shortest length of 6. For wordsQuery[1] = "acbfgh", only the string at index 0 shares the longest common suffix "fgh". Hence it is the answer, even though the string at index 2 is shorter. For wordsQuery[2] = "acbfegh", strings from wordsContainer that share the longest common suffix "gh" are at indices 0, 1, and 2. Among these, the answer is the string at index 2 because it has the shortest length of 6. Constraints: 1 <= wordsContainer.length, wordsQuery.length <= 104 1 <= wordsContainer[i].length <= 5 * 103 1 <= wordsQuery[i].length <= 5 * 103 wordsContainer[i] consists only of lowercase English letters. wordsQuery[i] consists only of lowercase English letters. Sum of wordsContainer[i].length is at most 5 * 105. Sum of wordsQuery[i].length is at most 5 * 105. Solutions Solution 1: Trie The problem requires us to find the longest common suffix, so we can consider using a Trie. We define the structure of the Trie node as follows: children: An array of length 26, used to store child nodes. length: The length of the shortest string at the current node. idx: The index of the string at the current...
Sat, 13 Apr 2024 00:00:00 -0700
https://leetcode.ca/2024-04-13-3093-Longest-Common-Suffix-Queries/
https://leetcode.ca/2024-04-13-3093-Longest-Common-Suffix-Queries/3092 - Most Frequent IDs
Welcome to Subscribe On Youtube 3092. Most Frequent IDs Description The problem involves tracking the frequency of IDs in a collection that changes over time. You have two integer arrays, nums and freq, of equal length n. Each element in nums represents an ID, and the corresponding element in freq indicates how many times that ID should be added to or removed from the collection at each step. Addition of IDs: If freq[i] is positive, it means freq[i] IDs with the value nums[i] are added to the collection at step i. Removal of IDs: If freq[i] is negative, it means -freq[i] IDs with the value nums[i] are removed from the collection at step i. Return an array ans of length n, where ans[i] represents the count of the most frequent ID in the collection after the ith step. If the collection is empty at any step, ans[i] should be 0 for that step. Example 1: Input: nums = [2,3,2,1], freq = [3,2,-3,1] Output: [3,3,2,2] Explanation: After step 0, we have 3 IDs with the value of 2. So ans[0] = 3. After step 1, we have 3 IDs with the value of 2 and 2 IDs with the value of 3. So ans[1] = 3. After step 2, we have 2 IDs with the value of 3. So ans[2] = 2. After step 3, we have 2 IDs with the value of 3 and 1 ID with the value of 1. So ans[3] = 2. Example 2: Input: nums = [5,5,3], freq = [2,-2,1] Output: [2,0,1] Explanation: After step 0, we have 2 IDs with the value of 5. So ans[0] = 2. After step 1, there are no IDs. So ans[1] = 0. After step 2, we have 1 ID with the value of 3. So ans[2] = 1. Constraints: 1 <= nums.length == freq.length <= 105 1 <= nums[i] <= 105 -105 <= freq[i] <= 105 freq[i] != 0 The input is generated such that the occurrences of an ID will not be negative in any step. Solutions Solution 1: Hash Table + Priority Queue (Max Heap) 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. For 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...
Fri, 12 Apr 2024 00:00:00 -0700
https://leetcode.ca/2024-04-12-3092-Most-Frequent-IDs/
https://leetcode.ca/2024-04-12-3092-Most-Frequent-IDs/3091 - Apply Operations to Make Sum of Array Greater Than or Equal to k
Welcome to Subscribe On Youtube 3091. Apply Operations to Make Sum of Array Greater Than or Equal to k Description You are given a positive integer k. Initially, you have an array nums = [1]. You can perform any of the following operations on the array any number of times (possibly zero): Choose any element in the array and increase its value by 1. Duplicate any element in the array and add it to the end of the array. Return the minimum number of operations required to make the sum of elements of the final array greater than or equal to k. Example 1: Input: k = 11 Output: 5 Explanation: We can do the following operations on the array nums = [1]: Increase the element by 1 three times. The resulting array is nums = [4]. Duplicate the element two times. The resulting array is nums = [4,4,4]. The sum of the final array is 4 + 4 + 4 = 12 which is greater than or equal to k = 11. The total number of operations performed is 3 + 2 = 5. Example 2: Input: k = 1 Output: 0 Explanation: The sum of the original array is already greater than or equal to 1, so no operations are needed. Constraints: 1 <= k <= 105 Solutions Solution 1: Enumeration We should put the copy operation (i.e., operation $2$) at the end to reduce the number of operations. Therefore, 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$. The time complexity is $O(k)$, where $k$ is the input positive integer $k$. The space complexity is $O(1)$. Java C++ Python Go TypeScript class Solution { public int minOperations(int k) { int ans = k; for (int a = 0; a < k; ++a) { int x = a + 1; int b = (k + x - 1) / x - 1; ans = Math.min(ans, a + b); } return ans; } } class Solution { public: int minOperations(int k) { int ans = k; for (int a = 0; a < k; ++a) { int x = a + 1; int b = (k + x - 1) / x - 1; ans = min(ans, a + b); } return ans; } }; class Solution: def minOperations(self, k: int) -> int: ans = k for a in range(k): x = a + 1 b = (k + x - 1) // x - 1 ans = min(ans, a + b) return ans func minOperations(k int) int { ans := k for a := 0; a < k; a++ { x := a + 1 b := (k+x-1)/x - 1 ans = min(ans, a+b) } return ans } function minOperations(k: number): number { let ans = k; for (let a = 0; a < k; ++a) { const x...
Thu, 11 Apr 2024 00:00:00 -0700
https://leetcode.ca/2024-04-11-3091-Apply-Operations-to-Make-Sum-of-Array-Greater-Than-or-Equal-to-k/
https://leetcode.ca/2024-04-11-3091-Apply-Operations-to-Make-Sum-of-Array-Greater-Than-or-Equal-to-k/3090 - Maximum Length Substring With Two Occurrences
Welcome to Subscribe On Youtube
3090. Maximum Length Substring With Two Occurrences
Description
Given a string s, return the maximum length of a substring such that it contains at most two occurrences of each character.
Example 1:
Input: s = "bcbbbcba"
Output: 4
Explanation:
The following substring has a length of 4 and contains at most two occurrences of each character: "bcbbbcba".
Example 2:
Input: s = "aaaa"
Output: 2
Explanation:
The following substring has a length of 2 and contains at most two occurrences of each character: "aaaa".
Constraints:
2 <= s.length <= 100
s consists only of lowercase English letters.
Solutions
Solution 1: Two Pointers
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.
In 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)$.
Finally, we return the answer $ans$.
The 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$.
Java
C++
Python
Go
TypeScript
class Solution {
public int maximumLengthSubstring(String s) {
int[] cnt = new int[26];
int ans = 0;
for (int i = 0, j = 0; j < s.length(); ++j) {
int idx = s.charAt(j) - 'a';
++cnt[idx];
while (cnt[idx] > 2) {
--cnt[s.charAt(i++) - 'a'];
}
ans = Math.max(ans, j - i + 1);
}
return ans;
}
}
class Solution {
public:
int maximumLengthSubstring(string s) {
int cnt[26]{};
int ans = 0;
for (int i = 0, j = 0; j < s.length(); ++j) {
int idx = s[j] - 'a';
++cnt[idx];
while (cnt[idx] > 2) {
--cnt[s[i++] - 'a'];
}
ans = max(ans, j - i + 1);
}
return ans;
}
};
class Solution:
def maximumLengthSubstring(self, s: str) -> int:
cnt = Counter()
ans = i = 0
for j, c in enumerate(s):
cnt[c] += 1
while cnt[c] > 2:
cnt[s[i]] -= 1
i += 1
ans = max(ans, j - i + 1)
return ans
func maximumLengthSubstring(s string) (ans int) {
cnt := [26]int{}
i := 0
for j, c := range s {
idx := c - 'a'
cnt[idx]++
for cnt[idx] > 2 {
cnt[s[i]-'a']--
i++
}
ans = max(ans, j-i+1)
}
return
}
function maximumLengthSubstring(s: string): number {
let ans = 0;
const cnt: number[] = Array(26).fill(0);
for (let i = 0, j = 0; j < s.length; ++j) {
const idx = s[j].charCodeAt(0) - 'a'.charCodeAt(0);
++cnt[idx];
while (cnt[idx] > 2) {
--cnt[s[i++].charCodeAt(0) - 'a'.charCodeAt(0)];
}
ans = Math.max(ans, j - i + 1);
}
return ans;
}
All Problems
All Solutions
Wed, 10 Apr 2024 00:00:00 -0700
https://leetcode.ca/2024-04-10-3090-Maximum-Length-Substring-With-Two-Occurrences/
https://leetcode.ca/2024-04-10-3090-Maximum-Length-Substring-With-Two-Occurrences/3089 - Find Bursty Behavior
Welcome to Subscribe On Youtube 3089. Find Bursty Behavior Description Table: Posts +-------------+---------+ \| Column Name \| Type \| +-------------+---------+ \| post_id \| int \| \| user_id \| int \| \| post_date \| date \| +-------------+---------+ post_id is the primary key (column with unique values) for this table. Each row of this table contains post_id, user_id, and post_date. Write a solution to find users who demonstrate bursty behavior in their posting patterns during February 2024. Bursty behavior is defined as any period of 7 consecutive days where a user's posting frequency is at least twice to their average weekly posting frequency for February 2024. Note: Only include the dates from February 1 to February 28 in your analysis, which means you should count February as having exactly 4 weeks. Return the result table orderd by user_id in ascending order. The result format is in the following example. Example: Input: Posts table: +---------+---------+------------+ \| post_id \| user_id \| post_date \| +---------+---------+------------+ \| 1 \| 1 \| 2024-02-27 \| \| 2 \| 5 \| 2024-02-06 \| \| 3 \| 3 \| 2024-02-25 \| \| 4 \| 3 \| 2024-02-14 \| \| 5 \| 3 \| 2024-02-06 \| \| 6 \| 2 \| 2024-02-25 \| +---------+---------+------------+ Output: +---------+----------------+------------------+ \| user_id \| max_7day_posts \| avg_weekly_posts \| +---------+----------------+------------------+ \| 1 \| 1 \| 0.2500 \| \| 2 \| 1 \| 0.2500 \| \| 5 \| 1 \| 0.2500 \| +---------+----------------+------------------+ Explanation: User 1: Made only 1 post in February, resulting in an average of 0.25 posts per week and a max of 1 post in any 7-day period. User 2: Also made just 1 post, with the same average and max 7-day posting frequency as User 1. User 5: Like Users 1 and 2, User 5 made only 1 post throughout February, leading to the same average and max 7-day posting metrics. User 3: Although User 3 made more posts than the others (3 posts), they did not reach twice the average weekly posts in their consecutive 7-day window, so they are not listed in the output. Note: Output table is ordered by user_id in ascending order. Solutions Solution 1: Self-Join + Group Count 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. Next, 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. Finally, we connect tables P and T with the...
Tue, 09 Apr 2024 00:00:00 -0700
https://leetcode.ca/2024-04-09-3089-Find-Bursty-Behavior/
https://leetcode.ca/2024-04-09-3089-Find-Bursty-Behavior/3088 - Make String Anti-palindrome
Welcome to Subscribe On Youtube 3088. Make String Anti-palindrome Description We call a string s of even length n an anti-palindrome if for each index 0 <= i < n, s[i] != s[n - i - 1]. Given a string s, your task is to make s an anti-palindrome by doing any number of operations (including zero). In one operation, you can select two characters from s and swap them. Return the resulting string. If multiple strings meet the conditions, return the lexicographically smallest one. If it can't be made into an anti-palindrome, return "-1". Example 1: Input: s = "abca" Output: "aabc" Explanation: "aabc" is an anti-palindrome string since s[0] != s[3] and s[1] != s[2]. Also, it is a rearrangement of "abca". Example 2: Input: s = "abba" Output: "aabb" Explanation: "aabb" is an anti-palindrome string since s[0] != s[3] and s[1] != s[2]. Also, it is a rearrangement of "abba". Example 3: Input: s = "cccd" Output: "-1" Explanation: You can see that no matter how you rearrange the characters of "cccd", either s[0] == s[3] or s[1] == s[2]. So it can not form an anti-palindrome string. Constraints: 2 <= s.length <= 105 s.length % 2 == 0 s consists only of lowercase English letters. Solutions Solution 1: Greedy + Sorting 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. Next, 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. The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string $s$. Java C++ Python Go TypeScript class Solution { public String makeAntiPalindrome(String s) { char[] cs = s.toCharArray(); Arrays.sort(cs); int n = cs.length; int m = n / 2; if (cs[m] == cs[m - 1]) { int i = m; while (i < n && cs[i] == cs[i - 1]) { ++i; } for (int j = m; j < n && cs[j] == cs[n - j - 1]; ++i, ++j) { if (i >= n) { return "-1"; } char t = cs[i]; cs[i] = cs[j]; cs[j] = t; } } return new String(cs); } } class Solution { public: string makeAntiPalindrome(string s) { sort(s.begin(), s.end()); int n = s.length(); int m = n / 2; if (s[m] == s[m - 1]) { int i =...
Mon, 08 Apr 2024 00:00:00 -0700
https://leetcode.ca/2024-04-08-3088-Make-String-Anti-palindrome/
https://leetcode.ca/2024-04-08-3088-Make-String-Anti-palindrome/3087 - Find Trending Hashtags
Welcome to Subscribe On Youtube
3087. Find Trending Hashtags
Description
Table: Tweets
+-------------+---------+
\| Column Name \| Type \|
+-------------+---------+
\| user_id \| int \|
\| tweet_id \| int \|
\| tweet_date \| date \|
\| tweet \| varchar \|
+-------------+---------+
tweet_id is the primary key (column with unique values) for this table.
Each row of this table contains user_id, tweet_id, tweet_date and tweet.
Write a solution to find the top 3 trending hashtags in February 2024. Each tweet only contains one hashtag.
Return the result table orderd by count of hashtag, hashtag in descending order.
The result format is in the following example.
Example 1:
Input:
Tweets table:
+---------+----------+----------------------------------------------+------------+
\| user_id \| tweet_id \| tweet \| tweet_date \|
+---------+----------+----------------------------------------------+------------+
\| 135 \| 13 \| Enjoying a great start to the day! #HappyDay \| 2024-02-01 \|
\| 136 \| 14 \| Another #HappyDay with good vibes! \| 2024-02-03 \|
\| 137 \| 15 \| Productivity peaks! #WorkLife \| 2024-02-04 \|
\| 138 \| 16 \| Exploring new tech frontiers. #TechLife \| 2024-02-04 \|
\| 139 \| 17 \| Gratitude for today's moments. #HappyDay \| 2024-02-05 \|
\| 140 \| 18 \| Innovation drives us. #TechLife \| 2024-02-07 \|
\| 141 \| 19 \| Connecting with nature's serenity. #Nature \| 2024-02-09 \|
+---------+----------+----------------------------------------------+------------+
Output:
+-----------+--------------+
\| hashtag \| hashtag_count\|
+-----------+--------------+
\| #HappyDay \| 3 \|
\| #TechLife \| 2 \|
\| #WorkLife \| 1 \|
+-----------+--------------+
Explanation:
#HappyDay: Appeared in tweet IDs 13, 14, and 17, with a total count of 3 mentions.
#TechLife: Appeared in tweet IDs 16 and 18, with a total count of 2 mentions.
#WorkLife: Appeared in tweet ID 15, with a total count of 1 mention.
Note: Output table is sorted in descending order by hashtag_count and hashtag respectively.
Solutions
Solution 1: Extract Substring + Grouping
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.
Python
SQL
import pandas as pd
def find_trending_hashtags(tweets: pd.DataFrame) -> pd.DataFrame:
tweets = tweets[tweets["tweet_date"].dt.strftime("%Y%m") == "202402"]
tweets["hashtag"] = "#" + tweets["tweet"].str.extract(r"#(\w+)")
hashtag_counts = tweets["hashtag"].value_counts().reset_index()
hashtag_counts.columns = ["hashtag", "hashtag_count"]
hashtag_counts = hashtag_counts.sort_values(
by=["hashtag_count", "hashtag"], ascending=[False, False]
)
top_3_hashtags = hashtag_counts.head(3)
return top_3_hashtags
# Write your MySQL query statement below
SELECT
CONCAT('#', SUBSTRING_INDEX(SUBSTRING_INDEX(tweet, '#', -1), ' ', 1)) AS hashtag,
COUNT(1) AS hashtag_count
FROM Tweets
WHERE DATE_FORMAT(tweet_date, '%Y%m') = '202402'
GROUP BY 1
ORDER BY 2 DESC, 1 DESC
LIMIT 3;
All Problems
All Solutions
Sun, 07 Apr 2024 00:00:00 -0700
https://leetcode.ca/2024-04-07-3087-Find-Trending-Hashtags/
https://leetcode.ca/2024-04-07-3087-Find-Trending-Hashtags/3086 - Minimum Moves to Pick K Ones
Welcome to Subscribe On Youtube 3086. Minimum Moves to Pick K Ones Description You are given a binary array nums of length n, a positive integer k and a non-negative integer maxChanges. Alice plays a game, where the goal is for Alice to pick up k ones from nums using the minimum number of moves. When the game starts, Alice picks up any index aliceIndex in the range [0, n - 1] and stands there. If nums[aliceIndex] == 1 , Alice picks up the one and nums[aliceIndex] becomes 0(this does not count as a move). After this, Alice can make any number of moves (including zero) where in each move Alice must perform exactly one of the following actions: Select any index j != aliceIndex such that nums[j] == 0 and set nums[j] = 1. This action can be performed at most maxChanges times. Select any two adjacent indices x and y (\|x - y\| == 1) such that nums[x] == 1, nums[y] == 0, then swap their values (set nums[y] = 1 and nums[x] = 0). If y == aliceIndex, Alice picks up the one after this move and nums[y] becomes 0. Return the minimum number of moves required by Alice to pick exactly k ones. Example 1: Input: nums = [1,1,0,0,0,1,1,0,0,1], k = 3, maxChanges = 1 Output: 3 Explanation: Alice can pick up 3 ones in 3 moves, if Alice performs the following actions in each move when standing at aliceIndex == 1: At the start of the game Alice picks up the one and nums[1] becomes 0. nums becomes [1,1,1,0,0,1,1,0,0,1]. Select j == 2 and perform an action of the first type. nums becomes [1,0,1,0,0,1,1,0,0,1] Select x == 2 and y == 1, and perform an action of the second type. nums becomes [1,1,0,0,0,1,1,0,0,1]. As y == aliceIndex, Alice picks up the one and nums becomes [1,0,0,0,0,1,1,0,0,1]. Select x == 0 and y == 1, and perform an action of the second type. nums becomes [0,1,0,0,0,1,1,0,0,1]. As y == aliceIndex, Alice picks up the one and nums becomes [0,0,0,0,0,1,1,0,0,1]. Note that it may be possible for Alice to pick up 3 ones using some other sequence of 3 moves. Example 2: Input: nums = [0,0,0,0], k = 2, maxChanges = 3 Output: 4 Explanation: Alice can pick up 2 ones in 4 moves, if Alice performs the following actions in each move when standing at aliceIndex == 0: Select j == 1 and perform an action of the first type. nums becomes [0,1,0,0]. Select x == 1 and y == 0, and perform an action of the second type. nums becomes [1,0,0,0]. As y == aliceIndex, Alice picks up the one and nums becomes [0,0,0,0]. Select j == 1 again and perform an action of the first type. nums becomes [0,1,0,0]. Select x == 1 and y == 0 again, and perform an action of the second type. nums becomes [1,0,0,0]. As y == aliceIndex, Alice picks up the one and nums becomes [0,0,0,0]. Constraints: 2 <= n...
Sat, 06 Apr 2024 00:00:00 -0700
https://leetcode.ca/2024-04-06-3086-Minimum-Moves-to-Pick-K-Ones/
https://leetcode.ca/2024-04-06-3086-Minimum-Moves-to-Pick-K-Ones/3085 - Minimum Deletions to Make String K-Special
Welcome to Subscribe On Youtube 3085. Minimum Deletions to Make String K-Special Description You are given a string word and an integer k. We consider word to be k-special if \|freq(word[i]) - freq(word[j])\| <= k for all indices i and j in the string. Here, freq(x) denotes the frequency of the character x in word, and \|y\| denotes the absolute value of y. Return the minimum number of characters you need to delete to make word k-special. Example 1: Input: word = "aabcaba", k = 0 Output: 3 Explanation: We can make word 0-special by deleting 2 occurrences of "a" and 1 occurrence of "c". Therefore, word becomes equal to "baba" where freq('a') == freq('b') == 2. Example 2: Input: word = "dabdcbdcdcd", k = 2 Output: 2 Explanation: We can make word 2-special by deleting 1 occurrence of "a" and 1 occurrence of "d". Therefore, word becomes equal to "bdcbdcdcd" where freq('b') == 2, freq('c') == 3, and freq('d') == 4. Example 3: Input: word = "aaabaaa", k = 2 Output: 1 Explanation: We can make word 2-special by deleting 1 occurrence of "b". Therefore, word becomes equal to "aaaaaa" where each letter's frequency is now uniformly 6. Constraints: 1 <= word.length <= 105 0 <= k <= 105 word consists only of lowercase English letters. Solutions Solution 1: Counting + Enumeration 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$. Next, 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. The calculation method of function $f(v)$ is as follows: Traverse 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)$. The 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$. Java C++ Python Go TypeScript class Solution { private List<Integer> nums = new ArrayList<>(); public int minimumDeletions(String word, int k) { int[] freq = new int[26]; int n = word.length(); for (int i = 0; i < n; ++i) { ++freq[word.charAt(i) - 'a']; } for (int v : freq) { if (v > 0) { nums.add(v); } } int ans = n; for...
Fri, 05 Apr 2024 00:00:00 -0700
https://leetcode.ca/2024-04-05-3085-Minimum-Deletions-to-Make-String-K-Special/
https://leetcode.ca/2024-04-05-3085-Minimum-Deletions-to-Make-String-K-Special/3084 - Count Substrings Starting and Ending with Given Character
Welcome to Subscribe On Youtube
3084. Count Substrings Starting and Ending with Given Character
Description
You are given a string s and a character c. Return the total number of substrings of s that start and end with c.
Example 1:
Input: s = "abada", c = "a"
Output: 6
Explanation: Substrings starting and ending with "a" are: "abada", "abada", "abada", "abada", "abada", "abada".
Example 2:
Input: s = "zzz", c = "z"
Output: 6
Explanation: There are a total of 6 substrings in s and all start and end with "z".
Constraints:
1 <= s.length <= 105
s and c consist only of lowercase English letters.
Solutions
Solution 1: Mathematics
First, we can count the number of character $c$ in string $s$, denoted as $cnt$.
Each 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.
Therefore, the answer is $cnt + \frac{cnt \times (cnt - 1)}{2}$.
The time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$.
Java
C++
Python
Go
TypeScript
class Solution {
public long countSubstrings(String s, char c) {
long cnt = s.chars().filter(ch -> ch == c).count();
return cnt + cnt * (cnt - 1) / 2;
}
}
class Solution {
public:
long long countSubstrings(string s, char c) {
long long cnt = ranges::count(s, c);
return cnt + cnt * (cnt - 1) / 2;
}
};
class Solution:
def countSubstrings(self, s: str, c: str) -> int:
cnt = s.count(c)
return cnt + cnt * (cnt - 1) // 2
func countSubstrings(s string, c byte) int64 {
cnt := int64(strings.Count(s, string(c)))
return cnt + cnt*(cnt-1)/2
}
function countSubstrings(s: string, c: string): number {
const cnt = s.split('').filter(ch => ch === c).length;
return cnt + Math.floor((cnt * (cnt - 1)) / 2);
}
All Problems
All Solutions
Thu, 04 Apr 2024 00:00:00 -0700
https://leetcode.ca/2024-04-04-3084-Count-Substrings-Starting-and-Ending-with-Given-Character/
https://leetcode.ca/2024-04-04-3084-Count-Substrings-Starting-and-Ending-with-Given-Character/3083 - Existence of a Substring in a String and Its Reverse
Welcome to Subscribe On Youtube 3083. Existence of a Substring in a String and Its Reverse Description Given a string s, find any substring of length 2 which is also present in the reverse of s. Return true if such a substring exists, and false otherwise. Example 1: Input: s = "leetcode" Output: true Explanation: Substring "ee" is of length 2 which is also present in reverse(s) == "edocteel". Example 2: Input: s = "abcba" Output: true Explanation: All of the substrings of length 2 "ab", "bc", "cb", "ba" are also present in reverse(s) == "abcba". Example 3: Input: s = "abcd" Output: false Explanation: There is no substring of length 2 in s, which is also present in the reverse of s. Constraints: 1 <= s.length <= 100 s consists only of lowercase English letters. Solutions Solution 1: Hash Table or Array We can use a hash table or a two-dimensional array $st$ to store all substrings of length $2$ of the reversed string $s$. Then 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. The 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$. Java C++ Python Go TypeScript class Solution { public boolean isSubstringPresent(String s) { boolean[][] st = new boolean[26][26]; int n = s.length(); for (int i = 0; i < n - 1; ++i) { st[s.charAt(i + 1) - 'a'][s.charAt(i) - 'a'] = true; } for (int i = 0; i < n - 1; ++i) { if (st[s.charAt(i) - 'a'][s.charAt(i + 1) - 'a']) { return true; } } return false; } } class Solution { public: bool isSubstringPresent(string s) { bool st[26][26]{}; int n = s.size(); for (int i = 0; i < n - 1; ++i) { st[s[i + 1] - 'a'][s[i] - 'a'] = true; } for (int i = 0; i < n - 1; ++i) { if (st[s[i] - 'a'][s[i + 1] - 'a']) { return true; } } return false; } }; class Solution: def isSubstringPresent(self, s: str) -> bool: st = {(a, b) for a, b in pairwise(s[::-1])} return any((a, b) in st for a, b in pairwise(s)) func isSubstringPresent(s string) bool { st := [26][26]bool{} for i := 0; i < len(s)-1; i++ { st[s[i+1]-'a'][s[i]-'a'] = true } for i := 0; i < len(s)-1; i++ { if st[s[i]-'a'][s[i+1]-'a'] { return true } } return false } function isSubstringPresent(s: string): boolean { const st: boolean[][] = Array.from({ length: 26 }, () => Array(26).fill(false)); for (let i = 0; i < s.length - 1; ++i) { st[s.charCodeAt(i + 1) - 97][s.charCodeAt(i) - 97] = true; } for (let i = 0; i < s.length - 1; ++i) { if...
Wed, 03 Apr 2024 00:00:00 -0700
https://leetcode.ca/2024-04-03-3083-Existence-of-a-Substring-in-a-String-and-Its-Reverse/
https://leetcode.ca/2024-04-03-3083-Existence-of-a-Substring-in-a-String-and-Its-Reverse/3082 - Find the Sum of the Power of All Subsequences
Welcome to Subscribe On Youtube
3082. Find the Sum of the Power of All Subsequences
Description
You are given an integer array nums of length n and a positive integer k.
The power of an array of integers is defined as the number of subsequences with their sum equal to k.
Return the sum of power of all subsequences of nums.
Since the answer may be very large, return it modulo 109 + 7.
Example 1:
Input: nums = [1,2,3], k = 3
Output: 6
Explanation:
There are 5 subsequences of nums with non-zero power:
The subsequence [1,2,3] has 2 subsequences with sum == 3: [1,2,3] and [1,2,3].
The subsequence [1,2,3] has 1 subsequence with sum == 3: [1,2,3].
The subsequence [1,2,3] has 1 subsequence with sum == 3: [1,2,3].
The subsequence [1,2,3] has 1 subsequence with sum == 3: [1,2,3].
The subsequence [1,2,3] has 1 subsequence with sum == 3: [1,2,3].
Hence the answer is 2 + 1 + 1 + 1 + 1 = 6.
Example 2:
Input: nums = [2,3,3], k = 5
Output: 4
Explanation:
There are 3 subsequences of nums with non-zero power:
The subsequence [2,3,3] has 2 subsequences with sum == 5: [2,3,3] and [2,3,3].
The subsequence [2,3,3] has 1 subsequence with sum == 5: [2,3,3].
The subsequence [2,3,3] has 1 subsequence with sum == 5: [2,3,3].
Hence the answer is 2 + 1 + 1 = 4.
Example 3:
Input: nums = [1,2,3], k = 7
Output: 0
Explanation: There exists no subsequence with sum 7. Hence all subsequences of nums have power = 0.
Constraints:
1 <= n <= 100
1 <= nums[i] <= 104
1 <= k <= 100
Solutions
Solution 1
All Problems
All Solutions
Tue, 02 Apr 2024 00:00:00 -0700
https://leetcode.ca/2024-04-02-3082-Find-the-Sum-of-the-Power-of-All-Subsequences/
https://leetcode.ca/2024-04-02-3082-Find-the-Sum-of-the-Power-of-All-Subsequences/3081 - Replace Question Marks in String to Minimize Its Value
Welcome to Subscribe On Youtube 3081. Replace Question Marks in String to Minimize Its Value Description You are given a string s. s[i] is either a lowercase English letter or '?'. For a string t having length m containing only lowercase English letters, we define the function cost(i) for an index i as the number of characters equal to t[i] that appeared before it, i.e. in the range [0, i - 1]. The value of t is the sum of cost(i) for all indices i. For example, for the string t = "aab": cost(0) = 0 cost(1) = 1 cost(2) = 0 Hence, the value of "aab" is 0 + 1 + 0 = 1. Your task is to replace all occurrences of '?' in s with any lowercase English letter so that the value of s is minimized. Return a string denoting the modified string with replaced occurrences of '?'. If there are multiple strings resulting in the minimum value, return the lexicographically smallest one. Example 1: Input: s = "???" Output: "abc" Explanation: In this example, we can replace the occurrences of '?' to make s equal to "abc". For "abc", cost(0) = 0, cost(1) = 0, and cost(2) = 0. The value of "abc" is 0. Some other modifications of s that have a value of 0 are "cba", "abz", and, "hey". Among all of them, we choose the lexicographically smallest. Example 2: Input: s = "a?a?" Output: "abac" Explanation: In this example, the occurrences of '?' can be replaced to make s equal to "abac". For "abac", cost(0) = 0, cost(1) = 0, cost(2) = 1, and cost(3) = 0. The value of "abac" is 1. Constraints: 1 <= s.length <= 105 s[i] is either a lowercase English letter or '?'. Solutions Solution 1: Greedy + Priority Queue 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. Therefore, 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. The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string $s$. Java C++ Python Go class Solution { public String minimizeStringValue(String s) { int[] cnt = new int[26]; int n = s.length(); int k = 0; char[] cs = s.toCharArray(); for (char c : cs) { if (c == '?') { ++k; } else {...
Mon, 01 Apr 2024 00:00:00 -0700
https://leetcode.ca/2024-04-01-3081-Replace-Question-Marks-in-String-to-Minimize-Its-Value/
https://leetcode.ca/2024-04-01-3081-Replace-Question-Marks-in-String-to-Minimize-Its-Value/3080 - Mark Elements on Array by Performing Queries
Welcome to Subscribe On Youtube 3080. Mark Elements on Array by Performing Queries Description You are given a 0-indexed array nums of size n consisting of positive integers. You are also given a 2D array queries of size m where queries[i] = [indexi, ki]. Initially all elements of the array are unmarked. You need to apply m queries on the array in order, where on the ith query you do the following: Mark the element at index indexi if it is not already marked. Then mark ki unmarked elements in the array with the smallest values. If multiple such elements exist, mark the ones with the smallest indices. And if less than ki unmarked elements exist, then mark all of them. Return an array answer of size m where answer[i] is the sum of unmarked elements in the array after the ith query. Example 1: Input: nums = [1,2,2,1,2,3,1], queries = [[1,2],[3,3],[4,2]] Output: [8,3,0] Explanation: We do the following queries on the array: Mark the element at index 1, and 2 of the smallest unmarked elements with the smallest indices if they exist, the marked elements now are nums = [1,2,2,1,2,3,1]. The sum of unmarked elements is 2 + 2 + 3 + 1 = 8. Mark the element at index 3, since it is already marked we skip it. Then we mark 3 of the smallest unmarked elements with the smallest indices, the marked elements now are nums = [1,2,2,1,2,3,1]. The sum of unmarked elements is 3. Mark the element at index 4, since it is already marked we skip it. Then we mark 2 of the smallest unmarked elements with the smallest indices if they exist, the marked elements now are nums = [1,2,2,1,2,3,1]. The sum of unmarked elements is 0. Example 2: Input: nums = [1,4,2,3], queries = [[0,1]] Output: [7] Explanation: We do one query which is mark the element at index 0 and mark the smallest element among unmarked elements. The marked elements will be nums = [1,4,2,3], and the sum of unmarked elements is 4 + 3 = 7. Constraints: n == nums.length m == queries.length 1 <= m <= n <= 105 1 <= nums[i] <= 105 queries[i].length == 2 0 <= indexi, ki <= n - 1 Solutions Solution 1: Sorting + Simulation 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. Then, 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. Next, 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...
Sun, 31 Mar 2024 00:00:00 -0700
https://leetcode.ca/2024-03-31-3080-Mark-Elements-on-Array-by-Performing-Queries/
https://leetcode.ca/2024-03-31-3080-Mark-Elements-on-Array-by-Performing-Queries/3079 - Find the Sum of Encrypted Integers
Welcome to Subscribe On Youtube 3079. Find the Sum of Encrypted Integers Description You are given an integer array nums containing positive integers. We define a function encrypt such that encrypt(x) replaces every digit in x with the largest digit in x. For example, encrypt(523) = 555 and encrypt(213) = 333. Return the sum of encrypted elements. Example 1: Input: nums = [1,2,3] Output: 6 Explanation: The encrypted elements are [1,2,3]. The sum of encrypted elements is 1 + 2 + 3 == 6. Example 2: Input: nums = [10,21,31] Output: 66 Explanation: The encrypted elements are [11,22,33]. The sum of encrypted elements is 11 + 22 + 33 == 66. Constraints: 1 <= nums.length <= 50 1 <= nums[i] <= 1000 Solutions Solution 1: Simulation 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: We 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$. The 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)$. Java C++ Python Go TypeScript class Solution { public int sumOfEncryptedInt(int[] nums) { int ans = 0; for (int x : nums) { ans += encrypt(x); } return ans; } private int encrypt(int x) { int mx = 0, p = 0; for (; x > 0; x /= 10) { mx = Math.max(mx, x % 10); p = p * 10 + 1; } return mx * p; } } class Solution { public: int sumOfEncryptedInt(vector<int>& nums) { auto encrypt = [&](int x) { int mx = 0, p = 0; for (; x; x /= 10) { mx = max(mx, x % 10); p = p * 10 + 1; } return mx * p; }; int ans = 0; for (int x : nums) { ans += encrypt(x); } return ans; } }; class Solution: def sumOfEncryptedInt(self, nums: List[int]) -> int: def encrypt(x: int) -> int: mx = p = 0 while x: x, v = divmod(x, 10) mx = max(mx, v) p = p * 10 + 1 return mx * p return sum(encrypt(x) for x in nums) func sumOfEncryptedInt(nums []int) (ans int) { encrypt := func(x int) int { mx, p := 0, 0 for ; x > 0; x /= 10 { mx = max(mx, x%10) p = p*10 + 1 } return mx * p } for _, x := range nums { ans += encrypt(x) } return } function sumOfEncryptedInt(nums: number[]): number { const encrypt = (x: number): number => { let [mx, p] = [0,...
Sat, 30 Mar 2024 00:00:00 -0700
https://leetcode.ca/2024-03-30-3079-Find-the-Sum-of-Encrypted-Integers/
https://leetcode.ca/2024-03-30-3079-Find-the-Sum-of-Encrypted-Integers/3078 - Match Alphanumerical Pattern in Matrix I
Welcome to Subscribe On Youtube 3078. Match Alphanumerical Pattern in Matrix I Description You are given a 2D integer matrix board and a 2D character matrix pattern. Where 0 <= board[r][c] <= 9 and each element of pattern is either a digit or a lowercase English letter. Your task is to find a submatrix of board that matches pattern. An integer matrix part matches pattern if we can replace cells containing letters in pattern with some digits (each distinct letter with a unique digit) in such a way that the resulting matrix becomes identical to the integer matrix part. In other words, The matrices have identical dimensions. If pattern[r][c] is a digit, then part[r][c] must be the same digit. If pattern[r][c] is a letter x: For every pattern[i][j] == x, part[i][j] must be the same as part[r][c]. For every pattern[i][j] != x, part[i][j] must be different than part[r][c]. Return an array of length 2 containing the row number and column number of the upper-left corner of a submatrix of board which matches pattern. If there is more than one such submatrix, return the coordinates of the submatrix with the lowest row index, and in case there is still a tie, return the coordinates of the submatrix with the lowest column index. If there are no suitable answers, return [-1, -1]. Example 1: 1 2 2 2 2 3 2 3 3 a b b b Input: board = [[1,2,2],[2,2,3],[2,3,3]], pattern = ["ab","bb"] Output: [0,0] Explanation: If we consider this mapping: "a" -> 1 and "b" -> 2; the submatrix with the upper-left corner (0,0) is a match as outlined in the matrix above. Note that the submatrix with the upper-left corner (1,1) is also a match but since it comes after the other one, we return [0,0]. Example 2: 1 1 2 3 3 4 6 6 6 a b 6 6 Input: board = [[1,1,2],[3,3,4],[6,6,6]], pattern = ["ab","66"] Output: [1,1] Explanation: If we consider this mapping: "a" -> 3 and "b" -> 4; the submatrix with the upper-left corner (1,1) is a match as outlined in the matrix above. Note that since the corresponding values of "a" and "b" must differ, the submatrix with the upper-left corner (1,0) is not a match. Hence, we return [1,1]. Example 3: 1 2 2 1 x x Input: board = [[1,2],[2,1]], pattern = ["xx"] Output: [-1,-1] Explanation: Since the values of the matched submatrix must be the same, there is no match. Hence, we return [-1,-1]. Constraints: 1 <= board.length <= 50 1 <= board[i].length <= 50 0 <= board[i][j] <= 9 1 <= pattern.length <= 50 1 <= pattern[i].length <= 50 pattern[i][j] is either a digit represented as a string or a lowercase English letter. Solutions Solution 1: Enumeration 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. We can enumerate each possible sub-matrix’s top-left position $(i,...
Fri, 29 Mar 2024 00:00:00 -0700
https://leetcode.ca/2024-03-29-3078-Match-Alphanumerical-Pattern-in-Matrix-I/
https://leetcode.ca/2024-03-29-3078-Match-Alphanumerical-Pattern-in-Matrix-I/