
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    
    <title>Leetcode</title>
    
    
    <description>leetcode.ca</description>
    
    <link>https://leetcode.ca/</link>
    <atom:link href="https://leetcode.ca/feed.xml" rel="self" type="application/rss+xml" />
    
    
      <item>
        <title>4007 - Widest Possible Fence</title>
        <description>
          
          Welcome to Subscribe On Youtube 4007. Widest Possible Fence Description You are given an integer array planks, where planks[i] represents the height of the ith wooden plank. Each plank has a width of 1 unit. You want to build a fence consisting of planks that all have the same height. You may either use a plank as is, or combine exactly two distinct original planks into a single plank whose height equals the sum of their heights. Each original plank can be used at most once, and not all original planks need to be used. Return the maximum possible width of the fence that can be built. &amp;nbsp; Example 1: Input: planks = [1,3,2,5,7,5,4,2,1] Output: 4 Explanation: We can have four planks of height 5. planks[3] = 5 planks[5] = 5 planks[0] + planks[6] = 1 + 4 = 5 planks[1] + planks[2] = 3 + 2 = 5 Hence, the maximum width is 4. Example 2: Input: planks = [2,3,7] Output: 1 Explanation: It is impossible to form two planks of the same height, even after combining two distinct original planks. Since not all original planks need to be used, we can choose any one plank as the fence. Therefore, the maximum possible width is 1. &amp;nbsp; Constraints: 1 &amp;lt;= planks.length &amp;lt;= 1000 1 &amp;lt;= planks[i] &amp;lt;= 109 Solutions Solution 1: Counting + Enumeration Thinking Every column of the fence must share one height. A plank may be used alone, two equal planks may be stacked, or two different heights may be stacked. Searching combinations plank by plank grows too quickly in $n$. After counting heights, each target height comes from height $h$ itself, two copies of $h/2$, or a pair $x+y=h$. A plank cannot join two pairings at once, so we may add column counts over height pairs directly. With $n\le 1000$, enumerating ordered height pairs is $O(m^2)$. The answer is the maximum among those column counts. We first use a hash table $\textit{cnt}$ to count the number of planks of each height. For a target height $h$, the number of planks of height $h$ we can obtain consists of three parts: Using planks of height $h$ directly, giving $\textit{cnt}[h]$ planks; If $h$ is even, two planks of height $h/2$ can be combined into one, giving $\lfloor \textit{cnt}[h/2] / 2 \rfloor$ planks; For each pair of heights $x + y = h$ with $x &amp;lt; y$, we can combine $\min(\textit{cnt}[x], \textit{cnt}[y])$ planks. For a fixed $h$, these three parts and the different height pairs $(x, h - x)$ involve disjoint sets of original planks, so they can be summed directly. We iterate over each height $x$ in $\textit{cnt}$ and accumulate the contributions into another hash table $t$: $t[x] \mathrel{+}= \textit{cnt}[x]$, using planks of height $x$ directly; $t[2x] \mathrel{+}= \lfloor \textit{cnt}[x] / 2 \rfloor$, pairing up two planks of height $x$; For each height $y &amp;gt; x$, $t[x + y] \mathrel{+}= \min(\textit{cnt}[x], \textit{cnt}[y])$, combining planks of heights $x$ and $y$. The answer is the maximum value in $t$. The...
        </description>
        <pubDate>Sun, 13 Sep 2026 00:00:00 -0700</pubDate>
        <link>https://leetcode.ca/2026-09-13-4007-Widest-Possible-Fence/</link>
        <guid isPermaLink="true">https://leetcode.ca/2026-09-13-4007-Widest-Possible-Fence/</guid>
      </item>
    
      <item>
        <title>4006 - Count Valid Prefixes</title>
        <description>
          
          Welcome to Subscribe On Youtube 4006. Count Valid Prefixes Description You are given a binary string s. A prefix of s is considered valid if its characters can be rearranged to form an alternating string. Return the number of valid prefixes of s. A string is considered alternating if no two adjacent characters are equal. &amp;nbsp; Example 1: Input: s = &amp;quot;00101&amp;quot; Output: 3 Explanation: The valid prefixes are: &amp;quot;0&amp;quot;: It is already an alternating string. &amp;quot;001&amp;quot;: It can be rearranged into &amp;quot;010&amp;quot;, which is an alternating string. &amp;quot;00101&amp;quot;: It can be rearranged into &amp;quot;01010&amp;quot;, which is an alternating string. Thus, the answer is 3. Example 2: Input: s = &amp;quot;101&amp;quot; Output: 3 Explanation: All prefixes of s = &amp;quot;101&amp;quot; are already alternating strings. Thus, the answer is 3. &amp;nbsp; Constraints: 1 &amp;lt;= s.length &amp;lt;= 100 s consists only of &amp;#39;0&amp;#39; and &amp;#39;1&amp;#39;. Solutions Solution 1: Counting Thinking A prefix is valid if and only if the absolute difference between the counts of &apos;0&apos; and &apos;1&apos; is at most $1$. Recounting both characters on every prefix would be quadratic. A single variable $t$ tracks the difference from left to right: increment on &apos;1&apos;, decrement on &apos;0&apos;. At each index we test $|t|\le 1$. The whole count is therefore a linear scan; we need not store a count array for every prefix. A string can be rearranged into an alternating string if and only if the counts of &apos;0&apos; and &apos;1&apos; in it differ by at most $1$. Therefore, we traverse the string $s$ and maintain a variable $t$ equal to the number of &apos;1&apos;s minus the number of &apos;0&apos;s in the current prefix (increment by one on &apos;1&apos;, decrement by one on &apos;0&apos;). If $|t| \leq 1$, the current prefix is valid, and we add one to 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 countValidPrefixes(String s) { int ans = 0, t = 0; for (char c : s.toCharArray()) { t += c == &apos;1&apos; ? 1 : -1; if (Math.abs(t) &amp;lt;= 1) { ans++; } } return ans; } } class Solution { public: int countValidPrefixes(string s) { int ans = 0, t = 0; for (char c : s) { t += c == &apos;1&apos; ? 1 : -1; if (abs(t) &amp;lt;= 1) { ans++; } } return ans; } }; class Solution: def countValidPrefixes(self, s: str) -&amp;gt; int: ans = t = 0 for c in s: t += 1 if c == &apos;1&apos; else -1 ans += 1 if abs(t) &amp;lt;= 1 else 0 return ans func countValidPrefixes(s string) int { ans, t := 0, 0 for _, c := range s { if c == &apos;1&apos; { t++ } else { t-- } if t &amp;gt;= -1 &amp;amp;&amp;amp; t &amp;lt;= 1 { ans++ } } return ans } function countValidPrefixes(s: string): number { let ans = 0; let t = 0;...
        </description>
        <pubDate>Sat, 12 Sep 2026 00:00:00 -0700</pubDate>
        <link>https://leetcode.ca/2026-09-12-4006-Count-Valid-Prefixes/</link>
        <guid isPermaLink="true">https://leetcode.ca/2026-09-12-4006-Count-Valid-Prefixes/</guid>
      </item>
    
      <item>
        <title>4005 - Minimum Operations to Make Array Equal III</title>
        <description>
          
          Welcome to Subscribe On Youtube




4005. Minimum Operations to Make Array Equal III 🔒

Description

You are given an integer array nums.

In one operation, you may choose any element nums[i] and perform one of the following:


	Multiply nums[i] by an integer k, where k &amp;gt;= 2.
	Divide nums[i] by an integer k, where 2 &amp;lt;= k &amp;lt; nums[i], provided that nums[i] is divisible by k.


Return the minimum number of operations required to make all elements of nums equal.

&amp;nbsp;
Example 1:


Input: nums = [6,12,8]

Output: 3

Explanation:

We can perform following operates to make all numbers to 6:


	Divide nums[1] = 12 by 2 to get 6.
	Divide nums[2] = 8 by 4 to get 2.
	Multiply nums[2] = 2 by 3 to get 6.



Example 2:


Input: nums = [5,15,20]

Output: 2

Explanation:

We can perform following operates to make all numbers to 5:


	Divide nums[1] = 15 by 3 to get 5.
	Divide nums[2] = 20 by 4 to get 5.



Example 3:


Input: nums = [7,7,7]

Output: 0

Explanation:

All elements are already equal, so no operations are needed.


&amp;nbsp;
Constraints:


	1 &amp;lt;= nums.length &amp;lt;= 105
	1 &amp;lt;= nums[i] &amp;lt;= 10​​​​​​​9


Solutions

Solution 1

All Problems

All Solutions

        </description>
        <pubDate>Fri, 11 Sep 2026 00:00:00 -0700</pubDate>
        <link>https://leetcode.ca/2026-09-11-4005-Minimum-Operations-to-Make-Array-Equal-III/</link>
        <guid isPermaLink="true">https://leetcode.ca/2026-09-11-4005-Minimum-Operations-to-Make-Array-Equal-III/</guid>
      </item>
    
      <item>
        <title>4004 - Minimum Moves to Balance Circular Array II</title>
        <description>
          
          Welcome to Subscribe On Youtube 4004. Minimum Moves to Balance Circular Array II 🔒 Description You are given a circular array balance of length n, where balance[i] is the net balance of person i. In one move, a person can transfer exactly 1 unit of balance to either their left or right neighbor. Return the minimum number of moves required so that every person has a non-negative balance. If it is impossible, return -1. &amp;nbsp; Example 1: Input: balance = [-1,2,-1] Output: 2 Explanation: One optimal sequence of moves is: Move 1 unit from i = 1 to i = 0, resulting in balance = [0, 1, -1] Move 1 unit from i = 1 to i = 2, resulting in balance = [0, 0, 0] Thus, the minimum number of moves required is 2. Example 2: Input: balance = [4,-1,-2] Output: 3 Explanation: One optimal sequence of moves is: Move 1 unit from i = 0 to i = 1, resulting in balance = [3, 0, -2] Move 1 unit from i = 0 to i = 2, resulting in balance = [2, 0, -1] Move 1 unit from i = 0 to i = 2, resulting in balance = [1, 0, 0] Thus, the minimum number of moves required is 3. Example 3: Input: balance = [-3,-3,5] Output: -1 Explanation: It is impossible to make all balances non-negative for balance = [-3, -3, 5], so the answer is -1. &amp;nbsp; Constraints: 1 &amp;lt;= n == balance.length &amp;lt;= 1000 -105 &amp;lt;= balance[i] &amp;lt;= 105 Solutions Solution 1: Minimum Cost Maximum Flow Let $n$ be the length of $\textit{balance}$. If the sum of all balances is negative, it is impossible to make everyone’s balance non-negative, so we return $-1$ directly. Otherwise, we model the problem as a minimum cost flow problem: Create a source $s$ and a sink $t$; For each person $i$ with $\textit{balance}[i] &amp;gt; 0$ (a surplus), add an edge from $s$ to $i$ with capacity $\textit{balance}[i]$ and unit cost $0$; For each person $i$ with $\textit{balance}[i] &amp;lt; 0$ (a deficit), add an edge from $i$ to $t$ with capacity $-\textit{balance}[i]$ and unit cost $0$; For each $i$, add an edge from $i$ to each of its two neighbors with infinite capacity and unit cost $1$, representing that transferring $1$ unit of balance to a neighbor takes $1$ move. Let $\textit{totalDeficit} = \sum_{\textit{balance}[i] &amp;lt; 0} (-\textit{balance}[i])$ be the total deficit. The answer is the minimum cost of sending $\textit{totalDeficit}$ units of flow from $s$ to $t$. Since the circular edges connect everyone in both directions, all the required flow can always be delivered as long as the total balance is non-negative. We use SPFA-based successive shortest path augmentation to solve the minimum cost flow problem. Note that each augmentation pushes the entire bottleneck flow along a shortest path instead of just $1$ unit: the bottleneck edge is either an edge connected to the source or the sink (which then gets saturated), or a reverse circular edge (which reroutes...
        </description>
        <pubDate>Thu, 10 Sep 2026 00:00:00 -0700</pubDate>
        <link>https://leetcode.ca/2026-09-10-4004-Minimum-Moves-to-Balance-Circular-Array-II/</link>
        <guid isPermaLink="true">https://leetcode.ca/2026-09-10-4004-Minimum-Moves-to-Balance-Circular-Array-II/</guid>
      </item>
    
      <item>
        <title>4003 - Minimum Cost Path with Alternating Directions III</title>
        <description>
          
          Welcome to Subscribe On Youtube 4003. Minimum Cost Path with Alternating Directions III Description You are given two integers m and n representing the number of rows and columns of a grid. Your goal is to reach cell (m - 1, n - 1). You are also given a 2D integer array penalty. The cost to enter cell (i, j) is (i + 1) * (j + 1). You begin at cell (0, 0) and initially pay its entrance cost. Actions performed after entering (0, 0) are numbered starting from 1. On each action, you may move to an adjacent cell or wait in the current cell. A move follows the parity rule if: On an odd-numbered action, you move right or down. On an even-numbered action, you move left or up. The cost of an action is determined as follows: If you move according to the parity rule, pay only the entrance cost of the destination cell. If you move in a direction that violates the parity rule, pay the entrance cost of the destination cell plus penalty[i][j], where (i, j) is the cell you move from. If you wait in cell (i, j), pay penalty[i][j]. After every move or wait, the action number increases by 1. Therefore, the required parity alternates after every action, regardless of whether a penalty was paid. Return the minimum total cost required to reach (m - 1, n - 1). &amp;nbsp; Example 1: Input: m = 2, n = 2, penalty = [[5,3],[1,4]] Output: 8 Explanation: The optimal path is: Start at cell (0, 0) with entry cost (0 + 1) * (0 + 1) = 1. Move 1: Move down to cell (1, 0) with entry cost (1 + 1) * (0 + 1) = 2. Move 2: Move right to cell (1, 1) with entry cost (1 + 1) * (1 + 1) = 4 and an extra cost of penalty[1][0] = 1 for violating the even parity rule. Thus, the total cost is 1 + 2 + 4 + 1 = 8. Example 2: Input: m = 2, n = 2, penalty = [[0,7],[3,2]] Output: 7 Explanation: The optimal path is: Start at cell (0, 0) with entry cost (0 + 1) * (0 + 1) = 1. Move 1: Wait at cell (0, 0) with an extra cost of penalty[0][0] = 0 to flip to even parity. Move 2: Move right to cell (0, 1) with entry cost (0 + 1) * (1 + 1) = 2 and an extra cost of penalty[0][0] = 0 for violating the even parity rule. Move 3: Move down to cell (1, 1) with entry cost (1 + 1) * (1 + 1) = 4. Thus, the total cost is 1 + 0 + 2 + 0 + 4 = 7. Example 3: Input: m = 2, n = 3, penalty = [[8,0,9],[7,4,1]] Output: 12 Explanation: The optimal path is: Start at cell (0, 0) with entry cost (0 + 1) * (0...
        </description>
        <pubDate>Wed, 09 Sep 2026 00:00:00 -0700</pubDate>
        <link>https://leetcode.ca/2026-09-09-4003-Minimum-Cost-Path-with-Alternating-Directions-III/</link>
        <guid isPermaLink="true">https://leetcode.ca/2026-09-09-4003-Minimum-Cost-Path-with-Alternating-Directions-III/</guid>
      </item>
    
      <item>
        <title>4002 - Count Valid Sequences</title>
        <description>
          
          Welcome to Subscribe On Youtube 4002. Count Valid Sequences Description You are given two positive integers n and k. A valid sequence is a sequence of k positive integers such that: The sum of all integers in the sequence is equal to n. The product of all integers in the sequence is even. Return the number of valid sequences. Since the answer may be very large, return it modulo 109​​​​​​​ + 7. Two sequences are considered different if they differ at any index. For example, [1, 1, 2] and [1, 2, 1] are considered different sequences. &amp;nbsp; Example 1: Input: n = 5, k = 3 Output: 3 Explanation: The sequences of length k = 3 whose sum is 5 are: Sequence Product Parity [1, 1, 3] 1 * 1 * 3 = 3 Odd [1, 2, 2] 1 * 2 * 2 = 4 Even [2, 1, 2] 2 * 1 * 2 = 4 Even [2, 2, 1] 2 * 2 * 1 = 4 Even [1, 3, 1] 1 * 3 * 1 = 3 Odd [3, 1, 1] 3 * 1 * 1 = 3 Odd There are 3 sequences with an even product, thus the answer is 3. Example 2: Input: n = 3, k = 2 Output: 2 Explanation: The sequences of length k = 2 whose sum is 3 are: Sequence Product Parity [1, 2] 1 * 2 = 2 Even [2, 1] 2 * 1 = 2 Even There are 2 sequences with an even product, thus the answer is 2. Example 3: Input: n = 5, k = 5 Output: 0 Explanation: The only possible sequence of length k = 5 whose sum is 5 is [1, 1, 1, 1, 1], which has an odd product. Thus, the answer is 0. &amp;nbsp; Constraints: 1 &amp;lt;= n &amp;lt;= 5 * 105 1 &amp;lt;= k &amp;lt;= n Solutions Solution 1: Combinatorics The number of ordered ways to write $n$ as a sum of $k$ positive integers is $\binom{n-1}{k-1}$. An even product means “at least one even number”; the complement is “all odd”. Therefore the answer is: \[\binom{n-1}{k-1} - \textit{(number of all-odd sequences)}\] If every number is odd, write the $i$-th number as $2a_i + 1$ ($a_i \ge 0$). Then: \[\sum_{i=1}^{k}(2a_i + 1) = n \implies \sum_{i=1}^{k} a_i = \frac{n-k}{2}\] All-odd sequences exist only when $n$ and $k$ have the same parity (i.e., $n + k$ is even), and their count is $\binom{\frac{n+k}{2}-1}{k-1}$; otherwise the count is $0$. After precomputing factorials and modular inverses, each combination can be evaluated in $O(1)$. Return the answer modulo $10^9+7$. The time complexity is $O(N + \log M)$ for preprocessing, and the space complexity is $O(N)$, where $N = 5 \times 10^5$ and $M = 10^9+7$. Each query is $O(1)$. Java C++ Python Go TypeScript class Solution { static final int MX = 500001; static final long MOD = 1000000007L; static long[] f = new long[MX]; static long[] g = new long[MX]; static { f[0] = 1; g[0]...
        </description>
        <pubDate>Tue, 08 Sep 2026 00:00:00 -0700</pubDate>
        <link>https://leetcode.ca/2026-09-08-4002-Count-Valid-Sequences/</link>
        <guid isPermaLink="true">https://leetcode.ca/2026-09-08-4002-Count-Valid-Sequences/</guid>
      </item>
    
      <item>
        <title>4001 - Aggregate Two Time Series</title>
        <description>
          
          Welcome to Subscribe On Youtube 4001. Aggregate Two Time Series Description You are given two 2D integer arrays series1 and series2. Each element in both series is of the form [timestamp, value], where: timestamp is an integer representing the time. value is an integer representing the value at that timestamp. Each array is sorted in strictly increasing order of timestamp. For any timestamp not present in a series, its value is taken from the next available timestamp in the same series if one exists. Otherwise, its value is considered 0. The aggregated series is formed by summing the corresponding values from both series at every timestamp that appears in either series. Return the aggregated series as a 2D integer array of [timestamp, summedValue] pairs, sorted in strictly increasing order of timestamp. &amp;nbsp; Example 1: Input: series1 = [[1,3],[4,1]], series2 = [[2,2],[5,2]] Output: [[1,5],[2,3],[4,3],[5,2]] Explanation: Timestamp series1 series2 summedValue 1 3 2 5 2 1 2 3 4 1 2 3 5 0 2 2 Thus, the aggregated series is [[1, 5], [2, 3], [4, 3], [5, 2]]. Example 2: Input: series1 = [[1,5],[3,1]], series2 = [[2,2]] Output: [[1,7],[2,3],[3,1]] Explanation: Timestamp series1 series2 summedValue 1 5 2 7 2 1 2 3 3 1 0 1 Thus, the aggregated series is [[1, 7], [2, 3], [3, 1]]. Example 3: Input: series1 = [[1,5]], series2 = [[1000000000,2]] Output: [[1,7],[1000000000,2]] Explanation: At timestamp 1, the next available value in series2 is 2 at timestamp 1000000000. At timestamp 1000000000, there is no later timestamp in series1, so its value is 0. Only timestamps that appear in at least one of the two series are included. &amp;nbsp; Constraints: 1 &amp;lt;= series1.length, series2.length &amp;lt;= 105 series1[i].length == series2[i].length == 2 1 &amp;lt;= series1[i][0], series2[i][0] &amp;lt;= 109 1 &amp;lt;= series1[i][1], series2[i][1] &amp;lt;= 109 Each series is sorted in strictly increasing order of timestamp. Solutions Solution 1: Two Pointers Both series are strictly increasing by timestamp, so they can be merged with two pointers. Taking the value of the next later timestamp for a missing timestamp is equivalent to: the value at the current pointer can be used directly for earlier missing timestamps in that series. Let pointers $i$ and $j$ point to the two series. While both are not exhausted: If $t_1 = t_2$, output $[t_1, v_1 + v_2]$ and advance both pointers; If $t_1 &amp;lt; t_2$, output $[t_1, v_1 + v_2]$ (series2 uses the current later $v_2$) and advance only $i$; If $t_2 &amp;lt; t_1$, handle symmetrically. After one series is exhausted, append the remaining points of the other series directly (there is no later timestamp on the opposite side, so its value is $0$). The time complexity is $O(m + n)$, and the space complexity is $O(m + n)$, where $m$ and $n$ are the lengths of the two series. Java C++ Python Go TypeScript class Solution { public List&amp;lt;List&amp;lt;Integer&amp;gt;&amp;gt; aggregateTimeSeries(int[][] series1, int[][] series2) { int m = series1.length, n = series2.length; int i = 0, j = 0; List&amp;lt;List&amp;lt;Integer&amp;gt;&amp;gt; ans = new ArrayList&amp;lt;&amp;gt;(); while...
        </description>
        <pubDate>Mon, 07 Sep 2026 00:00:00 -0700</pubDate>
        <link>https://leetcode.ca/2026-09-07-4001-Aggregate-Two-Time-Series/</link>
        <guid isPermaLink="true">https://leetcode.ca/2026-09-07-4001-Aggregate-Two-Time-Series/</guid>
      </item>
    
      <item>
        <title>4000 - Largest Integer With Given Digit Sum</title>
        <description>
          
          Welcome to Subscribe On Youtube




4000. Largest Integer With Given Digit Sum

Description

You are given two non-negative integers n and s.

Return the largest integer that has at most n digits and whose sum of digits is s. If no such integer exists, return -1.

&amp;nbsp;
Example 1:


Input: n = 2, s = 9

Output: 90

Explanation:

The largest integer with at most 2 digits that has a sum of digits of 9 is 90.


Example 2:


Input: n = 2, s = 19

Output: -1

Explanation:

There is no integer with at most 2 digits that has a sum of digits of 19, so the answer is -1.


Example 3:


Input: n = 5, s = 0

Output: 0

Explanation:

The only non-negative integer whose digits sum to 0 is 0.


&amp;nbsp;
Constraints:


	1 &amp;lt;= n &amp;lt;= 5
	0 &amp;lt;= s &amp;lt;= 100


Solutions

Solution 1: Greedy

If $n \times 9 &amp;lt; s$, even filling every digit with $9$ cannot reach digit sum $s$, so return $-1$.

Otherwise, to maximize the integer, assign as large a digit as possible to higher places. Construct $n$ digits from high to low: each digit takes $\min(s, 9)$, then subtract that value from $s$. The resulting integer is the answer (if $s = 0$, the result is $0$).

The time complexity is $O(n)$, and the space complexity is $O(1)$.



	Java

	C++

	Python

	Go

	TypeScript





	
class Solution {
    public int largestInteger(int n, int s) {
        if (n * 9 &amp;lt; s) {
            return -1;
        }
        int ans = 0;
        for (int i = 0; i &amp;lt; n; ++i) {
            int x = Math.min(s, 9);
            ans = ans * 10 + x;
            s -= x;
        }
        return ans;
    }
}




	
class Solution {
public:
    int largestInteger(int n, int s) {
        if (n * 9 &amp;lt; s) {
            return -1;
        }
        int ans = 0;
        for (int i = 0; i &amp;lt; n; ++i) {
            int x = min(s, 9);
            ans = ans * 10 + x;
            s -= x;
        }
        return ans;
    }
};




	
class Solution:
    def largestInteger(self, n: int, s: int) -&amp;gt; int:
        if n * 9 &amp;lt; s:
            return -1
        ans = 0
        for _ in range(n):
            x = min(s, 9)
            ans = ans * 10 + x
            s -= x
        return ans





	
func largestInteger(n int, s int) (ans int) {
	if n*9 &amp;lt; s {
		return -1
	}
	for i := 0; i &amp;lt; n; i++ {
		x := min(s, 9)
		ans = ans*10 + x
		s -= x
	}
	return
}





	
function largestInteger(n: number, s: number): number {
    if (n * 9 &amp;lt; s) {
        return -1;
    }
    let ans = 0;
    for (let i = 0; i &amp;lt; n; ++i) {
        const x = Math.min(s, 9);
        ans = ans * 10 + x;
        s -= x;
    }
    return ans;
}







All Problems

All Solutions

        </description>
        <pubDate>Sun, 06 Sep 2026 00:00:00 -0700</pubDate>
        <link>https://leetcode.ca/2026-09-06-4000-Largest-Integer-With-Given-Digit-Sum/</link>
        <guid isPermaLink="true">https://leetcode.ca/2026-09-06-4000-Largest-Integer-With-Given-Digit-Sum/</guid>
      </item>
    
      <item>
        <title>3999 - Minimum Number of String Groups Through Transformations</title>
        <description>
          
          Welcome to Subscribe On Youtube




3999. Minimum Number of String Groups Through Transformations

Description

You are given an array of strings words.

Define a transformation on a string s as follows:


	Let E be the subsequence of characters at even indices of s.
	Let O be the subsequence of characters at odd indices of s.
	Independently cyclically shift E and O by any number of positions to the right, possibly zero.
	Reconstruct the string by placing the shifted E characters back into even indices and the shifted O characters back into odd indices.


Two strings are equivalent if one can be transformed into the other by a single transformation.

Partition words into the minimum number of groups such that:


	Every string belongs to exactly one group.
	Every pair of strings in the same group are equivalent.


Return an integer denoting the minimum number of groups.

&amp;nbsp;
Example 1:


Input: words = [&amp;quot;ntgwz&amp;quot;,&amp;quot;zwntg&amp;quot;]

Output: 1

Explanation:


	For &amp;quot;ntgwz&amp;quot;, the even-index subsequence is &amp;quot;ngz&amp;quot; and the odd-index subsequence is &amp;quot;tw&amp;quot;.
	Shift &amp;quot;ngz&amp;quot; right by 1 position to obtain &amp;quot;zng&amp;quot;, and shift &amp;quot;tw&amp;quot; right by 1 position to obtain &amp;quot;wt&amp;quot;.
	After reconstructing the string, we obtain &amp;quot;zwntg&amp;quot;.
	Therefore, both strings are equivalent and belong to the same group.



Example 2:


Input: words = [&amp;quot;abc&amp;quot;,&amp;quot;cab&amp;quot;,&amp;quot;bac&amp;quot;,&amp;quot;acb&amp;quot;,&amp;quot;bca&amp;quot;,&amp;quot;cba&amp;quot;]

Output: 3

Explanation:

The strings can be partitioned into the following groups:


	[&amp;quot;abc&amp;quot;,&amp;quot;cba&amp;quot;]
	[&amp;quot;cab&amp;quot;,&amp;quot;bac&amp;quot;]
	[&amp;quot;acb&amp;quot;,&amp;quot;bca&amp;quot;]



Example 3:


Input: words = [&amp;quot;leet&amp;quot;,&amp;quot;abb&amp;quot;,&amp;quot;bab&amp;quot;,&amp;quot;deed&amp;quot;,&amp;quot;edde&amp;quot;,&amp;quot;code&amp;quot;,&amp;quot;bba&amp;quot;]

Output: 5

Explanation:

The strings can be partitioned into the following groups:


	[&amp;quot;abb&amp;quot;,&amp;quot;bba&amp;quot;]
	[&amp;quot;deed&amp;quot;,&amp;quot;edde&amp;quot;]
	[&amp;quot;leet&amp;quot;]
	[&amp;quot;bab&amp;quot;]
	[&amp;quot;code&amp;quot;]


​​​​​​​​​​​​​​All pairs of strings in each group are equivalent.


&amp;nbsp;
Constraints:


	1 &amp;lt;= words.length &amp;lt;= 105
	1 &amp;lt;= words[i].length &amp;lt;= 5 * 105
	The sum of words[i].length does not exceed 5 * 105.
	words[i] consist of lowercase English letters.


Solutions

Solution 1

All Problems

All Solutions

        </description>
        <pubDate>Sat, 05 Sep 2026 00:00:00 -0700</pubDate>
        <link>https://leetcode.ca/2026-09-05-3999-Minimum-Number-of-String-Groups-Through-Transformations/</link>
        <guid isPermaLink="true">https://leetcode.ca/2026-09-05-3999-Minimum-Number-of-String-Groups-Through-Transformations/</guid>
      </item>
    
      <item>
        <title>3998 - Transform Binary String Using Subsequence Sort</title>
        <description>
          
          Welcome to Subscribe On Youtube




3998. Transform Binary String Using Subsequence Sort

Description

You are given a binary string s.

You are also given an array of strings strs, where each strs[i] has the same length as s and consists of characters &amp;#39;0&amp;#39;, &amp;#39;1&amp;#39;, and &amp;#39;?&amp;#39;. Each &amp;#39;?&amp;#39; can be replaced by either &amp;#39;0&amp;#39; or &amp;#39;1&amp;#39;.

You may perform the following operation any number of times (including zero):


	Choose any subsequence sub of s.
	Sort sub in non-decreasing order.
	Replace the chosen subsequence in s with the sorted sub, keeping all other characters unchanged.


Return a boolean array ans, where ans[i] is true if it&amp;#39;s possible to replace all &amp;#39;?&amp;#39; in strs[i] with &amp;#39;0&amp;#39; or &amp;#39;1&amp;#39; and transform s into the resulting string using the allowed operation above, otherwise return false.

&amp;nbsp;
Example 1:


Input: s = &amp;quot;101&amp;quot;, strs = [&amp;quot;1?1&amp;quot;,&amp;quot;0?1&amp;quot;,&amp;quot;0?0&amp;quot;]

Output: [true,true,false]

Explanation:


	
		
			i
			strs[i]
			Replacement
			Result strs[i]
			Operation(s)
			Result
		
		
			0
			&amp;quot;1?1&amp;quot;
			? &amp;rarr; 0
			&amp;quot;101&amp;quot;
			Matches s.
			true
		
		
			1
			&amp;quot;0?1&amp;quot;
			? &amp;rarr; 1
			&amp;quot;011&amp;quot;
			Select the&amp;nbsp;subsequence at indices [0..2] of s &amp;rarr; &amp;quot;101&amp;quot;.
			Sort &amp;quot;101&amp;quot; to get &amp;quot;011&amp;quot; = strs[i].
			true
		
		
			2
			&amp;quot;0?0&amp;quot;
			? &amp;rarr; 0 or 1
			&amp;quot;000&amp;quot; or &amp;quot;010&amp;quot;
			Not feasible.
			false
		
	


Thus, ans = [true, true, false].


Example 2:


Input: s = &amp;quot;1100&amp;quot;, strs = [&amp;quot;0011&amp;quot;,&amp;quot;11?1&amp;quot;,&amp;quot;1?1?&amp;quot;]

Output: [true,false,true]

Explanation:


	
		
			i
			strs[i]
			Replacement
			Result strs[i]
			Operation(s)
			Result
		
		
			0
			&amp;quot;0011&amp;quot;
			-
			&amp;quot;0011&amp;quot;
			Select the&amp;nbsp;subsequence at indices [0..3] of s &amp;rarr; &amp;quot;1100&amp;quot;.
			Sort &amp;quot;1100&amp;quot; to get &amp;quot;0011&amp;quot; = strs[i].
			true
		
		
			1
			&amp;quot;11?1&amp;quot;
			? &amp;rarr; 0
			&amp;quot;1101&amp;quot;
			Not feasible.
			false
		
		
			2
			&amp;quot;1?1?&amp;quot;
			First ? &amp;rarr; 0
			Second ? &amp;rarr; 0
			&amp;quot;1010&amp;quot;
			Select the&amp;nbsp;subsequence at indices [1, 2] of s &amp;rarr; &amp;quot;10&amp;quot;.
			Sort &amp;quot;10&amp;quot; to get &amp;quot;01&amp;quot;, so s = &amp;quot;1010&amp;quot;.
			true
		
	


Thus, ans = [true, false, true].


Example 3:


Input: s = &amp;quot;1010&amp;quot;, strs = [&amp;quot;0011&amp;quot;]

Output: [true]

Explanation:


	
		
			i
			strs[i]
			Replacement
			Result strs[i]
			Operation(s)
			Result
		
		
			0
			&amp;quot;0011&amp;quot;
			-
			&amp;quot;0011&amp;quot;
			Select the&amp;nbsp;subsequence at indices [0, 2, 3] of s &amp;rarr; &amp;quot;110&amp;quot;.
			Sort &amp;quot;110&amp;quot; to get &amp;quot;011&amp;quot;, so s = &amp;quot;0011&amp;quot; = strs[i].
			true
		
	


Thus, ans = [true].


&amp;nbsp;
Constraints:


	1 &amp;lt;= n == s.length &amp;lt;= 2000
	s[i] is either &amp;#39;0&amp;#39; or &amp;#39;1&amp;#39;.
	1 &amp;lt;= strs.length &amp;lt;= 2000
	strs[i].length == n
	strs[i] is either &amp;#39;0&amp;#39;, &amp;#39;1&amp;#39;, or &amp;#39;?&amp;#39;​​​​​​​.


Solutions

Solution 1

All Problems

All Solutions

        </description>
        <pubDate>Fri, 04 Sep 2026 00:00:00 -0700</pubDate>
        <link>https://leetcode.ca/2026-09-04-3998-Transform-Binary-String-Using-Subsequence-Sort/</link>
        <guid isPermaLink="true">https://leetcode.ca/2026-09-04-3998-Transform-Binary-String-Using-Subsequence-Sort/</guid>
      </item>
    
      <item>
        <title>3997 - Count Dominant Nodes in a Binary Tree</title>
        <description>
          
          Welcome to Subscribe On Youtube 3997. Count Dominant Nodes in a Binary Tree Description You are given the root of a complete binary tree. A node x is called dominant if its value is equal to the maximum value among all nodes in the subtree rooted at x. Return the number of dominant nodes in the tree. &amp;nbsp; Example 1: Input: root = [5,3,8,2,4,7,1] Output: 5 Explanation: The leaf nodes with values 2, 4, 7, and 1 are dominant. The node with value 8 is dominant because its value is the maximum value in its subtree [8, 7, 1]. Thus, the answer is 5. Example 2: Input: root = [1,2,3,1,2] Output: 4 Explanation: The leaf nodes with values 1, 2, and 3 are dominant. The node with value 2 whose subtree is [2, 1, 2] is dominant because its value is the maximum value in its subtree. Thus, the answer is 4. &amp;nbsp; Constraints: The number of nodes in the tree is in the range [1, 105]. 1 &amp;lt;= Node.val &amp;lt;= 109 The tree is guaranteed to be a complete binary tree. Solutions Solution 1: DFS A node is dominant if its value equals the maximum value in the subtree rooted at it. Therefore, for each node, we only need the maximum values of its left and right subtrees, then compare them with the node itself. Perform a bottom-up DFS: return $-\infty$ for a null node (implemented with the language’s minimum integer value), and for the current node compute $\textit{mx} = \max(\textit{leftMax}, \textit{rightMax}, \textit{node.val})$. If $\textit{mx} = \textit{node.val}$, the node is dominant and the answer is incremented by one. Finally return $\textit{mx}$ for the parent node. The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of nodes in the tree. Java C++ Python Go TypeScript /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { private int ans; public int countDominantNodes(TreeNode root) { dfs(root); return ans; } private int dfs(TreeNode node) { if (node == null) { return Integer.MIN_VALUE; } int l = dfs(node.left); int r = dfs(node.right); int mx = Math.max(Math.max(l, r), node.val); if (mx == node.val) { ++ans; } return mx; } } /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int countDominantNodes(TreeNode* root) { int ans = 0; auto dfs = [&amp;amp;](this auto&amp;amp;&amp;amp; dfs, TreeNode* node) -&amp;gt; int { if (!node) { return INT_MIN; } int l = dfs(node-&amp;gt;left); int r =...
        </description>
        <pubDate>Thu, 03 Sep 2026 00:00:00 -0700</pubDate>
        <link>https://leetcode.ca/2026-09-03-3997-Count-Dominant-Nodes-in-a-Binary-Tree/</link>
        <guid isPermaLink="true">https://leetcode.ca/2026-09-03-3997-Count-Dominant-Nodes-in-a-Binary-Tree/</guid>
      </item>
    
      <item>
        <title>3996 - Even Number of Knight Moves</title>
        <description>
          
          Welcome to Subscribe On Youtube




3996. Even Number of Knight Moves

Description

You are given two integer arrays start and target, where each array is of the form [x, y] representing a cell on a standard 8 x 8 chessboard.

Return true if a knight can move from start to target in an even number of moves. Otherwise, return false.

Note: A valid knight move consists of moving two squares in one direction and one square perpendicular to it. The figure below illustrates all eight possible moves from a cell.



&amp;nbsp;
Example 1:


Input: start = [1,1], target = [2,2]

Output: true

Explanation:

One possible sequence of moves is (1, 1) -&amp;gt; (3, 2) -&amp;gt; (2, 4) -&amp;gt; (4, 3) -&amp;gt; (2, 2).

The knight reaches the target in 4 moves, which is even. Thus, the answer is true.


Example 2:


Input: start = [4,5], target = [6,6]

Output: false

Explanation:​​​​​​​

It is impossible to reach target = [6, 6] from start = [4, 5] in an even number of moves. Thus, the answer is false.


&amp;nbsp;
Constraints:


	start.length == target.length == 2
	0 &amp;lt;= start[i], target[i] &amp;lt;= 7


Solutions

Solution 1: Parity

Each knight move has an offset of $(\pm 1, \pm 2)$ or $(\pm 2, \pm 1)$, so the change in the coordinate sum $x + y$ is always odd. In other words, every move flips the color of the square (black/white distinguished by $(x + y) \bmod 2$).

Therefore:


  After an even number of moves, the start and target have the same color;
  After an odd number of moves, the start and target have different colors.


On an $8 \times 8$ chessboard, a knight can reach any square, and any path to a same-color square must have even length. Hence, it suffices to check whether $(x + y) \bmod 2$ is equal for the start and the target.

The time complexity is $O(1)$, and the space complexity is $O(1)$.



	Java

	C++

	Python

	Go

	TypeScript





	
class Solution {
    public boolean canReach(int[] start, int[] target) {
        return (start[0] + start[1]) % 2 == (target[0] + target[1]) % 2;
    }
}




	
class Solution {
public:
    bool canReach(vector&amp;lt;int&amp;gt;&amp;amp; start, vector&amp;lt;int&amp;gt;&amp;amp; target) {
        return (start[0] + start[1]) % 2 == (target[0] + target[1]) % 2;
    }
};




	
class Solution:
    def canReach(self, start: list[int], target: list[int]) -&amp;gt; bool:
        return (start[0] + start[1]) % 2 == (target[0] + target[1]) % 2





	
func canReach(start []int, target []int) bool {
	return (start[0]+start[1])%2 == (target[0]+target[1])%2
}





	
function canReach(start: number[], target: number[]): boolean {
    return (start[0] + start[1]) % 2 === (target[0] + target[1]) % 2;
}







All Problems

All Solutions

        </description>
        <pubDate>Wed, 02 Sep 2026 00:00:00 -0700</pubDate>
        <link>https://leetcode.ca/2026-09-02-3996-Even-Number-of-Knight-Moves/</link>
        <guid isPermaLink="true">https://leetcode.ca/2026-09-02-3996-Even-Number-of-Knight-Moves/</guid>
      </item>
    
      <item>
        <title>3995 - Minimum Cost to Convert String III</title>
        <description>
          
          Welcome to Subscribe On Youtube




3995. Minimum Cost to Convert String III

Description

You are given two strings, source and target.

You are also given a 2D string array rules, where rules[i] = [patterni, replacementi], and an integer array costs, where costs[i] is the base cost of applying rules[i]. Both arrays have the same length. Additionally, patterni and replacementi have the same length.

You may apply any rule any number of times. Each rule application works as follows:


	Choose an index l such that the range of positions from l to l + patterni.length - 1 exists in the current string and none of these positions has been used in a previous rule application.
	For each index j, the character patterni[j] must either be equal to the current character at position l + j, or be &amp;#39;*&amp;#39;.
	Replace the characters in this range with replacementi. The replacement is used exactly as given and does not contain wildcards.
	The cost of this rule application is costs[i] plus the number of &amp;#39;*&amp;#39; characters in patterni.
	Once a character position has been used in a rule application, it cannot be used in any later rule application.


Since every patterni and replacementi have the same length, character positions are preserved after every rule application.

Return the minimum total cost required to transform source into target. If it is impossible, return -1.

&amp;nbsp;
Example 1:


Input: source = &amp;quot;hello&amp;quot;, target = &amp;quot;world&amp;quot;, rules = [[&amp;quot;he&amp;quot;,&amp;quot;wo&amp;quot;],[&amp;quot;llo&amp;quot;,&amp;quot;rld&amp;quot;]], costs = [3,4]

Output: 7

Explanation:


	Apply rules[0] to replace &amp;quot;he&amp;quot; with &amp;quot;wo&amp;quot; at cost 3, so the string becomes &amp;quot;wollo&amp;quot;.
	Apply rules[1] to replace &amp;quot;llo&amp;quot; with &amp;quot;rld&amp;quot; at cost 4, so the string becomes &amp;quot;world&amp;quot;.
	The total cost is 3 + 4 = 7.



Example 2:


Input: source = &amp;quot;cat&amp;quot;, target = &amp;quot;dog&amp;quot;, rules = [[&amp;quot;c*t&amp;quot;,&amp;quot;dog&amp;quot;]], costs = [2]

Output: 3

Explanation:


	Apply rules[0] to replace &amp;quot;cat&amp;quot; with &amp;quot;dog&amp;quot;. The wildcard &amp;#39;*&amp;#39; matches &amp;#39;a&amp;#39;, adding 1 to the base cost 2.
	The total cost is 2 + 1 = 3.



Example 3:


Input: source = &amp;quot;test&amp;quot;, target = &amp;quot;next&amp;quot;, rules = [[&amp;quot;*e*t&amp;quot;,&amp;quot;next&amp;quot;]], costs = [4]

Output: 6

Explanation:


	Apply rules[0] to replace &amp;quot;test&amp;quot; with &amp;quot;next&amp;quot;. The first wildcard matches &amp;#39;t&amp;#39; and the second wildcard matches &amp;#39;s&amp;#39;, adding 2 to the base cost 4.
	The total cost is 4 + 2 = 6.



Example 4:


Input: source = &amp;quot;ab&amp;quot;, target = &amp;quot;bc&amp;quot;, rules = [[&amp;quot;a*&amp;quot;,&amp;quot;bd&amp;quot;]], costs = [9]

Output: -1

Explanation:

No sequence of rule applications can transform source into target, so the answer is -1.


&amp;nbsp;
Constraints:


	1 &amp;lt;= source.length == target.length &amp;lt;= 5000
	source and target consist of lowercase English letters.
	1 &amp;lt;= rules.length == costs.length &amp;lt;= 200
	rules[i] = [patterni, replacementi]
	1 &amp;lt;= patterni.length == replacementi.length &amp;lt;= 20
	patterni contains at least one lowercase English letter and at most 5 &amp;#39;*&amp;#39; characters.
	replacementi contains only lowercase English letters.
	1 &amp;lt;= costs[i] &amp;lt;= 1000


Solutions

Solution 1

All Problems

All Solutions

        </description>
        <pubDate>Tue, 01 Sep 2026 00:00:00 -0700</pubDate>
        <link>https://leetcode.ca/2026-09-01-3995-Minimum-Cost-to-Convert-String-III/</link>
        <guid isPermaLink="true">https://leetcode.ca/2026-09-01-3995-Minimum-Cost-to-Convert-String-III/</guid>
      </item>
    
      <item>
        <title>3994 - Minimum Adjacent Swaps to Partition Array</title>
        <description>
          
          Welcome to Subscribe On Youtube




3994. Minimum Adjacent Swaps to Partition Array

Description

You are given an integer array nums and two integers a and b such that a &amp;lt; b.

An array is called good if it can be split into three contiguous parts, in this order, such that:


	Every element in the first part is less than a.
	Every element in the second part is in the range [a, b] inclusive.
	Every element in the third part is greater than b.


Any of the three parts may be empty.

In one adjacent swap, you may swap two neighboring elements of nums.

Return the minimum number of adjacent swaps required to make nums good. Since the answer may be very large, return it modulo 109 + 7.

&amp;nbsp;
Example 1:


Input: nums = [1,3,2,4,5,6], a = 3, b = 4

Output: 1

Explanation:


	Swap nums[1] and nums[2]. The array becomes [1, 2, 3, 4, 5, 6].
	This array is good because it can be split into [1, 2], [3, 4], and [5, 6].



Example 2:


Input: nums = [9,7,5,3], a = 4, b = 8

Output: 5

Explanation:

One sequence of optimal swaps is as follows:


	Swap nums[2] and nums[3]. The array becomes [9, 7, 3, 5].
	Swap nums[1] and nums[2]. The array becomes [9, 3, 7, 5].
	Swap nums[0] and nums[1]. The array becomes [3, 9, 7, 5].
	Swap nums[1] and nums[2]. The array becomes [3, 7, 9, 5].
	Swap nums[2] and nums[3]. The array becomes [3, 7, 5, 9].
	This array is good because it can be split into [3], [7, 5], and [9].



Example 3:


Input: nums = [3,7,5,9], a = 4, b = 8

Output: 0

Explanation:

The array is already good. No swaps are needed.


&amp;nbsp;
Constraints:


	1 &amp;lt;= nums.length &amp;lt;= 105
	​​​​​​​1 &amp;lt;= nums[i] &amp;lt;= 109
	1 &amp;lt;= a &amp;lt; b &amp;lt;= 109​​​​​​​


Solutions

Solution 1

All Problems

All Solutions

        </description>
        <pubDate>Mon, 31 Aug 2026 00:00:00 -0700</pubDate>
        <link>https://leetcode.ca/2026-08-31-3994-Minimum-Adjacent-Swaps-to-Partition-Array/</link>
        <guid isPermaLink="true">https://leetcode.ca/2026-08-31-3994-Minimum-Adjacent-Swaps-to-Partition-Array/</guid>
      </item>
    
      <item>
        <title>3993 - Maximum Value of an Alternating Sequence</title>
        <description>
          
          Welcome to Subscribe On Youtube 3993. Maximum Value of an Alternating Sequence Description You are given three integers n, s, and m. A sequence seq of integers of length n is considered valid if: seq[0] = s. The sequence is alternating, meaning that either: seq[0] &amp;gt; seq[1] &amp;lt; seq[2] &amp;gt; ..., or seq[0] &amp;lt; seq[1] &amp;gt; seq[2] &amp;lt; .... For every adjacent pair, |seq[i] - seq[i - 1]| &amp;lt;= m. A sequence of length 1 is considered alternating. Return the maximum possible element that can appear in any valid sequence. &amp;nbsp; Example 1: Input: n = 4, s = 3, m = 5 Output: 12 Explanation: One valid sequence is [3, 8, 7, 12]. The maximum element in the sequence is 12. Example 2: Input: n = 2, s = 4, m = 3 Output: 7 Explanation: One valid sequence is [4, 7]. The maximum element in the sequence is 7. &amp;nbsp; Constraints: 1 &amp;lt;= n, s &amp;lt;= 109 1 &amp;lt;= m &amp;lt;= 105 Solutions Solution 1: Greedy If $n = 1$, the sequence contains only the starting value $s$, so the answer is $s$. Otherwise, the sequence length is at least $2$. Since the absolute difference between adjacent elements is at most $m$, and the sequence must strictly alternate up and down, to maximize some element we should repeatedly “rise by $m$, then fall by $1$”: the fall step is taken as the minimum value $1$ so that the next rise has the largest possible room. Construct the sequence in a “rise first” pattern: \[s,\ s+m,\ s+m-1,\ s+2m-1,\ s+2m-2,\ \ldots\] With length $n$, we can complete $\lfloor n / 2 \rfloor$ rises, and the peak after the $k$-th rise is $s + k(m - 1) + 1$. Therefore, the maximum element is: \[s + \left\lfloor \frac{n}{2} \right\rfloor (m - 1) + 1\] Starting with a fall only decreases the values first and cannot produce a larger peak, so the construction above is optimal. The time complexity is $O(1)$, and the space complexity is $O(1)$. Java C++ Python Go TypeScript class Solution { public long maximumValue(int n, int s, int m) { if (n == 1) { return s; } return (long) s + (long) (n / 2) * (m - 1) + 1; } } class Solution { public: long long maximumValue(int n, int s, int m) { if (n == 1) { return s; } return 1LL * s + 1LL * (n / 2) * (m - 1) + 1; } }; class Solution: def maximumValue(self, n: int, s: int, m: int) -&amp;gt; int: if n == 1: return s return s + n // 2 * (m - 1) + 1 func maximumValue(n int, s int, m int) int64 { if n == 1 { return int64(s) } return int64(s) + int64(n/2)*int64(m-1) + 1 } function maximumValue(n: number, s: number, m: number): number { if (n === 1) { return s; } return s + Math.floor(n / 2) * (m - 1) + 1; } All...
        </description>
        <pubDate>Sun, 30 Aug 2026 00:00:00 -0700</pubDate>
        <link>https://leetcode.ca/2026-08-30-3993-Maximum-Value-of-an-Alternating-Sequence/</link>
        <guid isPermaLink="true">https://leetcode.ca/2026-08-30-3993-Maximum-Value-of-an-Alternating-Sequence/</guid>
      </item>
    
      <item>
        <title>3992 - Rearrange String to Avoid Character Pair</title>
        <description>
          
          Welcome to Subscribe On Youtube 3992. Rearrange String to Avoid Character Pair Description You are given a string s and two distinct lowercase English letters x and y. Rearrange the characters of s to construct a new string t such that: t is a permutation of s. Every occurrence of y appears before every occurrence of x in t. Return any valid string t. &amp;nbsp; Example 1: Input: s = &amp;quot;aabc&amp;quot;, x = &amp;quot;a&amp;quot;, y = &amp;quot;c&amp;quot; Output: &amp;quot;cbaa&amp;quot; Explanation: The string &amp;quot;cbaa&amp;quot; is a permutation of &amp;quot;aabc&amp;quot;, and every occurrence of &amp;#39;c&amp;#39; appears before every occurrence of &amp;#39;a&amp;#39;. Example 2: Input: s = &amp;quot;dcab&amp;quot;, x = &amp;quot;d&amp;quot;, y = &amp;quot;b&amp;quot; Output: &amp;quot;cabd&amp;quot; Explanation: The string &amp;quot;cabd&amp;quot; is a permutation of &amp;quot;dcab&amp;quot;, and every occurrence of &amp;#39;b&amp;#39; appears before every occurrence of &amp;#39;d&amp;#39;. Example 3: Input: s = &amp;quot;axe&amp;quot;, x = &amp;quot;o&amp;quot;, y = &amp;quot;x&amp;quot; Output: &amp;quot;axe&amp;quot; Explanation: The string &amp;quot;axe&amp;quot; is already valid. Since &amp;#39;o&amp;#39; does not occur in the string, the required condition is automatically satisfied. &amp;nbsp; Constraints: 1 &amp;lt;= s.length &amp;lt;= 100 s consists of lowercase English letters. x and y are lowercase English letters. x != y Solutions Solution 1: Two Pointers We need to construct a permutation $t$ of $s$ such that every occurrence of $y$ appears before every occurrence of $x$. There are no extra constraints on the other characters. Therefore, it suffices to move all occurrences of $y$ to the front of the string. Traverse the string with two pointers: $i$ points to the next position where a $y$ should be placed, and $j$ scans from left to right. Whenever $t[j] = y$, swap $t[i]$ with $t[j]$ and increment $i$. After the scan, the prefix of $t$ consists entirely of $y$, which naturally satisfies the requirement that all $y$ appear before all $x$. The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of $s$. Java C++ Python Go TypeScript class Solution { public String rearrangeString(String s, char x, char y) { char[] t = s.toCharArray(); int i = 0; for (int j = 0; j &amp;lt; t.length; j++) { if (t[j] == y) { char tmp = t[i]; t[i] = t[j]; t[j] = tmp; i++; } } return new String(t); } } class Solution { public: string rearrangeString(string s, char x, char y) { int i = 0; for (int j = 0; j &amp;lt; s.size(); j++) { if (s[j] == y) { swap(s[i], s[j]); i++; } } return s; } }; class Solution: def rearrangeString(self, s: str, x: str, y: str) -&amp;gt; str: t = list(s) i = 0 for j, c in enumerate(t): if c == y: t[i], t[j] = c, t[i] i += 1 return &apos;&apos;.join(t) func rearrangeString(s string, x byte, y byte) string { t := []byte(s) i := 0 for j, c := range t { if c == y { t[i], t[j] = t[j], t[i] i++ } } return string(t) } function rearrangeString(s: string, x: string, y: string): string {...
        </description>
        <pubDate>Sat, 29 Aug 2026 00:00:00 -0700</pubDate>
        <link>https://leetcode.ca/2026-08-29-3992-Rearrange-String-to-Avoid-Character-Pair/</link>
        <guid isPermaLink="true">https://leetcode.ca/2026-08-29-3992-Rearrange-String-to-Avoid-Character-Pair/</guid>
      </item>
    
      <item>
        <title>3991 - Sort Array Using Prefix Reversals</title>
        <description>
          
          Welcome to Subscribe On Youtube 3991. Sort Array Using Prefix Reversals 🔒 Description You are given an integer array nums of length n, where nums is a permutation of the integers in the range [0, n - 1]. You are also given an integer array pre, where each pre[i] is a valid prefix length. In one operation, you may choose any length x from pre and reverse the first x elements of nums. For example, applying a prefix reversal of length 3 on [4, 1, 2, 3] results in [2, 1, 4, 3]. Return the minimum number of operations required to sort nums in ascending order. If it is impossible to sort nums, return -1. &amp;nbsp; Example 1: Input: nums = [2,0,1], pre = [2,3] Output: 2 Explanation: Reverse pre[1] = 3 elements to get nums = [1, 0, 2]. Then reverse pre[0] = 2 elements to get nums = [0, 1, 2]. Thus, the minimum number of prefix reversal required is 2. Example 2: Input: nums = [1,0,2], pre = [1,3] Output: -1 Explanation: It is impossible to sort the array using the given prefix lengths, so the answer is -1. Example 3: Input: nums = [0,1], pre = [2] Output: 0 Explanation: Since nums is already sorted, no prefix reversals are needed. Thus, the answer is 0. &amp;nbsp; Constraints: 1 &amp;lt;= n == nums.length &amp;lt;= 8 0 &amp;lt;= nums[i] &amp;lt;= n - 1 1 &amp;lt;= pre.length &amp;lt;= n 1 &amp;lt;= pre[i] &amp;lt;= n ​​​​​​​nums is a permutation of integers from 0 to n - 1. pre consists of unique integers. Solutions Solution 1: BFS Since $n \le 8$, the number of permutations is at most $8! = 40320$, so we can use BFS to find the minimum number of operations. Treat the current array as a state, and the target state is $[0, 1, \ldots, n - 1]$. If the initial state is already the target, return $0$. Otherwise, start BFS from the initial state: each time take a state from the queue, enumerate every prefix length $x$ in $\textit{pre}$, and reverse the first $x$ elements to obtain a new state. If the new state equals the target, return the current number of steps; otherwise, if it has not been visited, enqueue it. If the search finishes without reaching the target, return $-1$. For convenience of deduplication, encode each permutation as an integer in base $8$ (every element lies in $[0, 7]$). The time complexity is $O(n! \cdot m \cdot n)$, and the space complexity is $O(n! \cdot n)$. Here, $n$ is the length of the array, and $m$ is the length of $\textit{pre}$. Java C++ Python Go TypeScript class Solution { public int sortArray(int[] nums, int[] pre) { int n = nums.length; int target = 0; for (int i = 0; i &amp;lt; n; i++) { target = target * 8 + i; } int start = 0; for (int x : nums) { start = start * 8 + x; } if (start == target) {...
        </description>
        <pubDate>Sat, 29 Aug 2026 00:00:00 -0700</pubDate>
        <link>https://leetcode.ca/2026-08-29-3991-Sort-Array-Using-Prefix-Reversals/</link>
        <guid isPermaLink="true">https://leetcode.ca/2026-08-29-3991-Sort-Array-Using-Prefix-Reversals/</guid>
      </item>
    
      <item>
        <title>3990 - Create Grid With Exactly K Paths II</title>
        <description>
          
          Welcome to Subscribe On Youtube




3990. Create Grid With Exactly K Paths II 🔒

Description

You are given an integer k.

Construct any grid consisting only of the characters &amp;#39;.&amp;#39; and &amp;#39;#&amp;#39;, where:


	&amp;#39;.&amp;#39; represents a free cell.
	&amp;#39;#&amp;#39; represents an obstacle cell.


The grid must contain at most 25 rows and at most 25 columns.

A valid path is a sequence of free cells that:


	Starts at the top-left cell (0, 0).
	Ends at the bottom-right cell (m - 1, n - 1), where m and n are the dimensions of your constructed grid.
	Moves only:
	
		Right, from (i, j) to (i, j + 1), or
		Down, from (i, j) to (i + 1, j).
	
	


Return any grid such that there are exactly k valid paths from the top-left cell to the bottom-right cell. If no such grid exists, return an empty array.

&amp;nbsp;
Example 1:


Input: k = 2

Output: [&amp;quot;..#&amp;quot;,&amp;quot;#..&amp;quot;,&amp;quot;#..&amp;quot;]

Explanation:



The grid contains exactly 2 valid paths from (0, 0) to (2, 2):


	(0, 0) &amp;rarr; (0, 1) &amp;rarr; (1, 1) &amp;rarr; (1, 2) &amp;rarr; (2, 2)
	(0, 0) &amp;rarr; (0, 1) &amp;rarr; (1, 1) &amp;rarr; (2, 1) &amp;rarr; (2, 2)



Example 2:


Input: k = 3

Output: [&amp;quot;...&amp;quot;,&amp;quot;#..&amp;quot;,&amp;quot;#..&amp;quot;]

Explanation:

​​​​​​​

The grid contains exactly 3 valid paths from (0, 0) to (2, 2):


	(0, 0) &amp;rarr; (0, 1) &amp;rarr; (0, 2) &amp;rarr; (1, 2) &amp;rarr; (2, 2)
	(0, 0) &amp;rarr; (0, 1) &amp;rarr; (1, 1) &amp;rarr; (1, 2) &amp;rarr; (2, 2)
	(0, 0) &amp;rarr; (0, 1) &amp;rarr; (1, 1) &amp;rarr; (2, 1) &amp;rarr; (2, 2)



&amp;nbsp;
Constraints:​​​​​​​


	1 &amp;lt;= k &amp;lt;= 1000


Solutions

Solution 1

All Problems

All Solutions

        </description>
        <pubDate>Fri, 28 Aug 2026 00:00:00 -0700</pubDate>
        <link>https://leetcode.ca/2026-08-28-3990-Create-Grid-With-Exactly-K-Paths-II/</link>
        <guid isPermaLink="true">https://leetcode.ca/2026-08-28-3990-Create-Grid-With-Exactly-K-Paths-II/</guid>
      </item>
    
      <item>
        <title>3989 - Maximum Consistent Columns in a Grid</title>
        <description>
          
          Welcome to Subscribe On Youtube




3989. Maximum Consistent Columns in a Grid

Description

You are given a 2D integer array grid of size m x n, and an integer limit.

You may remove zero or more columns from the grid, but at least one column must remain. The relative order of the remaining columns must be preserved.

A grid is called consistent if for every row i, and for every pair of adjacent remaining columns a and b with a &amp;lt; b, the following holds: |grid[i][b] - grid[i][a]| &amp;lt;= limit.

Return the maximum number of columns that can remain such that the resulting grid is consistent.

&amp;nbsp;
Example 1:


Input: grid = [[-2,0,3]], limit = 2

Output: 2

Explanation:


	Remove column 2 and keep columns 0 and 1, which gives |grid[0][1] &amp;minus; grid[0][0]| = |0 &amp;minus; (&amp;minus;2)| = 2 &amp;lt;= limit.
	Thus, the maximum number of columns that can remain is 2.



Example 2:


Input: grid = [[1,-1,1],[2,2,2]], limit = 1

Output: 2

Explanation:


	Remove column 1 and keep columns 0 and 2, which gives
	
		|grid[0][2] &amp;minus; grid[0][0]| = |1 &amp;minus; 1| = 0 &amp;lt;= limit and
		|grid[1][2] &amp;minus; grid[1][0]| = |2 &amp;minus; 2| = 0 &amp;lt;= limit.
	
	
	Thus, the maximum number of columns that can remain is 2.



Example 3:


Input: grid = [[-5,5]], limit = 9

Output: 1

Explanation:


	Remove either column 0 or column 1, since |grid[0][1] &amp;minus; grid[0][0]| = |5 &amp;minus; (&amp;minus;5)| = 10 &amp;gt; limit.
	Thus, the maximum number of columns that can remain is 1.



&amp;nbsp;
Constraints:


	1 &amp;lt;= m == grid.length &amp;lt;= 250
	1 &amp;lt;= n == grid[i].length &amp;lt;= 250
	-105 &amp;lt;= grid[i][j] &amp;lt;= 105
	0 &amp;lt;= limit &amp;lt;= 105​​​​​​​​​​​​​​​​


Solutions

Solution 1

All Problems

All Solutions

        </description>
        <pubDate>Wed, 26 Aug 2026 00:00:00 -0700</pubDate>
        <link>https://leetcode.ca/2026-08-26-3989-Maximum-Consistent-Columns-in-a-Grid/</link>
        <guid isPermaLink="true">https://leetcode.ca/2026-08-26-3989-Maximum-Consistent-Columns-in-a-Grid/</guid>
      </item>
    
      <item>
        <title>3988 - Create Grid With Exactly K Paths I</title>
        <description>
          
          Welcome to Subscribe On Youtube




3988. Create Grid With Exactly K Paths I

Description

You are given three integers m, n, and k.

Construct any m x n grid consisting only of the characters &amp;#39;.&amp;#39; and &amp;#39;#&amp;#39;, where:


	&amp;#39;.&amp;#39; represents a free cell.
	&amp;#39;#&amp;#39; represents an obstacle cell.


A valid path is a sequence of free cells that:


	Starts at the top-left cell (0, 0).
	Ends at the bottom-right cell (m - 1, n - 1).
	Moves only:
	
		Right, from (i, j) to (i, j + 1), or
		Down, from (i, j) to (i + 1, j).
	
	


Return any grid such that there are exactly k valid paths from the top-left cell to the bottom-right cell. If no such grid exists, return an empty array.

&amp;nbsp;
Example 1:


Input: m = 2, n = 3, k = 2

Output: [&amp;quot;...&amp;quot;,&amp;quot;#..&amp;quot;]

Explanation:



There are exactly k = 2 valid paths from (0, 0) to (1, 2):


	(0, 0) &amp;rarr; (0, 1) &amp;rarr; (0, 2) &amp;rarr; (1, 2)
	(0, 0) &amp;rarr; (0, 1) &amp;rarr; (1, 1) &amp;rarr; (1, 2)



Example 2:


Input: m = 3, n = 3, k = 4

Output: [&amp;quot;..#&amp;quot;,&amp;quot;...&amp;quot;,&amp;quot;#..&amp;quot;]

Explanation:



There are exactly k = 4 valid paths from (0, 0) to (2, 2):


	(0, 0) &amp;rarr; (0, 1) &amp;rarr; (1, 1) &amp;rarr; (1, 2) &amp;rarr; (2, 2)
	(0, 0) &amp;rarr; (0, 1) &amp;rarr; (1, 1) &amp;rarr; (2, 1) &amp;rarr; (2, 2)
	(0, 0) &amp;rarr; (1, 0) &amp;rarr; (1, 1) &amp;rarr; (1, 2) &amp;rarr; (2, 2)
	(0, 0) &amp;rarr; (1, 0) &amp;rarr; (1, 1) &amp;rarr; (2, 1) &amp;rarr; (2, 2)



Example 3:


Input: m = 1, n = 4, k = 2

Output: []

Explanation:​

No grid exists with exactly k = 2 valid paths for a 1 x 4 grid, so the answer is an empty array.


&amp;nbsp;
Constraints:


	1 &amp;lt;= m, n &amp;lt;= 10
	1 &amp;lt;= k &amp;lt;= 4


Solutions

Solution 1

All Problems

All Solutions

        </description>
        <pubDate>Tue, 25 Aug 2026 00:00:00 -0700</pubDate>
        <link>https://leetcode.ca/2026-08-25-3988-Create-Grid-With-Exactly-K-Paths-I/</link>
        <guid isPermaLink="true">https://leetcode.ca/2026-08-25-3988-Create-Grid-With-Exactly-K-Paths-I/</guid>
      </item>
    
  </channel>
</rss>
