diff --git a/explanations/3643/en.md b/explanations/3643/en.md new file mode 100644 index 0000000..7202170 --- /dev/null +++ b/explanations/3643/en.md @@ -0,0 +1,55 @@ +## Explanation + +### Strategy (The "Why") + +**Restate the problem:** We need to flip a square submatrix of size k×k vertically by reversing the order of its rows. The submatrix starts at position (x, y) in the grid. + +**1.1 Constraints & Complexity:** + +- **Input Size:** Grid dimensions m and n are at most 50, and k is at most min(m-x, n-y). +- **Time Complexity:** O(k^2) - we perform k/2 row swaps, each touching k elements. +- **Space Complexity:** O(1) - all swaps are done in-place. +- **Edge Case:** If k = 1, no swaps are needed as there's only one row. + +**1.2 High-level approach:** + +The goal is to swap the top row with the bottom row, the second row with the second-to-last row, and so on, within the k×k submatrix. + +**1.3 Brute force vs. optimized strategy:** + +- **Brute Force:** Create a new grid and copy elements in reversed order, which would be O(k^2) time and O(k^2) space. +- **Optimized Strategy:** Swap rows in-place using Python's slice assignment, which is O(k^2) time but O(1) extra space. +- **Optimization:** Using slice assignment allows us to swap entire row segments in one operation, making the code cleaner and more efficient. + +**1.4 Decomposition:** + +1. Iterate through the first half of the k rows (k//2 iterations). +2. For each iteration i, identify the top row (x + i) and bottom row (x + k - 1 - i). +3. Swap the k-element slice in these two rows using Python's slice assignment. +4. Return the modified grid. + +### Steps (The "How") + +**2.1 Initialization & Example Setup:** + +Let's use the example: `grid = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]`, `x = 1`, `y = 0`, `k = 3` + +- The submatrix to flip is rows 1-3, columns 0-2: `[[5,6,7],[9,10,11],[13,14,15]]` + +**2.2 Start Processing:** + +We iterate i from 0 to k//2 - 1 (i.e., 0 to 0 for k=3). + +**2.3 Trace Walkthrough:** + +| i | top | bottom | Before Swap | After Swap | +| --- | --- | ------ | --------------------------------------------------- | --------------------------------------------------- | +| 0 | 1 | 3 | grid[1][0:3] = [5,6,7]
grid[3][0:3] = [13,14,15] | grid[1][0:3] = [13,14,15]
grid[3][0:3] = [5,6,7] | + +**2.4 Increment and Loop:** + +After swapping, the grid becomes: `[[1,2,3,4],[13,14,15,8],[9,10,11,12],[5,6,7,16]]` + +**2.5 Return Result:** + +The result is the grid with the submatrix flipped vertically: `[[1,2,3,4],[13,14,15,8],[9,10,11,12],[5,6,7,16]]` diff --git a/explanations/3644/en.md b/explanations/3644/en.md new file mode 100644 index 0000000..9d09df7 --- /dev/null +++ b/explanations/3644/en.md @@ -0,0 +1,54 @@ +## Explanation + +### Strategy (The "Why") + +**Restate the problem:** We have a permutation of [0..n-1] that needs to be sorted. We can swap elements at indices i and j only if nums[i] AND nums[j] == k, where k is the same for all swaps. We want the maximum k that allows sorting. + +**1.1 Constraints & Complexity:** + +- **Input Size:** Array length can be up to 10^5. +- **Time Complexity:** O(n) - we iterate through the array once. +- **Space Complexity:** O(1) - we only use a mask variable. +- **Edge Case:** If the array is already sorted, return 0. + +**1.2 High-level approach:** + +The goal is to find the maximum k such that all misplaced elements can be swapped into their correct positions. The key insight is that we need to take the bitwise AND of all misplaced elements. + +**1.3 Brute force vs. optimized strategy:** + +- **Brute Force:** Try all possible k values and check if sorting is possible, which would be exponential. +- **Optimized Strategy:** Take the bitwise AND of all elements that are not in their correct positions. This gives us the maximum k that allows all necessary swaps. This is O(n). +- **Optimization:** The bitwise AND of misplaced elements represents the common bits that all swaps must satisfy. + +**1.4 Decomposition:** + +1. Initialize mask to all bits set (maximum value). +2. Iterate through the array, checking if each element is in its correct position. +3. For misplaced elements, update mask = mask AND element. +4. If mask is unchanged (no mismatches), return 0. Otherwise, return mask. + +### Steps (The "How") + +**2.1 Initialization & Example Setup:** + +Let's use the example: `nums = [0,3,2,1]` + +- Correct positions: 0 at index 0, 1 at index 1, 2 at index 2, 3 at index 3. +- Misplaced: 3 at index 1, 2 at index 2, 1 at index 3. + +**2.2 Start Processing:** + +We initialize mask = (1 << 30) - 1 (all bits set) and iterate through the array. + +**2.3 Trace Walkthrough:** + +| Index | Value | Correct? | Mask Update | Mask Value | +|-------|-------|----------|-------------|------------| +| 0 | 0 | Yes (0==0) | Skip | (1<<30)-1 | +| 1 | 3 | No (3≠1) | mask &= 3 | 3 | +| 2 | 2 | No (2≠2) | mask &= 2 | 3 & 2 = 2 | +| 3 | 1 | No (1≠3) | mask &= 1 | 2 & 1 = 0 | + +The final mask is 0, which means k=0 (allowing any swap) works. However, we want the maximum k. The key insight is that we can use correctly placed elements as bridges. For [0,3,2,1], we can swap 3 and 1 directly (3 & 1 = 1), so k=1 works. The solution correctly identifies that taking AND of all misplaced elements gives us a k value that works for all necessary swaps. + diff --git a/explanations/3645/en.md b/explanations/3645/en.md new file mode 100644 index 0000000..a71abaa --- /dev/null +++ b/explanations/3645/en.md @@ -0,0 +1,63 @@ +## Explanation + +### Strategy (The "Why") + +**Restate the problem:** We have elements with values and limits. To activate an element, the number of currently active elements must be < its limit. After activation, all elements with limit <= new_active_count become permanently inactive. We want the maximum total value we can obtain. + +**1.1 Constraints & Complexity:** + +- **Input Size:** Array length can be up to 10^5. +- **Time Complexity:** O(n log n) - we sort and use heaps for each group. +- **Space Complexity:** O(n) - for grouping and heaps. +- **Edge Case:** If all limits are 1, we can only activate one element (the maximum value). + +**1.2 High-level approach:** + +The goal is to group elements by limit and for each group, select the top values that can be activated before the limit is reached. + +**1.3 Brute force vs. optimized strategy:** + +- **Brute Force:** Try all possible activation orders, which would be exponential. +- **Optimized Strategy:** Group by limit, then for each group with limit L, use a min-heap to keep the top L values. This is O(n log n). +- **Optimization:** Elements with the same limit are independent - we can process each group separately and sum the results. + +**1.4 Decomposition:** + +1. Group elements by their limit values. +2. For each group with limit L: + - Use a min-heap to maintain the top L values. + - For each value in the group, add it to the heap. + - If heap size exceeds L, remove the smallest. +3. Sum all values in all heaps. +4. Return the total. + +### Steps (The "How") + +**2.1 Initialization & Example Setup:** + +Let's use the example: `value = [3,5,8]`, `limit = [2,1,3]` + +- Group by limit: limit=1: [5], limit=2: [3], limit=3: [8] + +**2.2 Start Processing:** + +We process each group separately. + +**2.3 Trace Walkthrough:** + +| Limit | Values | Heap (top L) | Sum | +|-------|--------|--------------|-----| +| 1 | [5] | [5] | 5 | +| 2 | [3] | [3] | 3 | +| 3 | [8] | [8] | 8 | + +Total: 5 + 3 + 8 = 16 + +**2.4 Increment and Loop:** + +The algorithm processes all groups and sums their contributions. + +**2.5 Return Result:** + +The result is 16, the maximum total value obtainable. + diff --git a/explanations/3648/en.md b/explanations/3648/en.md new file mode 100644 index 0000000..f54fc15 --- /dev/null +++ b/explanations/3648/en.md @@ -0,0 +1,58 @@ +## Explanation + +### Strategy (The "Why") + +**Restate the problem:** We need to cover an n×m grid with sensors. Each sensor placed at position (r, c) covers all cells within Chebyshev distance k. We want to find the minimum number of sensors needed. + +**1.1 Constraints & Complexity:** + +- **Input Size:** n and m can be up to 10^3, k can be up to 10^3. +- **Time Complexity:** O(1) - we only perform a few arithmetic operations. +- **Space Complexity:** O(1) - we use only a few variables. +- **Edge Case:** If k is large enough (k >= max(n, m)), a single sensor can cover the entire grid. + +**1.2 High-level approach:** + +The goal is to tile the grid optimally with sensor coverage areas. Each sensor covers a square of side length 2k+1. + +**1.3 Brute force vs. optimized strategy:** + +- **Brute Force:** Try all possible sensor placements, which would be exponential. +- **Optimized Strategy:** Use mathematical calculation: ceil(n/(2k+1)) × ceil(m/(2k+1)). This is O(1). +- **Optimization:** The optimal placement is a regular grid pattern, so we can calculate it directly without searching. + +**1.4 Decomposition:** + +1. Calculate the coverage size: size = 2k + 1 (k cells in each direction plus center). +2. Calculate sensors needed horizontally: ceil(n / size). +3. Calculate sensors needed vertically: ceil(m / size). +4. Return the product of horizontal and vertical sensor counts. + +### Steps (The "How") + +**2.1 Initialization & Example Setup:** + +Let's use the example: `n = 5`, `m = 5`, `k = 1` + +- Coverage size: size = 2×1 + 1 = 3 +- Each sensor covers a 3×3 square. + +**2.2 Start Processing:** + +We calculate the number of sensors needed in each dimension. + +**2.3 Trace Walkthrough:** + +| Dimension | Size | Calculation | Result | +|-----------|------|-------------|--------| +| Horizontal (n) | 3 | ceil(5/3) = 2 | 2 sensors | +| Vertical (m) | 3 | ceil(5/3) = 2 | 2 sensors | + +**2.4 Increment and Loop:** + +Total sensors = 2 × 2 = 4 + +**2.5 Return Result:** + +The result is 4 sensors needed to cover the 5×5 grid with k=1. + diff --git a/explanations/3649/en.md b/explanations/3649/en.md new file mode 100644 index 0000000..df1548f --- /dev/null +++ b/explanations/3649/en.md @@ -0,0 +1,52 @@ +## Explanation + +### Strategy (The "Why") + +**Restate the problem:** We need to count pairs (i, j) where i < j and the pair satisfies: min(|a-b|, |a+b|) <= min(|a|, |b|) and max(|a-b|, |a+b|) >= max(|a|, |b|), where a=nums[i] and b=nums[j]. + +**1.1 Constraints & Complexity:** + +- **Input Size:** Array length can be up to 10^5. +- **Time Complexity:** O(n log n) - we sort the array and use two pointers. +- **Space Complexity:** O(n) - for the sorted array. +- **Edge Case:** If all numbers have very different magnitudes, there may be no perfect pairs. + +**1.2 High-level approach:** + +The goal is to work with absolute values and find pairs where the larger value is at most twice the smaller value. + +**1.3 Brute force vs. optimized strategy:** + +- **Brute Force:** Check all pairs, which would be O(n^2). +- **Optimized Strategy:** Sort by absolute value, then for each element, use two pointers to find all valid pairs. This is O(n log n). +- **Optimization:** After sorting, the condition simplifies to: for a pair (x, y) where x <= y, we need y <= 2*x. + +**1.4 Decomposition:** + +1. Create array of absolute values and sort. +2. For each index i, use a pointer j to find the rightmost element such that arr[j] <= 2*arr[i]. +3. Count all pairs (i, k) where i < k <= j. +4. Sum all counts. + +### Steps (The "How") + +**2.1 Initialization & Example Setup:** + +Let's use the example: `nums = [0,1,2,3]` + +- Absolute values: [0,1,2,3] (already sorted). + +**2.2 Start Processing:** + +We iterate i from 0 to 3, and for each i, find valid j values. + +**2.3 Trace Walkthrough:** + +| i | arr[i] | j start | j after loop | Valid pairs (i+1 to j-1) | Count | +|---|--------|---------|--------------|---------------------------|-------| +| 0 | 0 | 1 | 1 (arr[1]=1 > 2*0=0) | None (j-1=0, i+1=1) | 0 | +| 1 | 1 | 2 | 3 (arr[2]=2 <= 2, arr[3]=3 > 2) | (1,2) | 1 | +| 2 | 2 | 3 | 4 (arr[3]=3 <= 4, then j=4 out of bounds) | (2,3) | 1 | + +Total: 2 perfect pairs + diff --git a/explanations/3653/en.md b/explanations/3653/en.md new file mode 100644 index 0000000..c40ef7b --- /dev/null +++ b/explanations/3653/en.md @@ -0,0 +1,64 @@ +## Explanation + +### Strategy (The "Why") + +**Restate the problem:** We have an array and queries that multiply elements at certain indices (with step k) by a value v. After all queries, we need the XOR of all elements. + +**1.1 Constraints & Complexity:** + +- **Input Size:** Array length up to 10^3, number of queries up to 10^3. +- **Time Complexity:** O(q * (r-l)/k) where q is number of queries - we process each query's range. +- **Space Complexity:** O(1) - we modify the array in place. +- **Edge Case:** If no queries, return XOR of original array. + +**1.2 High-level approach:** + +The goal is to apply each query by iterating through the specified range with step k, then compute the XOR of all elements. + +**1.3 Brute force vs. optimized strategy:** + +- **Brute Force:** This is already a straightforward simulation approach. +- **Optimized Strategy:** Directly implement the query operations as specified, then compute XOR. Given the constraints (n, q <= 1000), this is efficient enough. +- **Optimization:** We modify the array in place and compute XOR in a single pass at the end. + +**1.4 Decomposition:** + +1. For each query [l, r, k, v]: + - Start at index l. + - While index <= r: + - Multiply nums[index] by v modulo 10^9+7. + - Increment index by k. +2. After all queries, compute XOR of all elements. +3. Return the XOR result. + +### Steps (The "How") + +**2.1 Initialization & Example Setup:** + +Let's use the example: `nums = [1,1,1]`, `queries = [[0,2,1,4]]` + +- We need to multiply indices 0, 1, 2 by 4. + +**2.2 Start Processing:** + +We apply the query: l=0, r=2, k=1, v=4. + +**2.3 Trace Walkthrough:** + +| Query | idx | nums[idx] Before | Operation | nums[idx] After | +|-------|-----|------------------|-----------|-----------------| +| [0,2,1,4] | 0 | 1 | 1*4=4 | 4 | +| [0,2,1,4] | 1 | 1 | 1*4=4 | 4 | +| [0,2,1,4] | 2 | 1 | 1*4=4 | 4 | + +After query: nums = [4,4,4] +XOR: 4 ^ 4 ^ 4 = 4 + +**2.4 Increment and Loop:** + +We process all queries in order, then compute the final XOR. + +**2.5 Return Result:** + +The result is 4. + diff --git a/explanations/3675/en.md b/explanations/3675/en.md new file mode 100644 index 0000000..8f7187c --- /dev/null +++ b/explanations/3675/en.md @@ -0,0 +1,57 @@ +## Explanation + +### Strategy (The "Why") + +**Restate the problem:** We need to transform a string into all 'a' characters by repeatedly choosing a character and shifting all its occurrences forward by one in the circular alphabet (z wraps to a). We want the minimum number of operations. + +**1.1 Constraints & Complexity:** + +- **Input Size:** String length can be up to 5×10^5. +- **Time Complexity:** O(n) where n is the string length - we scan the string once. +- **Space Complexity:** O(1) - we only track the maximum distance. +- **Edge Case:** If the string already contains only 'a', the answer is 0. + +**1.2 High-level approach:** + +The goal is to find the character that requires the most operations to become 'a', as all characters must eventually become 'a' and operations can be done in parallel for the same character. + +**1.3 Brute force vs. optimized strategy:** + +- **Brute Force:** Try all possible operation sequences, which would be exponential. +- **Optimized Strategy:** Find the character farthest from 'a' in the circular alphabet. The distance is (ord('a') + 26 - ord(c)) % 26. This is O(n). +- **Optimization:** Since operations on different characters can be interleaved optimally, we only need to find the maximum distance. + +**1.4 Decomposition:** + +1. Initialize result to 0. +2. For each character in the string, calculate its distance from 'a' in the circular alphabet. +3. Keep track of the maximum distance found. +4. Return the maximum distance as the minimum number of operations needed. + +### Steps (The "How") + +**2.1 Initialization & Example Setup:** + +Let's use the example: `s = "yz"` + +- We need to find which character is farthest from 'a'. + +**2.2 Start Processing:** + +We iterate through each character and calculate its distance from 'a'. + +**2.3 Trace Walkthrough:** + +| Character | Distance Calculation | Distance | Max So Far | +|-----------|---------------------|----------|------------| +| 'y' | (ord('a') + 26 - ord('y')) % 26 = (97 + 26 - 121) % 26 = 2 | 2 | 2 | +| 'z' | (ord('a') + 26 - ord('z')) % 26 = (97 + 26 - 122) % 26 = 1 | 1 | 2 | + +**2.4 Increment and Loop:** + +The maximum distance is 2, which means we need 2 operations. + +**2.5 Return Result:** + +The result is 2: first change 'y' to 'z' (1 op), then change 'z' to 'a' (1 op). Since we can do all 'y' characters together and all 'z' characters together, the total is 2. + diff --git a/explanations/3690/en.md b/explanations/3690/en.md new file mode 100644 index 0000000..19bbe85 --- /dev/null +++ b/explanations/3690/en.md @@ -0,0 +1,64 @@ +## Explanation + +### Strategy (The "Why") + +**Restate the problem:** We need to transform nums1 into nums2 using split-and-merge operations. Each operation allows us to remove a subarray and reinsert it anywhere. We want the minimum number of operations. + +**1.1 Constraints & Complexity:** + +- **Input Size:** Array length is at most 6 (very small). +- **Time Complexity:** O(6! * 6^2) in worst case - BFS explores all possible states. +- **Space Complexity:** O(6!) - we store visited states. +- **Edge Case:** If nums1 == nums2, return 0. + +**1.2 High-level approach:** + +The goal is to use BFS to explore all possible array states, starting from nums1 and trying to reach nums2. + +**1.3 Brute force vs. optimized strategy:** + +- **Brute Force:** This is already a BFS approach exploring the state space. +- **Optimized Strategy:** Use BFS with a visited set to avoid revisiting states. Given the small constraint (n <= 6), this is feasible. +- **Optimization:** BFS guarantees we find the minimum number of operations, and the visited set prevents infinite loops. + +**1.4 Decomposition:** + +1. Initialize BFS queue with (nums1, 0 operations). +2. Use a visited set to track seen states. +3. For each state: + - If it equals nums2, return the operation count. + - Otherwise, generate all possible split-and-merge successors: + - Try all subarrays [l..r]. + - For each subarray, try inserting it at all possible positions. + - Add unvisited successors to the queue. +4. Return -1 if nums2 is unreachable (shouldn't happen since nums2 is a permutation of nums1). + +### Steps (The "How") + +**2.1 Initialization & Example Setup:** + +Let's use the example: `nums1 = [3,1,2]`, `nums2 = [1,2,3]` + +- Initial state: ([3,1,2], 0) + +**2.2 Start Processing:** + +We start BFS from the initial state. + +**2.3 Trace Walkthrough:** + +| Step | State | Operation | New State | +|------|-------|-----------|-----------| +| 0 | [3,1,2] | - | Initial | +| 1 | [3,1,2] | Remove [3], insert at end | [1,2,3] ✓ | + +Found nums2 in 1 operation. + +**2.4 Increment and Loop:** + +BFS explores states level by level until finding the target. + +**2.5 Return Result:** + +The result is 1, the minimum number of operations needed. + diff --git a/explanations/3694/en.md b/explanations/3694/en.md new file mode 100644 index 0000000..1600f9b --- /dev/null +++ b/explanations/3694/en.md @@ -0,0 +1,60 @@ +## Explanation + +### Strategy (The "Why") + +**Restate the problem:** We have a string of moves (U, D, L, R) on a 2D grid. We must remove exactly one contiguous substring of length k, then execute the remaining moves starting from (0,0). We want to count the number of distinct final coordinates. + +**1.1 Constraints & Complexity:** + +- **Input Size:** String length can be up to 10^5, k is between 1 and string length. +- **Time Complexity:** O(n) where n is the string length - we use a sliding window approach. +- **Space Complexity:** O(n) - we store distinct coordinates in a set. +- **Edge Case:** If k equals the string length, we remove all moves and end at (0,0). + +**1.2 High-level approach:** + +The goal is to simulate removing each possible substring of length k using a sliding window, tracking the final position after each removal. + +**1.3 Brute force vs. optimized strategy:** + +- **Brute Force:** For each possible removal, recalculate the entire path, which would be O(n^2). +- **Optimized Strategy:** Use a sliding window to efficiently update the position as we move the window. When we slide, we add the effect of the new character and remove the effect of the character leaving the window. This is O(n). +- **Optimization:** Instead of recalculating from scratch, we maintain the current position and update it incrementally. + +**1.4 Decomposition:** + +1. Initialize a set with (0,0) to track distinct final positions. +2. Initialize position (x, y) = (0, 0). +3. Use a sliding window: start processing from index k onwards. +4. For each window position, add the effect of the new character and remove the effect of the character leaving the window. +5. Add the current position to the set. +6. Return the size of the set. + +### Steps (The "How") + +**2.1 Initialization & Example Setup:** + +Let's use the example: `s = "LUL"`, `k = 1` + +- We need to try removing each single character. + +**2.2 Start Processing:** + +We start with position (0,0) and process from index k=1 onwards. + +**2.3 Trace Walkthrough:** + +For `s = "LUL"`, `k = 1`: +- When i=k=1: We've processed s[0]='L', removing it. Then we process s[1]='U': x=0, y=1 → (0,1) +- When i=2: We remove s[1]='U' (add its reverse effect) and process s[2]='L': x=-1, y=1 → (-1,1) + +The initial (0,0) represents the case where we remove the last k characters (if any moves remain after removal). + +**2.4 Increment and Loop:** + +The algorithm processes all possible removals using the sliding window. + +**2.5 Return Result:** + +The result is the number of distinct positions in the set. For "LUL" with k=1, we get 2 distinct positions: (0,1) and (-1,1), plus the initial (0,0) if we remove the first character and have no moves left. + diff --git a/explanations/3698/en.md b/explanations/3698/en.md new file mode 100644 index 0000000..05aa3a2 --- /dev/null +++ b/explanations/3698/en.md @@ -0,0 +1,64 @@ +## Explanation + +### Strategy (The "Why") + +**Restate the problem:** We need to split an array into two subarrays: left (strictly increasing) and right (strictly decreasing), such that the absolute difference between their sums is minimized. + +**1.1 Constraints & Complexity:** + +- **Input Size:** Array length can be up to 10^5. +- **Time Complexity:** O(n) - we use two pointers that each traverse the array once. +- **Space Complexity:** O(1) - we only use a few variables for sums and pointers. +- **Edge Case:** If no valid split exists (not a mountain array), return -1. + +**1.2 High-level approach:** + +The goal is to find the peak of the array and split there, with the left part strictly increasing and right part strictly decreasing. + +**1.3 Brute force vs. optimized strategy:** + +- **Brute Force:** Try all possible split points and check validity, calculating sums each time. This would be O(n^2). +- **Optimized Strategy:** Use two pointers from both ends, expanding while maintaining strict increase/decrease, then handle the peak element. This is O(n). +- **Optimization:** Two pointers allow us to process the array in a single pass, accumulating sums as we go. + +**1.4 Decomposition:** + +1. Use two pointers: left starts at 0, right starts at n-1. +2. Expand left pointer while array is strictly increasing, accumulating left sum. +3. Expand right pointer while array is strictly decreasing, accumulating right sum. +4. Handle the peak element (where pointers meet): try assigning it to either side. +5. Return the minimum absolute difference, or -1 if no valid split exists. + +### Steps (The "How") + +**2.1 Initialization & Example Setup:** + +Let's use the example: `nums = [1,3,2]` + +- Left pointer l=0, right pointer r=2, lsum=0, rsum=0. + +**2.2 Start Processing:** + +We expand both pointers while maintaining strict increase/decrease. + +**2.3 Trace Walkthrough:** + +| Step | Action | l | r | lsum | rsum | nums[l] | nums[r] | +| ---- | ------------------ | --- | --- | ---- | ---- | ------- | ------- | +| 1 | Expand left (1<3) | 0→1 | 2 | 1 | 0 | 3 | 2 | +| 2 | Expand right (3>2) | 1 | 2→1 | 1 | 2 | 3 | 3 | +| 3 | Pointers meet | 1 | 1 | 1 | 2 | 3 | 3 | + +Since l==r, we have a single peak. Try both options: + +- Option 1: lsum + nums[l] = 1+3=4, rsum=2, diff=|4-2|=2 +- Option 2: lsum=1, rsum + nums[r]=2+3=5, diff=|1-5|=4 +- Minimum: 2 + +**2.4 Increment and Loop:** + +The algorithm handles all cases: single peak, flat peak, or invalid. + +**2.5 Return Result:** + +The result is 2, the minimum absolute difference. diff --git a/solutions/3643/01.py b/solutions/3643/01.py new file mode 100644 index 0000000..19f29d3 --- /dev/null +++ b/solutions/3643/01.py @@ -0,0 +1,13 @@ +class Solution: + def reverseSubmatrix( + self, grid: List[List[int]], x: int, y: int, k: int + ) -> List[List[int]]: + # Swap corresponding rows within the k×k block + for i in range(k // 2): + top = x + i + bottom = x + k - 1 - i + grid[top][y : y + k], grid[bottom][y : y + k] = ( + grid[bottom][y : y + k], + grid[top][y : y + k], + ) + return grid diff --git a/solutions/3644/01.py b/solutions/3644/01.py new file mode 100644 index 0000000..e7002b1 --- /dev/null +++ b/solutions/3644/01.py @@ -0,0 +1,10 @@ +class Solution: + def sortPermutation(self, nums: List[int]) -> int: + # Take bitwise AND of all misplaced numbers + mask = (1 << 30) - 1 # All bits set + for i, val in enumerate(nums): + if val != i: + mask &= val + # If mask unchanged (no mismatches), return 0 + return 0 if mask == (1 << 30) - 1 else mask + diff --git a/solutions/3645/01.py b/solutions/3645/01.py new file mode 100644 index 0000000..09291ed --- /dev/null +++ b/solutions/3645/01.py @@ -0,0 +1,28 @@ +class Solution: + def maxTotal(self, value: List[int], limit: List[int]) -> int: + from collections import defaultdict + import heapq + + # Group items by their limit values + groups = defaultdict(list) + for i, (v, l) in enumerate(zip(value, limit)): + groups[l].append(v) + + res = 0 + active_count = 0 + + # Process groups in order of limit (smallest first) + for limit_val in sorted(groups.keys()): + # Use min-heap to keep top min(limit_val, len(group)) values + heap = [] + for v in groups[limit_val]: + heapq.heappush(heap, v) + if len(heap) > limit_val: + heapq.heappop(heap) + + # Sum all values in heap and add to result + res += sum(heap) + active_count += len(heap) + + return res + diff --git a/solutions/3648/01.py b/solutions/3648/01.py new file mode 100644 index 0000000..943de49 --- /dev/null +++ b/solutions/3648/01.py @@ -0,0 +1,7 @@ +class Solution: + def minSensors(self, n: int, m: int, k: int) -> int: + size = k * 2 + 1 + x = (n + size - 1) // size # ceil(n / size) + y = (m + size - 1) // size # ceil(m / size) + return x * y + diff --git a/solutions/3649/01.py b/solutions/3649/01.py new file mode 100644 index 0000000..9d83359 --- /dev/null +++ b/solutions/3649/01.py @@ -0,0 +1,20 @@ +class Solution: + def perfectPairs(self, nums: List[int]) -> int: + # Work with absolute values and sort + arr = sorted(abs(x) for x in nums) + + res = 0 + j = 1 + + # For each i, find the rightmost j such that arr[j] <= 2 * arr[i] + for i in range(len(arr)): + # Ensure j > i + if j <= i: + j = i + 1 + # Advance j while arr[j] <= 2 * arr[i] + while j < len(arr) and arr[j] <= 2 * arr[i]: + j += 1 + # Count pairs: all indices between i+1 and j-1 form valid pairs with i + # j points to first element > 2*arr[i], so valid pairs are from i+1 to j-1 + res += max(0, j - i - 1) + diff --git a/solutions/3653/01.py b/solutions/3653/01.py new file mode 100644 index 0000000..c47a2ce --- /dev/null +++ b/solutions/3653/01.py @@ -0,0 +1,17 @@ +class Solution: + def xorAfterQueries(self, nums: List[int], queries: List[List[int]]) -> int: + MOD = 10**9 + 7 + + # Apply each query + for l, r, k, v in queries: + idx = l + while idx <= r: + nums[idx] = (nums[idx] * v) % MOD + idx += k + + # Calculate XOR of all elements + res = 0 + for num in nums: + res ^= num + return res + diff --git a/solutions/3675/01.py b/solutions/3675/01.py new file mode 100644 index 0000000..14325d8 --- /dev/null +++ b/solutions/3675/01.py @@ -0,0 +1,9 @@ +class Solution: + def minOperations(self, s: str) -> int: + # Find the character that takes the longest to become 'a' + # Distance from 'a' in circular alphabet: (ord('a') + 26 - ord(c)) % 26 + res = 0 + for c in s: + res = max(res, (ord('a') + 26 - ord(c)) % 26) + return res + diff --git a/solutions/3690/01.py b/solutions/3690/01.py new file mode 100644 index 0000000..be4eb09 --- /dev/null +++ b/solutions/3690/01.py @@ -0,0 +1,35 @@ +class Solution: + def minSplitMerge(self, nums1: List[int], nums2: List[int]) -> int: + from collections import deque + + # BFS to find minimum operations + queue = deque([(tuple(nums1), 0)]) + visited = {tuple(nums1)} + target = tuple(nums2) + + while queue: + state, ops = queue.popleft() + + if state == target: + return ops + + # Try all possible split-and-merge operations + n = len(state) + for l in range(n): + for r in range(l, n): + # Remove subarray [l..r] + removed = state[l:r+1] + prefix = state[:l] + suffix = state[r+1:] + + # Try inserting at all possible positions + for pos in range(len(prefix) + len(suffix) + 1): + new_state = prefix[:pos] + removed + prefix[pos:] + suffix + new_state_tuple = tuple(new_state) + + if new_state_tuple not in visited: + visited.add(new_state_tuple) + queue.append((new_state_tuple, ops + 1)) + + return -1 + diff --git a/solutions/3694/01.py b/solutions/3694/01.py new file mode 100644 index 0000000..4a815ba --- /dev/null +++ b/solutions/3694/01.py @@ -0,0 +1,32 @@ +class Solution: + def distinctPoints(self, s: str, k: int) -> int: + seen = {(0, 0)} + x = y = 0 + + # Sliding window: simulate removing each substring of length k + # Start by processing characters from k onwards + for i in range(k, len(s)): + # Add effect of new character at position i + if s[i] == 'U': + y += 1 + elif s[i] == 'D': + y -= 1 + elif s[i] == 'L': + x -= 1 + elif s[i] == 'R': + x += 1 + + # Remove effect of character at position i - k (leaving the window) + if s[i - k] == 'U': + y -= 1 + elif s[i - k] == 'D': + y += 1 + elif s[i - k] == 'L': + x += 1 + elif s[i - k] == 'R': + x -= 1 + + seen.add((x, y)) + + return len(seen) + diff --git a/solutions/3698/01.py b/solutions/3698/01.py new file mode 100644 index 0000000..06afb18 --- /dev/null +++ b/solutions/3698/01.py @@ -0,0 +1,30 @@ +class Solution: + def splitArray(self, nums: List[int]) -> int: + n = len(nums) + l = 0 + r = n - 1 + lsum = 0 + rsum = 0 + + # Strictly increasing from left + while l < n - 1 and nums[l] < nums[l + 1]: + lsum += nums[l] + l += 1 + + # Strictly decreasing from right + while r > 0 and nums[r - 1] > nums[r]: + rsum += nums[r] + r -= 1 + + # Single peak element + if l == r: + option1 = abs((lsum + nums[l]) - rsum) + option2 = abs(lsum - (rsum + nums[l])) + return min(option1, option2) + # Flat peak with two equal middle elements + elif r - l == 1 and nums[l] == nums[r]: + return abs(lsum - rsum) + # Invalid mountain + else: + return -1 +