Leetcodeleetcode.ca
https://leetcode.ca/
3228 - Maximum Number of Operations to Move Ones to the End
Welcome to Subscribe On Youtube 3228. Maximum Number of Operations to Move Ones to the End Description You are given a binary string s. You can perform the following operation on the string any number of times: Choose any index i from the string where i + 1 < s.length such that s[i] == '1' and s[i + 1] == '0'. Move the character s[i] to the right until it reaches the end of the string or another '1'. For example, for s = "010010", if we choose i = 1, the resulting string will be s = "000110". Return the maximum number of operations that you can perform. Example 1: Input: s = "1001101" Output: 4 Explanation: We can perform the following operations: Choose index i = 0. The resulting string is s = "0011101". Choose index i = 4. The resulting string is s = "0011011". Choose index i = 3. The resulting string is s = "0010111". Choose index i = 2. The resulting string is s = "0001111". Example 2: Input: s = "00111" Output: 0 Constraints: 1 <= s.length <= 105 s[i] is either '0' or '1'. Solutions Solution 1: Greedy We use a variable $\textit{ans}$ to record the answer and another variable $\textit{cnt}$ to count the current number of $1$s. Then, 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. Finally, we return the answer. 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 int maxOperations(String s) { int ans = 0, cnt = 0; int n = s.length(); for (int i = 0; i < n; ++i) { if (s.charAt(i) == '1') { ++cnt; } else if (i > 0 && s.charAt(i - 1) == '1') { ans += cnt; } } return ans; } } class Solution { public: int maxOperations(string s) { int ans = 0, cnt = 0; int n = s.size(); for (int i = 0; i < n; ++i) { if (s[i] == '1') { ++cnt; } else if (i && s[i - 1] == '1') { ans += cnt; } } return ans; } }; class Solution: def maxOperations(self, s: str) -> int: ans = cnt = 0 for i, c in enumerate(s): if c == "1": cnt += 1 elif i and s[i - 1] == "1": ans += cnt return ans func maxOperations(s string) (ans int) { cnt := 0 for i, c := range s { if c == '1' { cnt++ } else if i > 0 && s[i-1] == '1' { ans += cnt } } return } function maxOperations(s: string): number { let [ans, cnt] = [0, 0]; const n = s.length;...
Tue, 06 Aug 2024 00:00:00 -0700
https://leetcode.ca/2024-08-06-3228-Maximum-Number-of-Operations-to-Move-Ones-to-the-End/
https://leetcode.ca/2024-08-06-3228-Maximum-Number-of-Operations-to-Move-Ones-to-the-End/3227 - Vowels Game in a String
Welcome to Subscribe On Youtube 3227. Vowels Game in a String Description Alice and Bob are playing a game on a string. You are given a string s, Alice and Bob will take turns playing the following game where Alice starts first: On Alice's turn, she has to remove any non-empty substring from s that contains an odd number of vowels. On Bob's turn, he has to remove any non-empty substring from s that contains an even number of vowels. The first player who cannot make a move on their turn loses the game. We assume that both Alice and Bob play optimally. Return true if Alice wins the game, and false otherwise. The English vowels are: a, e, i, o, and u. Example 1: Input: s = "leetcoder" Output: true Explanation: Alice can win the game as follows: Alice plays first, she can delete the underlined substring in s = "leetcoder" which contains 3 vowels. The resulting string is s = "der". Bob plays second, he can delete the underlined substring in s = "der" which contains 0 vowels. The resulting string is s = "er". Alice plays third, she can delete the whole string s = "er" which contains 1 vowel. Bob plays fourth, since the string is empty, there is no valid play for Bob. So Alice wins the game. Example 2: Input: s = "bbcd" Output: false Explanation: There is no valid play for Alice in her first turn, so Alice loses the game. Constraints: 1 <= s.length <= 105 s consists only of lowercase English letters. Solutions Solution 1: Brain Teaser Let’s denote the number of vowels in the string as $k$. If $k = 0$, meaning there are no vowels in the string, then Little Red cannot remove any substring, and Little Ming wins directly. If $k$ is odd, then Little Red can remove the entire string, resulting in a direct win for Little Red. If $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. In conclusion, if the string contains vowels, then Little Red wins; otherwise, Little Ming wins. 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 boolean doesAliceWin(String s) { for (int i = 0; i < s.length(); ++i) { if ("aeiou".indexOf(s.charAt(i)) != -1) { return true; } } return false; } } class Solution { public: bool doesAliceWin(string s) { string vowels = "aeiou"; for (char c : s) { if (vowels.find(c) != string::npos) { return true; } } return false; } }; class Solution: def doesAliceWin(self, s: str) -> bool: vowels = set("aeiou") return any(c in vowels for c in s) func doesAliceWin(s string) bool { vowels := "aeiou" for _, c := range s { if strings.ContainsRune(vowels, c) { return true...
Mon, 05 Aug 2024 00:00:00 -0700
https://leetcode.ca/2024-08-05-3227-Vowels-Game-in-a-String/
https://leetcode.ca/2024-08-05-3227-Vowels-Game-in-a-String/3226 - Number of Bit Changes to Make Two Integers Equal
Welcome to Subscribe On Youtube
3226. Number of Bit Changes to Make Two Integers Equal
Description
You are given two positive integers n and k.
You can choose any bit in the binary representation of n that is equal to 1 and change it to 0.
Return the number of changes needed to make n equal to k. If it is impossible, return -1.
Example 1:
Input: n = 13, k = 4
Output: 2
Explanation:
Initially, the binary representations of n and k are n = (1101)2 and k = (0100)2.
We can change the first and fourth bits of n. The resulting integer is n = (0100)2 = k.
Example 2:
Input: n = 21, k = 21
Output: 0
Explanation:
n and k are already equal, so no changes are needed.
Example 3:
Input: n = 14, k = 13
Output: -1
Explanation:
It is not possible to make n equal to k.
Constraints:
1 <= n, k <= 106
Solutions
Solution 1: Bit Manipulation
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$.
The time complexity is $O(\log n)$, and the space complexity is $O(1)$.
Java
C++
Python
Go
TypeScript
class Solution {
public int minChanges(int n, int k) {
return (n & k) != k ? -1 : Integer.bitCount(n ^ k);
}
}
class Solution {
public:
int minChanges(int n, int k) {
return (n & k) != k ? -1 : __builtin_popcount(n ^ k);
}
};
class Solution:
def minChanges(self, n: int, k: int) -> int:
return -1 if n & k != k else (n ^ k).bit_count()
func minChanges(n int, k int) int {
if n&k != k {
return -1
}
return bits.OnesCount(uint(n ^ k))
}
function minChanges(n: number, k: number): number {
return (n & k) !== k ? -1 : bitCount(n ^ k);
}
function bitCount(i: number): number {
i = i - ((i >>> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
i = (i + (i >>> 4)) & 0x0f0f0f0f;
i = i + (i >>> 8);
i = i + (i >>> 16);
return i & 0x3f;
}
All Problems
All Solutions
Sun, 04 Aug 2024 00:00:00 -0700
https://leetcode.ca/2024-08-04-3226-Number-of-Bit-Changes-to-Make-Two-Integers-Equal/
https://leetcode.ca/2024-08-04-3226-Number-of-Bit-Changes-to-Make-Two-Integers-Equal/3225 - Maximum Score From Grid Operations
Welcome to Subscribe On Youtube
3225. Maximum Score From Grid Operations
Description
You are given a 2D matrix grid of size n x n. Initially, all cells of the grid are colored white. In one operation, you can select any cell of indices (i, j), and color black all the cells of the jth column starting from the top row down to the ith row.
The grid score is the sum of all grid[i][j] such that cell (i, j) is white and it has a horizontally adjacent black cell.
Return the maximum score that can be achieved after some number of operations.
Example 1:
Input: grid = [[0,0,0,0,0],[0,0,3,0,0],[0,1,0,0,0],[5,0,0,3,0],[0,0,0,0,2]]
Output: 11
Explanation:
In the first operation, we color all cells in column 1 down to row 3, and in the second operation, we color all cells in column 4 down to the last row. The score of the resulting grid is grid[3][0] + grid[1][2] + grid[3][3] which is equal to 11.
Example 2:
Input: grid = [[10,9,0,0,15],[7,1,0,8,0],[5,20,0,11,0],[0,0,0,1,2],[8,12,1,10,3]]
Output: 94
Explanation:
We perform operations on 1, 2, and 3 down to rows 1, 4, and 0, respectively. The score of the resulting grid is grid[0][0] + grid[1][0] + grid[2][1] + grid[4][1] + grid[1][3] + grid[2][3] + grid[3][3] + grid[4][3] + grid[0][4] which is equal to 94.
Constraints:
1 <= n == grid.length <= 100
n == grid[i].length
0 <= grid[i][j] <= 109
Solutions
Solution 1
All Problems
All Solutions
Sat, 03 Aug 2024 00:00:00 -0700
https://leetcode.ca/2024-08-03-3225-Maximum-Score-From-Grid-Operations/
https://leetcode.ca/2024-08-03-3225-Maximum-Score-From-Grid-Operations/3224 - Minimum Array Changes to Make Differences Equal
Welcome to Subscribe On Youtube 3224. Minimum Array Changes to Make Differences Equal Description You are given an integer array nums of size n where n is even, and an integer k. You can perform some changes on the array, where in one change you can replace any element in the array with any integer in the range from 0 to k. You need to perform some changes (possibly none) such that the final array satisfies the following condition: There exists an integer X such that abs(a[i] - a[n - i - 1]) = X for all (0 <= i < n). Return the minimum number of changes required to satisfy the above condition. Example 1: Input: nums = [1,0,1,2,4,3], k = 4 Output: 2 Explanation: We can perform the following changes: Replace nums[1] by 2. The resulting array is nums = [1,2,1,2,4,3]. Replace nums[3] by 3. The resulting array is nums = [1,2,1,3,4,3]. The integer X will be 2. Example 2: Input: nums = [0,1,2,3,3,6,5,4], k = 6 Output: 2 Explanation: We can perform the following operations: Replace nums[3] by 0. The resulting array is nums = [0,1,2,0,3,6,5,4]. Replace nums[4] by 4. The resulting array is nums = [0,1,2,0,4,6,5,4]. The integer X will be 4. Constraints: 2 <= n == nums.length <= 105 n is even. 0 <= nums[i] <= k <= 105 Solutions Solution 1: Difference Array Assume that in the final array, the difference between the pair $\textit{nums}[i]$ and $\textit{nums}[n-i-1]$ is $s$. Let’s denote $x$ as the smaller value between $\textit{nums}[i]$ and $\textit{nums}[n-i-1]$, and $y$ as the larger value. For each pair of numbers, we have the following scenarios: If no change is needed, then $y - x = s$. 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$. If two changes are made, then $s > \max(y, k - x)$. That is: In the range $[0, y-x-1]$, $1$ change is needed. At $[y-x]$, no change is needed. In the range $[y-x+1, \max(y, k-x)]$, $1$ change is needed. In the range $[\max(y, k-x)+1, k]$, $2$ changes are needed. We enumerate each pair of numbers and use a difference array to update the number of changes needed in different ranges for each pair. Finally, we find the minimum value among the prefix sums from the difference array, which is the minimum number of changes needed. The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\textit{nums}$. Similar problems: 1674. Minimum Moves to Make Array Complementary Java C++ Python Go TypeScript class Solution { public int minChanges(int[] nums, int k) { int[] d = new int[k + 2]; int n = nums.length; for (int i = 0; i < n / 2; ++i) { int x = Math.min(nums[i], nums[n - i - 1]); int y = Math.max(nums[i], nums[n - i - 1]); d[0] += 1; d[y - x] -=...
Fri, 02 Aug 2024 00:00:00 -0700
https://leetcode.ca/2024-08-02-3224-Minimum-Array-Changes-to-Make-Differences-Equal/
https://leetcode.ca/2024-08-02-3224-Minimum-Array-Changes-to-Make-Differences-Equal/3223 - Minimum Length of String After Operations
Welcome to Subscribe On Youtube 3223. Minimum Length of String After Operations Description You are given a string s. You can perform the following process on s any number of times: Choose an index i in the string such that there is at least one character to the left of index i that is equal to s[i], and at least one character to the right that is also equal to s[i]. Delete the closest character to the left of index i that is equal to s[i]. Delete the closest character to the right of index i that is equal to s[i]. Return the minimum length of the final string s that you can achieve. Example 1: Input: s = "abaacbcbb" Output: 5 Explanation: We do the following operations: Choose index 2, then remove the characters at indices 0 and 3. The resulting string is s = "bacbcbb". Choose index 3, then remove the characters at indices 0 and 5. The resulting string is s = "acbcb". Example 2: Input: s = "aa" Output: 2 Explanation: We cannot perform any operations, so we return the length of the original string. Constraints: 1 <= s.length <= 2 * 105 s consists only of lowercase English letters. Solutions Solution 1: Counting 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. 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 size of the character set, which is $26$ in this problem. Java C++ Python Go TypeScript class Solution { public int minimumLength(String s) { int[] cnt = new int[26]; for (int i = 0; i < s.length(); ++i) { ++cnt[s.charAt(i) - 'a']; } int ans = 0; for (int x : cnt) { if (x > 0) { ans += x % 2 == 1 ? 1 : 2; } } return ans; } } class Solution { public: int minimumLength(string s) { int cnt[26]{}; for (char& c : s) { ++cnt[c - 'a']; } int ans = 0; for (int x : cnt) { if (x) { ans += x % 2 ? 1 : 2; } } return ans; } }; class Solution: def minimumLength(self, s: str) -> int: cnt = Counter(s) return sum(1 if x & 1 else 2 for x in cnt.values()) func minimumLength(s string) (ans int) { cnt := [26]int{} for _, c := range s { cnt[c-'a']++ } for _, x := range cnt { if x > 0 { if x&1 == 1 { ans += 1 } else { ans += 2 } } } return } function minimumLength(s: string): number...
Thu, 01 Aug 2024 00:00:00 -0700
https://leetcode.ca/2024-08-01-3223-Minimum-Length-of-String-After-Operations/
https://leetcode.ca/2024-08-01-3223-Minimum-Length-of-String-After-Operations/3222 - Find the Winning Player in Coin Game
Welcome to Subscribe On Youtube
3222. Find the Winning Player in Coin Game
Description
You are given two positive integers x and y, denoting the number of coins with values 75 and 10 respectively.
Alice and Bob are playing a game. Each turn, starting with Alice, the player must pick up coins with a total value 115. If the player is unable to do so, they lose the game.
Return the name of the player who wins the game if both players play optimally.
Example 1:
Input: x = 2, y = 7
Output: "Alice"
Explanation:
The game ends in a single turn:
Alice picks 1 coin with a value of 75 and 4 coins with a value of 10.
Example 2:
Input: x = 4, y = 11
Output: "Bob"
Explanation:
The game ends in 2 turns:
Alice picks 1 coin with a value of 75 and 4 coins with a value of 10.
Bob picks 1 coin with a value of 75 and 4 coins with a value of 10.
Constraints:
1 <= x, y <= 100
Solutions
Solution 1: Mathematics
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.
If $x > 0$ and $y \geq 4$, then Alice can continue the operation, and Bob loses, return “Alice”; otherwise, return “Bob”.
The time complexity is $O(1)$, and the space complexity is $O(1)$.
Java
C++
Python
Go
TypeScript
class Solution {
public String losingPlayer(int x, int y) {
int k = Math.min(x / 2, y / 8);
x -= k * 2;
y -= k * 8;
return x > 0 && y >= 4 ? "Alice" : "Bob";
}
}
class Solution {
public:
string losingPlayer(int x, int y) {
int k = min(x / 2, y / 8);
x -= k * 2;
y -= k * 8;
return x && y >= 4 ? "Alice" : "Bob";
}
};
class Solution:
def losingPlayer(self, x: int, y: int) -> str:
k = min(x // 2, y // 8)
x -= k * 2
y -= k * 8
return "Alice" if x and y >= 4 else "Bob"
func losingPlayer(x int, y int) string {
k := min(x/2, y/8)
x -= 2 * k
y -= 8 * k
if x > 0 && y >= 4 {
return "Alice"
}
return "Bob"
}
function losingPlayer(x: number, y: number): string {
const k = Math.min((x / 2) | 0, (y / 8) | 0);
x -= k * 2;
y -= k * 8;
return x && y >= 4 ? 'Alice' : 'Bob';
}
All Problems
All Solutions
Wed, 31 Jul 2024 00:00:00 -0700
https://leetcode.ca/2024-07-31-3222-Find-the-Winning-Player-in-Coin-Game/
https://leetcode.ca/2024-07-31-3222-Find-the-Winning-Player-in-Coin-Game/3221 - Maximum Array Hopping Score II
Welcome to Subscribe On Youtube 3221. Maximum Array Hopping Score II 🔒 Description Given an array nums, you have to get the maximum score starting from index 0 and hopping until you reach the last element of the array. In each hop, you can jump from index i to an index j > i, and you get a score of (j - i) * nums[j]. Return the maximum score you can get. Example 1: Input: nums = [1,5,8] Output: 16 Explanation: There are two possible ways to reach the last element: 0 -> 1 -> 2 with a score of (1 - 0) * 5 + (2 - 1) * 8 = 13. 0 -> 2 with a score of (2 - 0) * 8 = 16. Example 2: Input: nums = [4,5,2,8,9,1,3] Output: 42 Explanation: We can do the hopping 0 -> 4 -> 6 with a score of (4 - 0) * 9 + (6 - 4) * 3 = 42. Constraints: 2 <= nums.length <= 105 1 <= nums[i] <= 105 Solutions Solution 1: Monotonic Stack 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. Therefore, 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. Next, 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$. Java C++ Python Go TypeScript class Solution { public long maxScore(int[] nums) { Deque<Integer> stk = new ArrayDeque<>(); for (int i = 0; i < nums.length; ++i) { while (!stk.isEmpty() && nums[stk.peek()] <= nums[i]) { stk.pop(); } stk.push(i); } long ans = 0, i = 0; while (!stk.isEmpty()) { int j = stk.pollLast(); ans += (j - i) * nums[j]; i = j; } return ans; } } class Solution { public: long long maxScore(vector<int>& nums) { vector<int> stk; for (int i = 0; i < nums.size(); ++i) { while (stk.size() && nums[stk.back()] <= nums[i]) { stk.pop_back(); } stk.push_back(i); } long long ans = 0, i = 0; for (int j : stk) { ans += (j - i) * nums[j]; i = j; } return ans; } }; class Solution: def maxScore(self, nums: List[int]) -> int: stk = [] for i, x in enumerate(nums): while stk and nums[stk[-1]] <= x: stk.pop() stk.append(i) ans = i = 0 for j in stk: ans += nums[j] * (j -...
Tue, 30 Jul 2024 00:00:00 -0700
https://leetcode.ca/2024-07-30-3221-Maximum-Array-Hopping-Score-II/
https://leetcode.ca/2024-07-30-3221-Maximum-Array-Hopping-Score-II/3220 - Odd and Even Transactions
Welcome to Subscribe On Youtube
3220. Odd and Even Transactions
Description
Table: transactions
+++
\| Column Name \| Type \|
+++
\| transaction_id \| int \|
\| amount \| int \|
\| transaction_date \| date \|
+++
The transactions_id column uniquely identifies each row in this table.
Each row of this table contains the transaction id, amount and transaction date.
Write a solution to find the sum of amounts for odd and even transactions for each day. If there are no odd or even transactions for a specific date, display as 0.
Return the result table ordered by transaction_date in ascending order.
The result format is in the following example.
Example:
Input:
transactions table:
+-+--++
\| 1 \| 150 \| 2024-07-01 \|
\| 2 \| 200 \| 2024-07-01 \|
\| 3 \| 75 \| 2024-07-01 \|
\| 4 \| 300 \| 2024-07-02 \|
\| 5 \| 50 \| 2024-07-02 \|
\| 6 \| 120 \| 2024-07-03 \|
++++----+
Explanation:
For transaction dates:
2024-07-01:
Sum of amounts for odd transactions: 75
Sum of amounts for even transactions: 150 + 200 = 350
2024-07-02:
Sum of amounts for odd transactions: 0
Sum of amounts for even transactions: 300 + 50 = 350
2024-07-03:
Sum of amounts for odd transactions: 0
Sum of amounts for even transactions: 120
Note: The output table is ordered by transaction_date in ascending order.
Solutions
Solution 1: Grouping and Summing
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.
Python
SQL
import pandas as pd
def sum_daily_odd_even(transactions: pd.DataFrame) -> pd.DataFrame:
transactions["odd_sum"] = transactions["amount"].where(
transactions["amount"] % 2 == 1, 0
)
transactions["even_sum"] = transactions["amount"].where(
transactions["amount"] % 2 == 0, 0
)
result = (
transactions.groupby("transaction_date")
.agg(odd_sum=("odd_sum", "sum"), even_sum=("even_sum", "sum"))
.reset_index()
)
result = result.sort_values("transaction_date")
return result
# Write your MySQL query statement below
SELECT
transaction_date,
SUM(IF(amount % 2 = 1, amount, 0)) AS odd_sum,
SUM(IF(amount % 2 = 0, amount, 0)) AS even_sum
FROM transactions
GROUP BY 1
ORDER BY 1;
All Problems
All Solutions
Mon, 29 Jul 2024 00:00:00 -0700
https://leetcode.ca/2024-07-29-3220-Odd-and-Even-Transactions/
https://leetcode.ca/2024-07-29-3220-Odd-and-Even-Transactions/3219 - Minimum Cost for Cutting Cake II
Welcome to Subscribe On Youtube 3219. Minimum Cost for Cutting Cake II Description There is an m x n cake that needs to be cut into 1 x 1 pieces. You are given integers m, n, and two arrays: horizontalCut of size m - 1, where horizontalCut[i] represents the cost to cut along the horizontal line i. verticalCut of size n - 1, where verticalCut[j] represents the cost to cut along the vertical line j. In one operation, you can choose any piece of cake that is not yet a 1 x 1 square and perform one of the following cuts: Cut along a horizontal line i at a cost of horizontalCut[i]. Cut along a vertical line j at a cost of verticalCut[j]. After the cut, the piece of cake is divided into two distinct pieces. The cost of a cut depends only on the initial cost of the line and does not change. Return the minimum total cost to cut the entire cake into 1 x 1 pieces. Example 1: Input: m = 3, n = 2, horizontalCut = [1,3], verticalCut = [5] Output: 13 Explanation: Perform a cut on the vertical line 0 with cost 5, current total cost is 5. Perform a cut on the horizontal line 0 on 3 x 1 subgrid with cost 1. Perform a cut on the horizontal line 0 on 3 x 1 subgrid with cost 1. Perform a cut on the horizontal line 1 on 2 x 1 subgrid with cost 3. Perform a cut on the horizontal line 1 on 2 x 1 subgrid with cost 3. The total cost is 5 + 1 + 1 + 3 + 3 = 13. Example 2: Input: m = 2, n = 2, horizontalCut = [7], verticalCut = [4] Output: 15 Explanation: Perform a cut on the horizontal line 0 with cost 7. Perform a cut on the vertical line 0 on 1 x 2 subgrid with cost 4. Perform a cut on the vertical line 0 on 1 x 2 subgrid with cost 4. The total cost is 7 + 4 + 4 = 15. Constraints: 1 <= m, n <= 105 horizontalCut.length == m - 1 verticalCut.length == n - 1 1 <= horizontalCut[i], verticalCut[i] <= 103 Solutions Solution 1: Greedy + Two Pointers 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. Therefore, 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. Each 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...
Sun, 28 Jul 2024 00:00:00 -0700
https://leetcode.ca/2024-07-28-3219-Minimum-Cost-for-Cutting-Cake-II/
https://leetcode.ca/2024-07-28-3219-Minimum-Cost-for-Cutting-Cake-II/3218 - Minimum Cost for Cutting Cake I
Welcome to Subscribe On Youtube 3218. Minimum Cost for Cutting Cake I Description There is an m x n cake that needs to be cut into 1 x 1 pieces. You are given integers m, n, and two arrays: horizontalCut of size m - 1, where horizontalCut[i] represents the cost to cut along the horizontal line i. verticalCut of size n - 1, where verticalCut[j] represents the cost to cut along the vertical line j. In one operation, you can choose any piece of cake that is not yet a 1 x 1 square and perform one of the following cuts: Cut along a horizontal line i at a cost of horizontalCut[i]. Cut along a vertical line j at a cost of verticalCut[j]. After the cut, the piece of cake is divided into two distinct pieces. The cost of a cut depends only on the initial cost of the line and does not change. Return the minimum total cost to cut the entire cake into 1 x 1 pieces. Example 1: Input: m = 3, n = 2, horizontalCut = [1,3], verticalCut = [5] Output: 13 Explanation: Perform a cut on the vertical line 0 with cost 5, current total cost is 5. Perform a cut on the horizontal line 0 on 3 x 1 subgrid with cost 1. Perform a cut on the horizontal line 0 on 3 x 1 subgrid with cost 1. Perform a cut on the horizontal line 1 on 2 x 1 subgrid with cost 3. Perform a cut on the horizontal line 1 on 2 x 1 subgrid with cost 3. The total cost is 5 + 1 + 1 + 3 + 3 = 13. Example 2: Input: m = 2, n = 2, horizontalCut = [7], verticalCut = [4] Output: 15 Explanation: Perform a cut on the horizontal line 0 with cost 7. Perform a cut on the vertical line 0 on 1 x 2 subgrid with cost 4. Perform a cut on the vertical line 0 on 1 x 2 subgrid with cost 4. The total cost is 7 + 4 + 4 = 15. Constraints: 1 <= m, n <= 20 horizontalCut.length == m - 1 verticalCut.length == n - 1 1 <= horizontalCut[i], verticalCut[i] <= 103 Solutions Solution 1: Greedy + Two Pointers 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. Therefore, 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. Each 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...
Sat, 27 Jul 2024 00:00:00 -0700
https://leetcode.ca/2024-07-27-3218-Minimum-Cost-for-Cutting-Cake-I/
https://leetcode.ca/2024-07-27-3218-Minimum-Cost-for-Cutting-Cake-I/3217 - Delete Nodes From Linked List Present in Array
Welcome to Subscribe On Youtube 3217. Delete Nodes From Linked List Present in Array Description You are given an array of integers nums and the head of a linked list. Return the head of the modified linked list after removing all nodes from the linked list that have a value that exists in nums. Example 1: Input: nums = [1,2,3], head = [1,2,3,4,5] Output: [4,5] Explanation: Remove the nodes with values 1, 2, and 3. Example 2: Input: nums = [1], head = [1,2,1,2,1,2] Output: [2,2,2] Explanation: Remove the nodes with value 1. Example 3: Input: nums = [5], head = [1,2,3,4] Output: [1,2,3,4] Explanation: No node has value 5. Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 105 All elements in nums are unique. The number of nodes in the given list is in the range [1, 105]. 1 <= Node.val <= 105 The input is generated such that there is at least one node in the linked list that has a value not present in nums. Solutions Solution 1: Hash Table 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}$. Next, 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. Finally, we return the next node of the dummy node $\textit{dummy}$. The 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}$. Java C++ Python Go TypeScript /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode modifiedList(int[] nums, ListNode head) { Set<Integer> s = new HashSet<>(); for (int x : nums) { s.add(x); } ListNode dummy = new ListNode(0, head); for (ListNode pre = dummy; pre.next != null;) { if (s.contains(pre.next.val)) { pre.next = pre.next.next; } else { pre = pre.next; } } return dummy.next; } } /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* modifiedList(vector<int>& nums, ListNode* head) { unordered_set<int> s(nums.begin(), nums.end()); ListNode* dummy = new ListNode(0, head); for (ListNode* pre = dummy; pre->next;) { if (s.count(pre->next->val)) { pre->next = pre->next->next; } else { pre = pre->next; } } return dummy->next; } }; # Definition for singly-linked list. # class...
Fri, 26 Jul 2024 00:00:00 -0700
https://leetcode.ca/2024-07-26-3217-Delete-Nodes-From-Linked-List-Present-in-Array/
https://leetcode.ca/2024-07-26-3217-Delete-Nodes-From-Linked-List-Present-in-Array/3216 - Lexicographically Smallest String After a Swap
Welcome to Subscribe On Youtube 3216. Lexicographically Smallest String After a Swap Description Given a string s containing only digits, return the lexicographically smallest string that can be obtained after swapping adjacent digits in s with the same parity at most once. Digits have the same parity if both are odd or both are even. For example, 5 and 9, as well as 2 and 4, have the same parity, while 6 and 9 do not. Example 1: Input: s = "45320" Output: "43520" Explanation: s[1] == '5' and s[2] == '3' both have the same parity, and swapping them results in the lexicographically smallest string. Example 2: Input: s = "001" Output: "001" Explanation: There is no need to perform a swap because s is already the lexicographically smallest. Constraints: 2 <= s.length <= 100 s consists only of digits. Solutions Solution 1: Greedy + Simulation 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. After 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. The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the string $\textit{s}$. Java C++ Python Go TypeScript class Solution { public String getSmallestString(String s) { char[] cs = s.toCharArray(); int n = cs.length; for (int i = 1; i < n; ++i) { char a = cs[i - 1], b = cs[i]; if (a > b && a % 2 == b % 2) { cs[i] = a; cs[i - 1] = b; return new String(cs); } } return s; } } class Solution { public: string getSmallestString(string s) { int n = s.length(); for (int i = 1; i < n; ++i) { char a = s[i - 1], b = s[i]; if (a > b && a % 2 == b % 2) { s[i - 1] = b; s[i] = a; break; } } return s; } }; class Solution: def getSmallestString(self, s: str) -> str: for i, (a, b) in enumerate(pairwise(map(ord, s))): if (a + b) % 2 == 0 and a > b: return s[:i] + s[i + 1] + s[i] + s[i + 2 :] return s func getSmallestString(s string) string { cs := []byte(s) n := len(cs) for i := 1; i < n; i++ { a, b := cs[i-1], cs[i] if a > b && a%2 == b%2 { cs[i-1], cs[i] = b, a return string(cs) } } return s } function getSmallestString(s: string): string { const n = s.length; const cs: string[] = s.split(''); for (let i = 1; i < n; ++i) { const a = cs[i - 1]; const...
Thu, 25 Jul 2024 00:00:00 -0700
https://leetcode.ca/2024-07-25-3216-Lexicographically-Smallest-String-After-a-Swap/
https://leetcode.ca/2024-07-25-3216-Lexicographically-Smallest-String-After-a-Swap/3215 - Count Triplets with Even XOR Set Bits II
Welcome to Subscribe On Youtube 3215. Count Triplets with Even XOR Set Bits II 🔒 Description Given three integer arrays a, b, and c, return the number of triplets (a[i], b[j], c[k]), such that the bitwise XOR between the elements of each triplet has an even number of set bits. Example 1: Input: a = [1], b = [2], c = [3] Output: 1 Explanation: The only triplet is (a[0], b[0], c[0]) and their XOR is: 1 XOR 2 XOR 3 = 002. Example 2: Input: a = [1,1], b = [2,3], c = [1,5] Output: 4 Explanation: Consider these four triplets: (a[0], b[1], c[0]): 1 XOR 3 XOR 1 = 0112 (a[1], b[1], c[0]): 1 XOR 3 XOR 1 = 0112 (a[0], b[0], c[1]): 1 XOR 2 XOR 5 = 1102 (a[1], b[0], c[1]): 1 XOR 2 XOR 5 = 1102 Constraints: 1 <= a.length, b.length, c.length <= 105 0 <= a[i], b[i], c[i] <= 109 Solutions Solution 1: Bit Manipulation 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. We 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. Then, 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. Finally, return the answer. The time complexity is $O(n)$, where $n$ is the length of arrays a, b, c. The space complexity is $O(1)$. Java C++ Python Go TypeScript class Solution { public long tripletCount(int[] a, int[] b, int[] c) { int[] cnt1 = new int[2]; int[] cnt2 = new int[2]; int[] cnt3 = new int[2]; for (int x : a) { ++cnt1[Integer.bitCount(x) & 1]; } for (int x : b) { ++cnt2[Integer.bitCount(x) & 1]; } for (int x : c) { ++cnt3[Integer.bitCount(x) & 1]; } long ans = 0; for (int i = 0; i < 2; ++i) { for (int j = 0; j < 2; ++j) { for (int k = 0; k < 2; ++k) { if ((i + j + k) % 2 == 0) { ans += 1L * cnt1[i] * cnt2[j] * cnt3[k]; } } } } return ans; } } class Solution { public: long long tripletCount(vector<int>& a, vector<int>& b, vector<int>& c) { int cnt1[2]{}; int cnt2[2]{}; int cnt3[2]{}; for (int x : a) { ++cnt1[__builtin_popcount(x) & 1]; } for (int x : b) { ++cnt2[__builtin_popcount(x) & 1]; } for (int x : c) { ++cnt3[__builtin_popcount(x) & 1];...
Wed, 24 Jul 2024 00:00:00 -0700
https://leetcode.ca/2024-07-24-3215-Count-Triplets-with-Even-XOR-Set-Bits-II/
https://leetcode.ca/2024-07-24-3215-Count-Triplets-with-Even-XOR-Set-Bits-II/3214 - Year on Year Growth Rate
Welcome to Subscribe On Youtube
3214. Year on Year Growth Rate 🔒
Description
Table: user_transactions
++-+
\| transaction_id \| integer \|
\| product_id \| integer \|
\| spend \| decimal \|
\| transaction_date \| datetime \|
++-+++
\| transaction_id \| product_id \| spend \| transaction_date \|
++-+++
Output:
+++-+-+-+
\| 2019 \| 123424 \| 1500.60 \| NULL \| NULL \|
\| 2020 \| 123424 \| 1000.20 \| 1500.60 \| -33.35 \|
\| 2021 \| 123424 \| 1246.44 \| 1000.20 \| 24.62 \|
\| 2022 \| 123424 \| 2145.32 \| 1246.44 \| 72.12 \|
+++-+----+
Explanation:
For product ID 123424:
In 2019:
Current year's spend is 1500.60
No previous year's spend recorded
YoY growth rate: NULL
In 2020:
Current year's spend is 1000.20
Previous year's spend is 1500.60
YoY growth rate: ((1000.20 - 1500.60) / 1500.60) * 100 = -33.35%
In 2021:
Current year's spend is 1246.44
Previous year's spend is 1000.20
YoY growth rate: ((1246.44 - 1000.20) / 1000.20) * 100 = 24.62%
In 2022:
Current year's spend is 2145.32
Previous year's spend is 1246.44
YoY growth rate: ((2145.32 - 1246.44) / 1246.44) * 100 = 72.12%
Note: Output table is ordered by product_id and year in ascending order.
</div>
Solutions
Solution 1: Grouping Statistics + Left Join
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.
SQL
# Write your MySQL query statement below
WITH
T AS (
SELECT product_id, YEAR(transaction_date) year, SUM(spend) curr_year_spend
FROM user_transactions
GROUP BY 1, 2
),
S AS (
SELECT t1.year, t1.product_id, t1.curr_year_spend, t2.curr_year_spend prev_year_spend
FROM
T t1
LEFT JOIN T t2 ON t1.product_id = t2.product_id AND t1.year = t2.year + 1
)
SELECT
*,
ROUND((curr_year_spend - prev_year_spend) / prev_year_spend * 100, 2) yoy_rate
FROM S
ORDER BY 2, 1;
All Problems
All Solutions
Tue, 23 Jul 2024 00:00:00 -0700
https://leetcode.ca/2024-07-23-3214-Year-on-Year-Growth-Rate/
https://leetcode.ca/2024-07-23-3214-Year-on-Year-Growth-Rate/3213 - Construct String with Minimum Cost
Welcome to Subscribe On Youtube 3213. Construct String with Minimum Cost Description You are given a string target, an array of strings words, and an integer array costs, both arrays of the same length. Imagine an empty string s. You can perform the following operation any number of times (including zero): Choose an index i in the range [0, words.length - 1]. Append words[i] to s. The cost of operation is costs[i]. Return the minimum cost to make s equal to target. If it's not possible, return -1. Example 1: Input: target = "abcdef", words = ["abdef","abc","d","def","ef"], costs = [100,1,1,10,5] Output: 7 Explanation: The minimum cost can be achieved by performing the following operations: Select index 1 and append "abc" to s at a cost of 1, resulting in s = "abc". Select index 2 and append "d" to s at a cost of 1, resulting in s = "abcd". Select index 4 and append "ef" to s at a cost of 5, resulting in s = "abcdef". Example 2: Input: target = "aaaa", words = ["z","zz","zzz"], costs = [1,10,100] Output: -1 Explanation: It is impossible to make s equal to target, so we return -1. Constraints: 1 <= target.length <= 5 * 104 1 <= words.length == costs.length <= 5 * 104 1 <= words[i].length <= target.length The total sum of words[i].length is less than or equal to 5 * 104. target and words[i] consist only of lowercase English letters. 1 <= costs[i] <= 104 Solutions Solution 1: String Hashing + Dynamic Programming + Enumerating Length 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}$. For 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: \[f[i] = \min(f[i], f[i - j] + \textit{cost}[k])\] where $\textit{cost}[k]$ represents the minimum cost of a word of length $j$ whose hash value matches $\textit{target}[i - j + 1, i]$. The 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}$. Java C++ Python Go class Hashing { private final long[] p; private final long[] h; private final long mod; public Hashing(String word, long base, int mod) { int n = word.length(); p = new long[n + 1]; h = new long[n + 1]; p[0] = 1; this.mod = mod; for (int i = 1; i <= n; i++) { p[i] = p[i - 1] * base % mod; h[i] = (h[i - 1] * base +...
Mon, 22 Jul 2024 00:00:00 -0700
https://leetcode.ca/2024-07-22-3213-Construct-String-with-Minimum-Cost/
https://leetcode.ca/2024-07-22-3213-Construct-String-with-Minimum-Cost/3212 - Count Submatrices With Equal Frequency of X and Y
Welcome to Subscribe On Youtube 3212. Count Submatrices With Equal Frequency of X and Y Description Given a 2D character matrix grid, where grid[i][j] is either 'X', 'Y', or '.', return the number of submatrices that contain: grid[0][0] an equal frequency of 'X' and 'Y'. at least one 'X'. Example 1: Input: grid = [["X","Y","."],["Y",".","."]] Output: 3 Explanation: Example 2: Input: grid = [["X","X"],["X","Y"]] Output: 0 Explanation: No submatrix has an equal frequency of 'X' and 'Y'. Example 3: Input: grid = [[".","."],[".","."]] Output: 0 Explanation: No submatrix has at least one 'X'. Constraints: 1 <= grid.length, grid[i].length <= 1000 grid[i][j] is either 'X', 'Y', or '.'. Solutions Solution 1: 2D Prefix Sum 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. After traversing all positions, return the answer. The 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. Java C++ Python Go TypeScript class Solution { public int numberOfSubmatrices(char[][] grid) { int m = grid.length, n = grid[0].length; int[][][] s = new int[m + 1][n + 1][2]; int ans = 0; for (int i = 1; i <= m; ++i) { for (int j = 1; j <= n; ++j) { s[i][j][0] = s[i - 1][j][0] + s[i][j - 1][0] - s[i - 1][j - 1][0] + (grid[i - 1][j - 1] == 'X' ? 1 : 0); s[i][j][1] = s[i - 1][j][1] + s[i][j - 1][1] - s[i - 1][j - 1][1] + (grid[i - 1][j - 1] == 'Y' ? 1 : 0); if (s[i][j][0] > 0 && s[i][j][0] == s[i][j][1]) { ++ans; } } } return ans; } } class Solution { public: int numberOfSubmatrices(vector<vector<char>>& grid) { int m = grid.size(), n = grid[0].size(); vector<vector<vector<int>>> s(m + 1, vector<vector<int>>(n + 1, vector<int>(2))); int ans = 0; for (int i = 1; i <= m; ++i) { for (int j = 1; j <= n; ++j) { s[i][j][0] = s[i - 1][j][0] + s[i][j - 1][0] - s[i - 1][j - 1][0] + (grid[i - 1][j - 1] == 'X' ? 1 : 0); s[i][j][1] = s[i - 1][j][1] + s[i][j - 1][1] - s[i - 1][j - 1][1] + (grid[i - 1][j - 1] == 'Y' ? 1 : 0); if (s[i][j][0] > 0 && s[i][j][0] == s[i][j][1]) { ++ans; } } } return ans; } }; class Solution: def numberOfSubmatrices(self, grid: List[List[str]]) -> int: m, n = len(grid), len(grid[0]) s = [[[0] * 2 for _ in range(n + 1)] for _ in range(m + 1)] ans = 0 for i, row in enumerate(grid, 1): for j, x in enumerate(row, 1):...
Sun, 21 Jul 2024 00:00:00 -0700
https://leetcode.ca/2024-07-21-3212-Count-Submatrices-With-Equal-Frequency-of-X-and-Y/
https://leetcode.ca/2024-07-21-3212-Count-Submatrices-With-Equal-Frequency-of-X-and-Y/3211 - Generate Binary Strings Without Adjacent Zeros
Welcome to Subscribe On Youtube 3211. Generate Binary Strings Without Adjacent Zeros Description You are given a positive integer n. A binary string x is valid if all substrings of x of length 2 contain at least one "1". Return all valid strings with length n, in any order. Example 1: Input: n = 3 Output: ["010","011","101","110","111"] Explanation: The valid strings of length 3 are: "010", "011", "101", "110", and "111". Example 2: Input: n = 1 Output: ["0","1"] Explanation: The valid strings of length 1 are: "0" and "1". Constraints: 1 <= n <= 18 Solutions Solution 1: DFS 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. The 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)$. Java C++ Python Go TypeScript class Solution { private List<String> ans = new ArrayList<>(); private StringBuilder t = new StringBuilder(); private int n; public List<String> validStrings(int n) { this.n = n; dfs(0); return ans; } private void dfs(int i) { if (i >= n) { ans.add(t.toString()); return; } for (int j = 0; j < 2; ++j) { if ((j == 0 && (i == 0 || t.charAt(i - 1) == '1')) || j == 1) { t.append(j); dfs(i + 1); t.deleteCharAt(t.length() - 1); } } } } class Solution { public: vector<string> validStrings(int n) { vector<string> ans; string t; auto dfs = [&](auto&& dfs, int i) { if (i >= n) { ans.emplace_back(t); return; } for (int j = 0; j < 2; ++j) { if ((j == 0 && (i == 0 || t[i - 1] == '1')) || j == 1) { t.push_back('0' + j); dfs(dfs, i + 1); t.pop_back(); } } }; dfs(dfs, 0); return ans; } }; class Solution: def validStrings(self, n: int) -> List[str]: def dfs(i: int): if i >= n: ans.append("".join(t)) return for j in range(2): if (j == 0 and (i == 0 or t[i - 1] == "1")) or j == 1: t.append(str(j)) dfs(i + 1) t.pop() ans = [] t = [] dfs(0) return ans func validStrings(n int) (ans []string) { t := []byte{} var dfs func(int) dfs = func(i int) { if i >= n { ans = append(ans, string(t)) return } for j := 0; j < 2; j++ { if (j == 0 && (i == 0 || t[i-1] == '1')) || j == 1 { t = append(t, byte('0'+j)) dfs(i + 1) t = t[:len(t)-1] } } } dfs(0) return } function validStrings(n: number): string[] { const ans: string[] = []; const t: string[] = []; const dfs = (i:...
Sat, 20 Jul 2024 00:00:00 -0700
https://leetcode.ca/2024-07-20-3211-Generate-Binary-Strings-Without-Adjacent-Zeros/
https://leetcode.ca/2024-07-20-3211-Generate-Binary-Strings-Without-Adjacent-Zeros/3210 - Find the Encrypted String
Welcome to Subscribe On Youtube
3210. Find the Encrypted String
Description
You are given a string s and an integer k. Encrypt the string using the following algorithm:
For each character c in s, replace c with the kth character after c in the string (in a cyclic manner).
Return the encrypted string.
Example 1:
Input: s = "dart", k = 3
Output: "tdar"
Explanation:
For i = 0, the 3rd character after 'd' is 't'.
For i = 1, the 3rd character after 'a' is 'd'.
For i = 2, the 3rd character after 'r' is 'a'.
For i = 3, the 3rd character after 't' is 'r'.
Example 2:
Input: s = "aaa", k = 1
Output: "aaa"
Explanation:
As all the characters are the same, the encrypted string will also be the same.
Constraints:
1 <= s.length <= 100
1 <= k <= 104
s consists only of lowercase English letters.
Solutions
Solution 1: Simulation
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.
The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $s$.
Java
C++
Python
Go
TypeScript
class Solution {
public String getEncryptedString(String s, int k) {
char[] cs = s.toCharArray();
int n = cs.length;
for (int i = 0; i < n; ++i) {
cs[i] = s.charAt((i + k) % n);
}
return new String(cs);
}
}
class Solution {
public:
string getEncryptedString(string s, int k) {
int n = s.length();
string cs(n, ' ');
for (int i = 0; i < n; ++i) {
cs[i] = s[(i + k) % n];
}
return cs;
}
};
class Solution:
def getEncryptedString(self, s: str, k: int) -> str:
cs = list(s)
n = len(s)
for i in range(n):
cs[i] = s[(i + k) % n]
return "".join(cs)
func getEncryptedString(s string, k int) string {
cs := []byte(s)
for i := range s {
cs[i] = s[(i+k)%len(s)]
}
return string(cs)
}
function getEncryptedString(s: string, k: number): string {
const cs: string[] = [];
const n = s.length;
for (let i = 0; i < n; ++i) {
cs[i] = s[(i + k) % n];
}
return cs.join('');
}
All Problems
All Solutions
Fri, 19 Jul 2024 00:00:00 -0700
https://leetcode.ca/2024-07-19-3210-Find-the-Encrypted-String/
https://leetcode.ca/2024-07-19-3210-Find-the-Encrypted-String/3209 - Number of Subarrays With AND Value of K
Welcome to Subscribe On Youtube 3209. Number of Subarrays With AND Value of K Description Given an array of integers nums and an integer k, return the number of subarrays of nums where the bitwise AND of the elements of the subarray equals k. Example 1: Input: nums = [1,1,1], k = 1 Output: 6 Explanation: All subarrays contain only 1's. Example 2: Input: nums = [1,1,2], k = 1 Output: 3 Explanation: Subarrays having an AND value of 1 are: [1,1,2], [1,1,2], [1,1,2]. Example 3: Input: nums = [1,2,3], k = 2 Output: 2 Explanation: Subarrays having an AND value of 2 are: [1,2,3], [1,2,3]. Constraints: 1 <= nums.length <= 105 0 <= nums[i], k <= 109 Solutions Solution 1: Hash Table + Enumeration 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. If 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. 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 AND operation of each value in the set with $nums[r + 1]$, plus $\textit{nums}[r + 1]$ itself. Therefore, 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. The 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. Java C++ Python Go TypeScript class Solution { public long countSubarrays(int[] nums, int k) { long ans = 0; Map<Integer, Integer> pre = new HashMap<>(); for (int x : nums) { Map<Integer, Integer> cur = new HashMap<>(); for (var e : pre.entrySet()) { int y = e.getKey(), v = e.getValue(); cur.merge(x & y, v, Integer::sum); } cur.merge(x, 1, Integer::sum); ans += cur.getOrDefault(k, 0); pre = cur; } return ans; } } class Solution { public: long long countSubarrays(vector<int>& nums, int k) { long long ans = 0; unordered_map<int, int> pre; for (int x : nums) { unordered_map<int, int> cur; for (auto& [y, v] : pre) { cur[x & y]...
Thu, 18 Jul 2024 00:00:00 -0700
https://leetcode.ca/2024-07-18-3209-Number-of-Subarrays-With-AND-Value-of-K/
https://leetcode.ca/2024-07-18-3209-Number-of-Subarrays-With-AND-Value-of-K/