From 14525563bee8aacb3d48641a84adbf2a68bc6e77 Mon Sep 17 00:00:00 2001 From: Sri Hari Date: Sat, 11 Oct 2025 21:33:02 +0530 Subject: [PATCH 1/5] Added articles --- .../largest-submatrix-with-rearrangements.md | 133 ++++++++++ articles/minimum-cost-for-tickets.md | 233 ++++++++++++++++++ ...um-time-to-collect-all-apples-in-a-tree.md | 68 +++++ articles/rearrange-array-elements-by-sign.md | 72 ++++++ 4 files changed, 506 insertions(+) diff --git a/articles/largest-submatrix-with-rearrangements.md b/articles/largest-submatrix-with-rearrangements.md index d1aec6383..0e856f0b3 100644 --- a/articles/largest-submatrix-with-rearrangements.md +++ b/articles/largest-submatrix-with-rearrangements.md @@ -120,6 +120,39 @@ class Solution { } ``` +```csharp +public class Solution { + public int LargestSubmatrix(int[][] matrix) { + int ROWS = matrix.Length; + int COLS = matrix[0].Length; + int res = 0; + + for (int startRow = 0; startRow < ROWS; startRow++) { + Queue ones = new Queue(); + for (int i = 0; i < COLS; i++) { + ones.Enqueue(i); + } + + for (int r = startRow; r < ROWS; r++) { + if (ones.Count == 0) break; + + int size = ones.Count; + for (int k = 0; k < size; k++) { + int c = ones.Dequeue(); + if (matrix[r][c] == 1) { + ones.Enqueue(c); + } + } + + res = Math.Max(res, ones.Count * (r - startRow + 1)); + } + } + + return res; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -253,6 +286,40 @@ class Solution { } ``` +```csharp +public class Solution { + public int LargestSubmatrix(int[][] matrix) { + int ROWS = matrix.Length; + int COLS = matrix[0].Length; + int res = 0; + int[] prevHeights = new int[COLS]; + + for (int r = 0; r < ROWS; r++) { + int[] heights = new int[COLS]; + Array.Copy(matrix[r], heights, COLS); + + for (int c = 0; c < COLS; c++) { + if (heights[c] > 0) { + heights[c] += prevHeights[c]; + } + } + + int[] sortedHeights = (int[])heights.Clone(); + Array.Sort(sortedHeights); + Array.Reverse(sortedHeights); + + for (int i = 0; i < COLS; i++) { + res = Math.Max(res, (i + 1) * sortedHeights[i]); + } + + prevHeights = heights; + } + + return res; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -369,6 +436,35 @@ class Solution { } ``` +```csharp +public class Solution { + public int LargestSubmatrix(int[][] matrix) { + int ROWS = matrix.Length; + int COLS = matrix[0].Length; + int res = 0; + + for (int r = 1; r < ROWS; r++) { + for (int c = 0; c < COLS; c++) { + if (matrix[r][c] > 0) { + matrix[r][c] += matrix[r - 1][c]; + } + } + } + + for (int r = 0; r < ROWS; r++) { + int[] row = (int[])matrix[r].Clone(); + Array.Sort(row); + Array.Reverse(row); + for (int i = 0; i < COLS; i++) { + res = Math.Max(res, (i + 1) * row[i]); + } + } + + return res; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -517,6 +613,43 @@ class Solution { } ``` +```csharp +public class Solution { + public int LargestSubmatrix(int[][] matrix) { + int ROWS = matrix.Length; + int COLS = matrix[0].Length; + int res = 0; + List prevHeights = new List(); + + for (int r = 0; r < ROWS; r++) { + List heights = new List(); + + foreach (int c in prevHeights) { + if (matrix[r][c] > 0) { + matrix[r][c] += matrix[r - 1][c]; + heights.Add(c); + } + } + + for (int c = 0; c < COLS; c++) { + if (matrix[r][c] == 1) { + heights.Add(c); + } + } + + for (int i = 0; i < heights.Count; i++) { + int c = heights[i]; + res = Math.Max(res, (i + 1) * matrix[r][c]); + } + + prevHeights = heights; + } + + return res; + } +} +``` + ::tabs-end ### Time & Space Complexity diff --git a/articles/minimum-cost-for-tickets.md b/articles/minimum-cost-for-tickets.md index c7ccc7e12..53b7926c9 100644 --- a/articles/minimum-cost-for-tickets.md +++ b/articles/minimum-cost-for-tickets.md @@ -120,6 +120,39 @@ class Solution { } ``` +```csharp +public class Solution { + int[] days, costs; + int n; + + public int MincostTickets(int[] days, int[] costs) { + this.days = days; + this.costs = costs; + n = days.Length; + return Dfs(0); + } + + private int Dfs(int i) { + if (i == n) + return 0; + + int res = costs[0] + Dfs(i + 1); + + int j = i; + while (j < n && days[j] < days[i] + 7) + j++; + res = Math.Min(res, costs[1] + Dfs(j)); + + j = i; + while (j < n && days[j] < days[i] + 30) + j++; + res = Math.Min(res, costs[2] + Dfs(j)); + + return res; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -248,6 +281,39 @@ class Solution { } ``` +```csharp +public class Solution { + int[] days, costs; + Dictionary dp = new Dictionary(); + + public int MincostTickets(int[] days, int[] costs) { + this.days = days; + this.costs = costs; + return Dfs(0); + } + + private int Dfs(int i) { + if (i == days.Length) + return 0; + if (dp.ContainsKey(i)) + return dp[i]; + + dp[i] = int.MaxValue; + int j; + + int[] durations = {1, 7, 30}; + for (int k = 0; k < 3; k++) { + j = i; + while (j < days.Length && days[j] < days[i] + durations[k]) + j++; + dp[i] = Math.Min(dp[i], costs[k] + Dfs(j)); + } + + return dp[i]; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -351,6 +417,30 @@ class Solution { } ``` +```csharp +public class Solution { + public int MincostTickets(int[] days, int[] costs) { + int n = days.Length; + int[] dp = new int[n + 1]; + + for (int i = n - 1; i >= 0; i--) { + dp[i] = int.MaxValue; + int j = i; + for (int k = 0; k < 3; k++) { + int d = k == 0 ? 1 : k == 1 ? 7 : 30; + int c = costs[k]; + while (j < n && days[j] < days[i] + d) { + j++; + } + dp[i] = Math.Min(dp[i], c + dp[j]); + } + } + + return dp[0]; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -475,6 +565,37 @@ class Solution { } ``` +```csharp +public class Solution { + public int MincostTickets(int[] days, int[] costs) { + int n = days.Length; + int[] newDays = new int[n + 1]; + Array.Copy(days, newDays, n); + newDays[n] = days[n - 1] + 30; + n += 1; + + int[] dp = new int[n]; + int last7 = n, last30 = n; + + for (int i = n - 2; i >= 0; i--) { + dp[i] = dp[i + 1] + costs[0]; + + while (last7 > i + 1 && newDays[last7 - 1] >= newDays[i] + 7) { + last7--; + } + dp[i] = Math.Min(dp[i], costs[1] + dp[last7]); + + while (last30 > i + 1 && newDays[last30 - 1] >= newDays[i] + 30) { + last30--; + } + dp[i] = Math.Min(dp[i], costs[2] + dp[last30]); + } + + return dp[0]; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -592,6 +713,37 @@ class Solution { } ``` +```csharp +public class Solution { + public int MincostTickets(int[] days, int[] costs) { + Queue<(int day, int cost)> dp7 = new Queue<(int, int)>(); + Queue<(int day, int cost)> dp30 = new Queue<(int, int)>(); + int dp = 0; + + foreach (int d in days) { + while (dp7.Count > 0 && dp7.Peek().day + 7 <= d) { + dp7.Dequeue(); + } + + while (dp30.Count > 0 && dp30.Peek().day + 30 <= d) { + dp30.Dequeue(); + } + + dp7.Enqueue((d, dp + costs[1])); + dp30.Enqueue((d, dp + costs[2])); + + int cost1 = dp + costs[0]; + int cost7 = dp7.Peek().cost; + int cost30 = dp30.Peek().cost; + + dp = Math.Min(cost1, Math.Min(cost7, cost30)); + } + + return dp; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -721,6 +873,36 @@ class Solution { } ``` +```csharp +public class Solution { + public int MincostTickets(int[] days, int[] costs) { + Queue<(int day, int cost)> dp7 = new Queue<(int, int)>(); + Queue<(int day, int cost)> dp30 = new Queue<(int, int)>(); + int dp = 0; + int last7 = 0, last30 = 0; + + for (int i = days.Length - 1; i >= 0; i--) { + dp += costs[0]; + + while (dp7.Count > 0 && dp7.Peek().day >= days[i] + 7) { + last7 = dp7.Dequeue().cost; + } + dp = Math.Min(dp, costs[1] + last7); + + while (dp30.Count > 0 && dp30.Peek().day >= days[i] + 30) { + last30 = dp30.Dequeue().cost; + } + dp = Math.Min(dp, costs[2] + last30); + + dp7.Enqueue((days[i], dp)); + dp30.Enqueue((days[i], dp)); + } + + return dp; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -835,6 +1017,31 @@ class Solution { } ``` +```csharp +public class Solution { + public int MincostTickets(int[] days, int[] costs) { + int[] dp = new int[366]; + int i = 0; + + for (int d = 1; d <= 365; d++) { + dp[d] = dp[d - 1]; + if (i == days.Length) { + return dp[d]; + } + + if (d == days[i]) { + dp[d] += costs[0]; + dp[d] = Math.Min(dp[d], costs[1] + dp[Math.Max(0, d - 7)]); + dp[d] = Math.Min(dp[d], costs[2] + dp[Math.Max(0, d - 30)]); + i++; + } + } + + return dp[365]; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -953,6 +1160,32 @@ class Solution { } ``` +```csharp +public class Solution { + public int MincostTickets(int[] days, int[] costs) { + int[] dp = new int[31]; + int i = 0; + + for (int d = 1; d <= 365; d++) { + if (i >= days.Length) { + break; + } + + dp[d % 31] = dp[(d - 1) % 31]; + + if (d == days[i]) { + dp[d % 31] += costs[0]; + dp[d % 31] = Math.Min(dp[d % 31], costs[1] + dp[Math.Max(0, d - 7) % 31]); + dp[d % 31] = Math.Min(dp[d % 31], costs[2] + dp[Math.Max(0, d - 30) % 31]); + i++; + } + } + + return dp[days[days.Length - 1] % 31]; + } +} +``` + ::tabs-end ### Time & Space Complexity diff --git a/articles/minimum-time-to-collect-all-apples-in-a-tree.md b/articles/minimum-time-to-collect-all-apples-in-a-tree.md index 8ad4a4804..617eb8575 100644 --- a/articles/minimum-time-to-collect-all-apples-in-a-tree.md +++ b/articles/minimum-time-to-collect-all-apples-in-a-tree.md @@ -112,6 +112,33 @@ class Solution { } ``` +```csharp +public class Solution { + public int MinTime(int n, int[][] edges, List hasApple) { + var adj = new Dictionary>(); + for (int i = 0; i < n; i++) adj[i] = new List(); + foreach (var e in edges) { + adj[e[0]].Add(e[1]); + adj[e[1]].Add(e[0]); + } + + int Dfs(int cur, int par) { + int time = 0; + foreach (var child in adj[cur]) { + if (child == par) continue; + int childTime = Dfs(child, cur); + if (childTime > 0 || hasApple[child]) { + time += 2 + childTime; + } + } + return time; + } + + return Dfs(0, -1); + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -302,6 +329,47 @@ class Solution { } ``` +```csharp +public class Solution { + public int MinTime(int n, int[][] edges, List hasApple) { + var adj = new Dictionary>(); + for (int i = 0; i < n; i++) adj[i] = new List(); + + int[] indegree = new int[n]; + foreach (var e in edges) { + adj[e[0]].Add(e[1]); + adj[e[1]].Add(e[0]); + indegree[e[0]]++; + indegree[e[1]]++; + } + + var queue = new Queue(); + for (int i = 1; i < n; i++) { + if (indegree[i] == 1) { + queue.Enqueue(i); + indegree[i] = 0; + } + } + + int[] time = new int[n]; + while (queue.Count > 0) { + int node = queue.Dequeue(); + foreach (var nei in adj[node]) { + if (indegree[nei] <= 0) continue; + + indegree[nei]--; + if (hasApple[node] || time[node] > 0) + time[nei] += time[node] + 2; + if (indegree[nei] == 1 && nei != 0) + queue.Enqueue(nei); + } + } + + return time[0]; + } +} +``` + ::tabs-end ### Time & Space Complexity diff --git a/articles/rearrange-array-elements-by-sign.md b/articles/rearrange-array-elements-by-sign.md index 02e465145..79da7c04c 100644 --- a/articles/rearrange-array-elements-by-sign.md +++ b/articles/rearrange-array-elements-by-sign.md @@ -106,6 +106,34 @@ class Solution { } ``` +```csharp +public class Solution { + public int[] RearrangeArray(int[] nums) { + int n = nums.Length; + + for (int i = 0; i < n; i++) { + if ((i % 2 == 0 && nums[i] > 0) || (i % 2 == 1 && nums[i] < 0)) { + continue; + } + + int j = i + 1; + while (j < n && ((nums[j] > 0) == (nums[i] > 0))) { + j++; + } + + int tmp = nums[j]; + while (j > i) { + nums[j] = nums[j - 1]; + j--; + } + nums[i] = tmp; + } + + return nums; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -213,6 +241,29 @@ class Solution { } ``` +```csharp +public class Solution { + public int[] RearrangeArray(int[] nums) { + List pos = new List(); + List neg = new List(); + + foreach (int num in nums) { + if (num > 0) pos.Add(num); + else neg.Add(num); + } + + int i = 0; + while (2 * i < nums.Length) { + nums[2 * i] = pos[i]; + nums[2 * i + 1] = neg[i]; + i++; + } + + return nums; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -304,6 +355,27 @@ class Solution { } ``` +```csharp +public class Solution { + public int[] RearrangeArray(int[] nums) { + int i = 0, j = 1; + int[] res = new int[nums.Length]; + + for (int k = 0; k < nums.Length; k++) { + if (nums[k] > 0) { + res[i] = nums[k]; + i += 2; + } else { + res[j] = nums[k]; + j += 2; + } + } + + return res; + } +} +``` + ::tabs-end ### Time & Space Complexity From 043eed7f9ece3f0e6c171f744145a77565605306 Mon Sep 17 00:00:00 2001 From: Sri Hari Date: Sat, 18 Oct 2025 13:04:04 +0530 Subject: [PATCH 2/5] Added articles --- articles/count-primes.md | 346 ++++++++++++++++++ articles/find-the-difference-of-two-arrays.md | 102 ++++++ articles/largest-divisible-subset.md | 187 ++++++++++ articles/maximal-square.md | 137 +++++++ 4 files changed, 772 insertions(+) create mode 100644 articles/count-primes.md diff --git a/articles/count-primes.md b/articles/count-primes.md new file mode 100644 index 000000000..2e18770e0 --- /dev/null +++ b/articles/count-primes.md @@ -0,0 +1,346 @@ +## 1. Brute Force + +::tabs-start + +```python +class Solution: + def countPrimes(self, n: int) -> int: + res = 0 + for num in range(2, n): + isPrime = True + for i in range(2, int(num ** 0.5) + 1): + if num % i == 0: + isPrime = False + break + if isPrime: + res += 1 + return res +``` + +```java +public class Solution { + public int countPrimes(int n) { + int res = 0; + for (int num = 2; num < n; num++) { + boolean isPrime = true; + for (int i = 2; i * i <= num; i++) { + if (num % i == 0) { + isPrime = false; + break; + } + } + if (isPrime) { + res++; + } + } + return res; + } +} +``` + +```cpp +class Solution { +public: + int countPrimes(int n) { + int res = 0; + for (int num = 2; num < n; num++) { + bool isPrime = true; + for (int i = 2; i * i <= num; i++) { + if (num % i == 0) { + isPrime = false; + break; + } + } + if (isPrime) res++; + } + return res; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number} n + * @return {number} + */ + countPrimes(n) { + let res = 0; + for (let num = 2; num < n; num++) { + let isPrime = true; + for (let i = 2; i * i <= num; i++) { + if (num % i === 0) { + isPrime = false; + break; + } + } + if (isPrime) res++; + } + return res; + } +} +``` + +```csharp +public class Solution { + public int CountPrimes(int n) { + int res = 0; + for (int num = 2; num < n; num++) { + bool isPrime = true; + for (int i = 2; i * i <= num; i++) { + if (num % i == 0) { + isPrime = false; + break; + } + } + if (isPrime) { + res++; + } + } + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n \sqrt {n})$ +* Space complexity: $O(1)$ + +--- + +## 2. Sieve of Eratosthenes + +::tabs-start + +```python +class Solution: + def countPrimes(self, n: int) -> int: + sieve = [False] * n + res = 0 + for num in range(2, n): + if not sieve[num]: + res += 1 + for i in range(num * num, n, num): + sieve[i] = True + return res +``` + +```java +public class Solution { + public int countPrimes(int n) { + boolean[] sieve = new boolean[n]; + int res = 0; + for (int num = 2; num < n; num++) { + if (!sieve[num]) { + res++; + for (long i = num * 1L * num; i < n; i += num) { + sieve[(int) i] = true; + } + } + } + return res; + } +} +``` + +```cpp +class Solution { +public: + int countPrimes(int n) { + vector sieve(n, false); + int res = 0; + for (int num = 2; num < n; num++) { + if (!sieve[num]) { + res++; + for (long long i = 1LL * num * num; i < n; i += num) { + sieve[i] = true; + } + } + } + return res; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number} n + * @return {number} + */ + countPrimes(n) { + const sieve = new Array(n).fill(false); + let res = 0; + for (let num = 2; num < n; num++) { + if (!sieve[num]) { + res++; + for (let i = num * num; i < n; i += num) { + sieve[i] = true; + } + } + } + return res; + } +} +``` + +```csharp +public class Solution { + public int CountPrimes(int n) { + bool[] sieve = new bool[n]; + int res = 0; + for (int num = 2; num < n; num++) { + if (!sieve[num]) { + res++; + for (long i = (long)num * num; i < n; i += num) { + sieve[(int)i] = true; + } + } + } + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n \log (\log n))$ +* Space complexity: $O(n)$ + +--- + +## 3. Sieve of Eratosthenes (Optimal) + +::tabs-start + +```python +class Solution: + def countPrimes(self, n: int) -> int: + if n < 3: + return 0 + + isPrime = [False] * n + count = n // 2 + + for i in range(3, int(n ** 0.5) + 1, 2): + if not isPrime[i]: + for j in range(i * i, n, 2 * i): + if not isPrime[j]: + isPrime[j] = True + count -= 1 + + return count +``` + +```java +public class Solution { + public int countPrimes(int n) { + if (n < 3) return 0; + + boolean[] isPrime = new boolean[n]; + int count = n / 2; + + for (int i = 3; i * i < n; i += 2) { + if (!isPrime[i]) { + for (int j = i * i; j < n; j += 2 * i) { + if (!isPrime[j]) { + isPrime[j] = true; + count--; + } + } + } + } + + return count; + } +} +``` + +```cpp +class Solution { +public: + int countPrimes(int n) { + if (n < 3) return 0; + + vector isPrime(n, false); + int count = n / 2; + + for (int i = 3; i * i < n; i += 2) { + if (!isPrime[i]) { + for (int j = i * i; j < n; j += 2 * i) { + if (!isPrime[j]) { + isPrime[j] = true; + count--; + } + } + } + } + + return count; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number} n + * @return {number} + */ + countPrimes(n) { + if (n < 3) return 0; + + const isPrime = new Array(n).fill(false); + let count = Math.floor(n / 2); + + for (let i = 3; i * i < n; i += 2) { + if (!isPrime[i]) { + for (let j = i * i; j < n; j += 2 * i) { + if (!isPrime[j]) { + isPrime[j] = true; + count--; + } + } + } + } + + return count; + } +} +``` + +```csharp +public class Solution { + public int CountPrimes(int n) { + if (n < 3) return 0; + + bool[] isPrime = new bool[n]; + int count = n / 2; + + for (int i = 3; i * i < n; i += 2) { + if (!isPrime[i]) { + for (int j = i * i; j < n; j += 2 * i) { + if (!isPrime[j]) { + isPrime[j] = true; + count--; + } + } + } + } + + return count; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n \log (\log n))$ +* Space complexity: $O(n)$ \ No newline at end of file diff --git a/articles/find-the-difference-of-two-arrays.md b/articles/find-the-difference-of-two-arrays.md index 08f994bbc..77f4f795c 100644 --- a/articles/find-the-difference-of-two-arrays.md +++ b/articles/find-the-difference-of-two-arrays.md @@ -148,6 +148,41 @@ class Solution { } ``` +```csharp +public class Solution { + public List> FindDifference(int[] nums1, int[] nums2) { + var res = new List> { new HashSet(), new HashSet() }; + + foreach (int num1 in nums1) { + bool found = false; + foreach (int num2 in nums2) { + if (num1 == num2) { + found = true; + break; + } + } + if (!found) res[0].Add(num1); + } + + foreach (int num2 in nums2) { + bool found = false; + foreach (int num1 in nums1) { + if (num1 == num2) { + found = true; + break; + } + } + if (!found) res[1].Add(num2); + } + + return new List> { + res[0].ToList(), + res[1].ToList() + }; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -279,6 +314,27 @@ class Solution { } ``` +```csharp +public class Solution { + public List> FindDifference(int[] nums1, int[] nums2) { + var num1Set = new HashSet(nums1); + var num2Set = new HashSet(nums2); + var res1 = new List(); + var res2 = new List(); + + foreach (int num in num1Set) { + if (!num2Set.Contains(num)) res1.Add(num); + } + + foreach (int num in num2Set) { + if (!num1Set.Contains(num)) res2.Add(num); + } + + return new List> { res1, res2 }; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -382,6 +438,23 @@ class Solution { } ``` +```csharp +public class Solution { + public List> FindDifference(int[] nums1, int[] nums2) { + var numSet1 = new HashSet(nums1); + var numSet2 = new HashSet(nums2); + + var res1 = new List(numSet1); + res1.RemoveAll(num => numSet2.Contains(num)); + + var res2 = new List(numSet2); + res2.RemoveAll(num => numSet1.Contains(num)); + + return new List> { res1, res2 }; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -457,6 +530,35 @@ class Solution { } ``` +```csharp +public class Solution { + public List> FindDifference(int[] nums1, int[] nums2) { + Array.Sort(nums1); + Array.Sort(nums2); + + var diff1 = Helper(nums1, nums2); + var diff2 = Helper(nums2, nums1); + + return new List> { diff1, diff2 }; + } + + private List Helper(int[] A, int[] B) { + int n = A.Length, m = B.Length, j = 0; + var res = new List(); + int prev = int.MinValue; + + foreach (int num in A) { + if (num == prev) continue; + while (j < m && B[j] < num) j++; + if (j == m || B[j] != num) res.Add(num); + prev = num; + } + + return res; + } +} +``` + ::tabs-end ### Time & Space Complexity diff --git a/articles/largest-divisible-subset.md b/articles/largest-divisible-subset.md index 1fc86d067..15ee72e70 100644 --- a/articles/largest-divisible-subset.md +++ b/articles/largest-divisible-subset.md @@ -117,6 +117,39 @@ class Solution { } ``` +```csharp +public class Solution { + private List[][] cache; + private int[] nums; + + public List LargestDivisibleSubset(int[] nums) { + Array.Sort(nums); + this.nums = nums; + int n = nums.Length; + cache = new List[n + 1][]; + for (int i = 0; i <= n; i++) { + cache[i] = new List[n + 1]; + } + return Dfs(0, -1); + } + + private List Dfs(int i, int prevIndex) { + if (i == nums.Length) return new List(); + if (cache[i][prevIndex + 1] != null) return cache[i][prevIndex + 1]; + + List res = Dfs(i + 1, prevIndex); + if (prevIndex == -1 || nums[i] % nums[prevIndex] == 0) { + List tmp = new List { nums[i] }; + tmp.AddRange(Dfs(i + 1, i)); + if (tmp.Count > res.Count) res = tmp; + } + + cache[i][prevIndex + 1] = res; + return res; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -277,6 +310,46 @@ class Solution { } ``` +```csharp +public class Solution { + private Dictionary> cache; + private int[] nums; + + public List LargestDivisibleSubset(int[] nums) { + Array.Sort(nums); + this.nums = nums; + cache = new Dictionary>(); + List res = new List(); + + for (int i = 0; i < nums.Length; i++) { + List tmp = Dfs(i); + if (tmp.Count > res.Count) { + res = tmp; + } + } + return res; + } + + private List Dfs(int i) { + if (cache.ContainsKey(i)) return cache[i]; + + List res = new List { nums[i] }; + for (int j = i + 1; j < nums.Length; j++) { + if (nums[j] % nums[i] == 0) { + List tmp = new List { nums[i] }; + tmp.AddRange(Dfs(j)); + if (tmp.Count > res.Count) { + res = tmp; + } + } + } + + cache[i] = res; + return res; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -401,6 +474,32 @@ class Solution { } ``` +```csharp +public class Solution { + public List LargestDivisibleSubset(int[] nums) { + Array.Sort(nums); + List> dp = new List>(); + foreach (int num in nums) { + dp.Add(new List { num }); + } + + List res = new List(); + for (int i = nums.Length - 1; i >= 0; i--) { + for (int j = i + 1; j < nums.Length; j++) { + if (nums[j] % nums[i] == 0) { + List tmp = new List { nums[i] }; + tmp.AddRange(dp[j]); + if (tmp.Count > dp[i].Count) dp[i] = tmp; + } + } + if (dp[i].Count > res.Count) res = dp[i]; + } + + return res; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -587,6 +686,57 @@ class Solution { } ``` +```csharp +public class Solution { + private int[][] dp; + private int[] nums; + private int n; + + public List LargestDivisibleSubset(int[] nums) { + Array.Sort(nums); + this.nums = nums; + n = nums.Length; + dp = new int[n][]; + for (int i = 0; i < n; i++) { + dp[i] = new int[] { -1, -1 }; + } + + int maxLen = 1, startIndex = 0; + for (int i = 0; i < n; i++) { + if (Dfs(i) > maxLen) { + maxLen = Dfs(i); + startIndex = i; + } + } + + List subset = new List(); + while (startIndex != -1) { + subset.Add(nums[startIndex]); + startIndex = dp[startIndex][1]; + } + + return subset; + } + + private int Dfs(int i) { + if (dp[i][0] != -1) return dp[i][0]; + + dp[i][0] = 1; + for (int j = i + 1; j < n; j++) { + if (nums[j] % nums[i] == 0) { + int length = Dfs(j) + 1; + if (length > dp[i][0]) { + dp[i][0] = length; + dp[i][1] = j; + } + } + } + + return dp[i][0]; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -732,6 +882,43 @@ class Solution { } ``` +```csharp +public class Solution { + public List LargestDivisibleSubset(int[] nums) { + Array.Sort(nums); + int n = nums.Length; + int[][] dp = new int[n][]; + for (int i = 0; i < n; i++) { + dp[i] = new int[] { 1, -1 }; + } + + int maxLen = 1, startIndex = 0; + + for (int i = 0; i < n; i++) { + for (int j = 0; j < i; j++) { + if (nums[i] % nums[j] == 0 && dp[j][0] + 1 > dp[i][0]) { + dp[i][0] = dp[j][0] + 1; + dp[i][1] = j; + } + } + + if (dp[i][0] > maxLen) { + maxLen = dp[i][0]; + startIndex = i; + } + } + + List subset = new List(); + while (startIndex != -1) { + subset.Add(nums[startIndex]); + startIndex = dp[startIndex][1]; + } + + return subset; + } +} +``` + ::tabs-end ### Time & Space Complexity diff --git a/articles/maximal-square.md b/articles/maximal-square.md index fd294c36f..824f01303 100644 --- a/articles/maximal-square.md +++ b/articles/maximal-square.md @@ -176,6 +176,47 @@ class Solution { } ``` +```csharp +public class Solution { + public int MaximalSquare(char[][] matrix) { + int m = matrix.Length; + int n = matrix[0].Length; + int res = 0; + + for (int r = 0; r < m; r++) { + for (int c = 0; c < n; c++) { + if (matrix[r][c] == '0') continue; + int k = 1; + while (true) { + if (r + k > m || c + k > n) break; + bool flag = true; + + for (int i = r; i < r + k; i++) { + if (matrix[i][c + k - 1] == '0') { + flag = false; + break; + } + } + + for (int j = c; j < c + k; j++) { + if (matrix[r + k - 1][j] == '0') { + flag = false; + break; + } + } + + if (!flag) break; + res = Math.Max(res, k * k); + k++; + } + } + } + + return res; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -334,6 +375,52 @@ class Solution { } ``` +```csharp +public class Solution { + private int[][] dp; + + public int MaximalSquare(char[][] matrix) { + int ROWS = matrix.Length, COLS = matrix[0].Length; + dp = new int[ROWS][]; + for (int i = 0; i < ROWS; i++) { + dp[i] = new int[COLS]; + for (int j = 0; j < COLS; j++) { + dp[i][j] = -1; + } + } + + Dfs(0, 0, matrix); + int maxSquare = 0; + for (int i = 0; i < ROWS; i++) { + for (int j = 0; j < COLS; j++) { + maxSquare = Math.Max(maxSquare, dp[i][j]); + } + } + return maxSquare * maxSquare; + } + + private int Dfs(int r, int c, char[][] matrix) { + if (r >= matrix.Length || c >= matrix[0].Length) { + return 0; + } + if (dp[r][c] != -1) { + return dp[r][c]; + } + + int down = Dfs(r + 1, c, matrix); + int right = Dfs(r, c + 1, matrix); + int diag = Dfs(r + 1, c + 1, matrix); + + dp[r][c] = 0; + if (matrix[r][c] == '1') { + dp[r][c] = 1 + Math.Min(down, Math.Min(right, diag)); + } + + return dp[r][c]; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -436,6 +523,30 @@ class Solution { } ``` +```csharp +public class Solution { + public int MaximalSquare(char[][] matrix) { + int m = matrix.Length, n = matrix[0].Length; + int[][] dp = new int[m + 1][]; + for (int i = 0; i <= m; i++) { + dp[i] = new int[n + 1]; + } + + int maxSquare = 0; + for (int r = m - 1; r >= 0; r--) { + for (int c = n - 1; c >= 0; c--) { + if (matrix[r][c] == '1') { + dp[r][c] = 1 + Math.Min(dp[r + 1][c], Math.Min(dp[r][c + 1], dp[r + 1][c + 1])); + maxSquare = Math.Max(maxSquare, dp[r][c]); + } + } + } + + return maxSquare * maxSquare; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -556,6 +667,32 @@ class Solution { } ``` +```csharp +public class Solution { + public int MaximalSquare(char[][] matrix) { + int m = matrix.Length, n = matrix[0].Length; + int[] dp = new int[n + 1]; + int maxSquare = 0; + + for (int r = m - 1; r >= 0; r--) { + int prev = 0; + for (int c = n - 1; c >= 0; c--) { + int temp = dp[c]; + if (matrix[r][c] == '1') { + dp[c] = 1 + Math.Min(dp[c], Math.Min(dp[c + 1], prev)); + maxSquare = Math.Max(maxSquare, dp[c]); + } else { + dp[c] = 0; + } + prev = temp; + } + } + + return maxSquare * maxSquare; + } +} +``` + ::tabs-end ### Time & Space Complexity From 8b13332d096d7a0f85c34bd28e7747bbd33e7074 Mon Sep 17 00:00:00 2001 From: Sri Hari Date: Tue, 28 Oct 2025 22:03:23 +0530 Subject: [PATCH 3/5] Added articles --- ...ree-from-preorder-and-inorder-traversal.md | 342 ++++++++++++++++++ articles/insertion-sort-list.md | 108 ++++++ articles/k-closest-points-to-origin.md | 2 +- articles/length-of-last-word.md | 42 +++ ...inimum-number-of-moves-to-seat-everyone.md | 49 +++ ...umber-of-operations-to-make-array-empty.md | 122 +++++++ ...es-that-satisfy-the-given-sum-condition.md | 123 +++++++ articles/sort-an-array.md | 14 +- .../sort-array-by-increasing-frequency.md | 14 + 9 files changed, 808 insertions(+), 8 deletions(-) diff --git a/articles/binary-tree-from-preorder-and-inorder-traversal.md b/articles/binary-tree-from-preorder-and-inorder-traversal.md index 04b56213c..d9aafb577 100644 --- a/articles/binary-tree-from-preorder-and-inorder-traversal.md +++ b/articles/binary-tree-from-preorder-and-inorder-traversal.md @@ -912,3 +912,345 @@ class Solution { - Time complexity: $O(n)$ - Space complexity: $O(n)$ for recursion stack. + +--- + +## 4. Morris Traversal + +::tabs-start + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: + head = TreeNode(None) + curr = head + i, j, n = 0, 0, len(preorder) + while i < n and j < n: + # Go right and then as far left as possible + curr.right = TreeNode(preorder[i], right = curr.right) + curr = curr.right + i += 1 + while i < n and curr.val != inorder[j]: + curr.left = TreeNode(preorder[i], right=curr) + curr = curr.left + i += 1 + j += 1 + while curr.right and j < n and curr.right.val == inorder[j]: + prev = curr.right + curr.right = None + curr = prev + j += 1 + + return head.right +``` + +```java +/** + * 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; + * } + * } + */ +public class Solution { + public TreeNode buildTree(int[] preorder, int[] inorder) { + TreeNode head = new TreeNode(0); + TreeNode curr = head; + int i = 0, j = 0, n = preorder.length; + + while (i < n && j < n) { + curr.right = new TreeNode(preorder[i], null, curr.right); + curr = curr.right; + i++; + while (i < n && curr.val != inorder[j]) { + curr.left = new TreeNode(preorder[i], null, curr); + curr = curr.left; + i++; + } + j++; + while (curr.right != null && j < n && curr.right.val == inorder[j]) { + TreeNode prev = curr.right; + curr.right = null; + curr = prev; + j++; + } + } + return head.right; + } +} +``` + +```cpp +/** + * 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: + TreeNode* buildTree(vector& preorder, vector& inorder) { + TreeNode* head = new TreeNode(0); + TreeNode* curr = head; + int i = 0, j = 0, n = preorder.size(); + + while (i < n && j < n) { + curr->right = new TreeNode(preorder[i], nullptr, curr->right); + curr = curr->right; + i++; + while (i < n && curr->val != inorder[j]) { + curr->left = new TreeNode(preorder[i], nullptr, curr); + curr = curr->left; + i++; + } + j++; + while (curr->right && j < n && curr->right->val == inorder[j]) { + TreeNode* prev = curr->right; + curr->right = nullptr; + curr = prev; + j++; + } + } + return head->right; + } +}; +``` + +```javascript +/** + * Definition for a binary tree node. + * class TreeNode { + * constructor(val = 0, left = null, right = null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ + +class Solution { + /** + * @param {number[]} preorder + * @param {number[]} inorder + * @return {TreeNode} + */ + buildTree(preorder, inorder) { + let head = new TreeNode(null); + let curr = head; + let i = 0, j = 0, n = preorder.length; + + while (i < n && j < n) { + curr.right = new TreeNode(preorder[i], null, curr.right); + curr = curr.right; + i++; + while (i < n && curr.val !== inorder[j]) { + curr.left = new TreeNode(preorder[i], null, curr); + curr = curr.left; + i++; + } + j++; + while (curr.right && j < n && curr.right.val === inorder[j]) { + let prev = curr.right; + curr.right = null; + curr = prev; + j++; + } + } + return head.right; + } +} +``` + +```csharp +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +public class Solution { + public TreeNode BuildTree(int[] preorder, int[] inorder) { + TreeNode head = new TreeNode(0); + TreeNode curr = head; + int i = 0, j = 0, n = preorder.Length; + + while (i < n && j < n) { + curr.right = new TreeNode(preorder[i], null, curr.right); + curr = curr.right; + i++; + while (i < n && curr.val != inorder[j]) { + curr.left = new TreeNode(preorder[i], null, curr); + curr = curr.left; + i++; + } + j++; + while (curr.right != null && j < n && curr.right.val == inorder[j]) { + TreeNode prev = curr.right; + curr.right = null; + curr = prev; + j++; + } + } + return head.right; + } +} +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func buildTree(preorder []int, inorder []int) *TreeNode { + head := &TreeNode{} + curr := head + i, j, n := 0, 0, len(preorder) + + for i < n && j < n { + curr.Right = &TreeNode{Val: preorder[i], Right: curr.Right} + curr = curr.Right + i++ + for i < n && curr.Val != inorder[j] { + curr.Left = &TreeNode{Val: preorder[i], Right: curr} + curr = curr.Left + i++ + } + j++ + for curr.Right != nil && j < n && curr.Right.Val == inorder[j] { + prev := curr.Right + curr.Right = nil + curr = prev + j++ + } + } + return head.Right +} +``` + +```kotlin +/** + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +class Solution { + fun buildTree(preorder: IntArray, inorder: IntArray): TreeNode? { + val head = TreeNode(0) + var curr: TreeNode? = head + var i = 0 + var j = 0 + val n = preorder.size + + while (i < n && j < n) { + curr!!.right = TreeNode(preorder[i], null, curr.right) + curr = curr.right + i++ + while (i < n && curr!!.`val` != inorder[j]) { + curr.left = TreeNode(preorder[i], null, curr) + curr = curr.left + i++ + } + j++ + while (curr!!.right != null && j < n && curr.right!!.`val` == inorder[j]) { + val prev = curr.right + curr.right = null + curr = prev + j++ + } + } + return head.right + } +} +``` + +```swift +/** + * Definition for a binary tree node. + * public class TreeNode { + * public var val: Int + * public var left: TreeNode? + * public var right: TreeNode? + * public init() { self.val = 0; self.left = nil; self.right = nil; } + * public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; } + * public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) { + * self.val = val + * self.left = left + * self.right = right + * } + * } + */ +class Solution { + func buildTree(_ preorder: [Int], _ inorder: [Int]) -> TreeNode? { + let head = TreeNode(0) + var curr: TreeNode? = head + var i = 0, j = 0 + let n = preorder.count + + while i < n && j < n { + curr!.right = TreeNode(preorder[i], nil, curr!.right) + curr = curr!.right + i += 1 + + while i < n && curr!.val != inorder[j] { + curr!.left = TreeNode(preorder[i], nil, curr) + curr = curr!.left + i += 1 + } + + j += 1 + while curr!.right != nil && j < n && curr!.right!.val == inorder[j] { + let prev = curr!.right + curr!.right = nil + curr = prev + j += 1 + } + } + + return head.right + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: + * $O(1)$ extra space. + * $O(n)$ for the output tree. \ No newline at end of file diff --git a/articles/insertion-sort-list.md b/articles/insertion-sort-list.md index d729a6b95..0b7ec9552 100644 --- a/articles/insertion-sort-list.md +++ b/articles/insertion-sort-list.md @@ -127,6 +127,38 @@ class Solution { } ``` +```csharp +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode InsertionSortList(ListNode head) { + List arr = new List(); + ListNode cur = head; + while (cur != null) { + arr.Add(cur.val); + cur = cur.next; + } + + arr.Sort(); + cur = head; + foreach (int val in arr) { + cur.val = val; + cur = cur.next; + } + return head; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -240,6 +272,40 @@ class Solution { } ``` +```csharp +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode InsertionSortList(ListNode head) { + if (head == null) return head; + + ListNode cur = head.next; + while (cur != null) { + ListNode tmp = head; + while (tmp != cur) { + if (tmp.val > cur.val) { + int t = tmp.val; + tmp.val = cur.val; + cur.val = t; + } + tmp = tmp.next; + } + cur = cur.next; + } + return head; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -404,6 +470,48 @@ class Solution { } ``` +```csharp +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode InsertionSortList(ListNode head) { + if (head == null) return head; + + ListNode dummy = new ListNode(0, head); + ListNode prev = head, cur = head.next; + + while (cur != null) { + if (cur.val >= prev.val) { + prev = cur; + cur = cur.next; + continue; + } + + ListNode tmp = dummy; + while (cur.val > tmp.next.val) { + tmp = tmp.next; + } + + prev.next = cur.next; + cur.next = tmp.next; + tmp.next = cur; + cur = prev.next; + } + + return dummy.next; + } +} +``` + ::tabs-end ### Time & Space Complexity diff --git a/articles/k-closest-points-to-origin.md b/articles/k-closest-points-to-origin.md index 950ee2098..b999e0c70 100644 --- a/articles/k-closest-points-to-origin.md +++ b/articles/k-closest-points-to-origin.md @@ -288,7 +288,7 @@ class Solution { ### Time & Space Complexity -- Time complexity: $O(k * \log n)$ +- Time complexity: $O(n + k * \log n)$ - Space complexity: $O(n)$ > Where $n$ is the length of the array $points$. diff --git a/articles/length-of-last-word.md b/articles/length-of-last-word.md index 8952e481b..cfc9b5c29 100644 --- a/articles/length-of-last-word.md +++ b/articles/length-of-last-word.md @@ -94,6 +94,25 @@ class Solution { } ``` +```csharp +public class Solution { + public int LengthOfLastWord(string s) { + int length = 0, i = 0; + while (i < s.Length) { + if (s[i] == ' ') { + while (i < s.Length && s[i] == ' ') i++; + if (i == s.Length) return length; + length = 0; + } else { + length++; + i++; + } + } + return length; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -174,6 +193,20 @@ class Solution { } ``` +```csharp +public class Solution { + public int LengthOfLastWord(string s) { + int i = s.Length - 1, length = 0; + while (i >= 0 && s[i] == ' ') i--; + while (i >= 0 && s[i] != ' ') { + length++; + i--; + } + return length; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -224,6 +257,15 @@ class Solution { } ``` +```csharp +public class Solution { + public int LengthOfLastWord(string s) { + var parts = s.Split(' ', StringSplitOptions.RemoveEmptyEntries); + return parts[^1].Length; + } +} +``` + ::tabs-end ### Time & Space Complexity diff --git a/articles/minimum-number-of-moves-to-seat-everyone.md b/articles/minimum-number-of-moves-to-seat-everyone.md index e2ed02e82..91e9a578c 100644 --- a/articles/minimum-number-of-moves-to-seat-everyone.md +++ b/articles/minimum-number-of-moves-to-seat-everyone.md @@ -3,15 +3,46 @@ ::tabs-start ```python +class Solution: + def minMovesToSeat(self, seats: List[int], students: List[int]) -> int: + seats.sort() + students.sort() + res = 0 + for i in range(len(seats)): + res += abs(seats[i] - students[i]) + return res ``` ```java +public class Solution { + public int minMovesToSeat(int[] seats, int[] students) { + Arrays.sort(seats); + Arrays.sort(students); + int res = 0; + for (int i = 0; i < seats.length; i++) { + res += Math.abs(seats[i] - students[i]); + } + return res; + } +} ``` ```cpp +class Solution { +public: + int minMovesToSeat(vector& seats, vector& students) { + sort(seats.begin(), seats.end()); + sort(students.begin(), students.end()); + int res = 0; + for (int i = 0; i < seats.size(); i++) { + res += abs(seats[i] - students[i]); + } + return res; + } +}; ``` ```javascript @@ -22,13 +53,31 @@ class Solution { * @return {number} */ minMovesToSeat(seats, students) { + seats.sort((a, b) => a - b); + students.sort((a, b) => a - b); + let res = 0; + for (let i = 0; i < seats.length; i++) { + res += Math.abs(seats[i] - students[i]); + } + return res; } } ``` ```csharp +public class Solution { + public int MinMovesToSeat(int[] seats, int[] students) { + Array.Sort(seats); + Array.Sort(students); + int res = 0; + for (int i = 0; i < seats.Length; i++) { + res += Math.Abs(seats[i] - students[i]); + } + return res; + } +} ``` ::tabs-end diff --git a/articles/minimum-number-of-operations-to-make-array-empty.md b/articles/minimum-number-of-operations-to-make-array-empty.md index f0cd1394b..1a16919f9 100644 --- a/articles/minimum-number-of-operations-to-make-array-empty.md +++ b/articles/minimum-number-of-operations-to-make-array-empty.md @@ -133,6 +133,36 @@ class Solution { } ``` +```csharp +public class Solution { + public int MinOperations(int[] nums) { + Dictionary count = new Dictionary(); + foreach (int num in nums) { + if (!count.ContainsKey(num)) count[num] = 0; + count[num]++; + } + + int Dfs(int cur) { + if (cur < 0) return int.MaxValue; + if (cur == 0) return 0; + + int ops = Math.Min(Dfs(cur - 2), Dfs(cur - 3)); + if (ops == int.MaxValue) return int.MaxValue; + return 1 + ops; + } + + int res = 0; + foreach (var kvp in count) { + int op = Dfs(kvp.Value); + if (op == int.MaxValue) return -1; + res += op; + } + + return res; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -301,6 +331,43 @@ class Solution { } ``` +```csharp +public class Solution { + public int MinOperations(int[] nums) { + Dictionary count = new Dictionary(); + foreach (int num in nums) { + if (!count.ContainsKey(num)) count[num] = 0; + count[num]++; + } + + Dictionary cache = new Dictionary(); + + int Dfs(int num) { + if (num < 0) return int.MaxValue; + if (num == 2 || num == 3) return 1; + if (cache.ContainsKey(num)) return cache[num]; + + int res = Math.Min(Dfs(num - 2), Dfs(num - 3)); + if (res == int.MaxValue) { + cache[num] = int.MaxValue; + } else { + cache[num] = res + 1; + } + return cache[num]; + } + + int resTotal = 0; + foreach (var kvp in count) { + int op = Dfs(kvp.Value); + if (op == int.MaxValue) return -1; + resTotal += op; + } + + return resTotal; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -458,6 +525,40 @@ class Solution { } ``` +```csharp +public class Solution { + public int MinOperations(int[] nums) { + Dictionary count = new Dictionary(); + foreach (int num in nums) { + if (!count.ContainsKey(num)) count[num] = 0; + count[num]++; + } + + int maxf = count.Values.Max(); + int[] minOps = new int[maxf + 1]; + for (int i = 0; i <= maxf; i++) minOps[i] = 0; + minOps[1] = int.MaxValue; + + for (int i = 2; i <= maxf; i++) { + minOps[i] = minOps[i - 2]; + if (i - 3 >= 0) + minOps[i] = Math.Min(minOps[i], minOps[i - 3]); + if (minOps[i] != int.MaxValue) + minOps[i] += 1; + } + + int res = 0; + foreach (var kvp in count) { + int op = minOps[kvp.Value]; + if (op == int.MaxValue) return -1; + res += op; + } + + return res; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -555,6 +656,27 @@ class Solution { } ``` +```csharp +public class Solution { + public int MinOperations(int[] nums) { + Dictionary count = new Dictionary(); + foreach (int num in nums) { + if (!count.ContainsKey(num)) count[num] = 0; + count[num]++; + } + + int res = 0; + foreach (var kvp in count) { + int cnt = kvp.Value; + if (cnt == 1) return -1; + res += (int)Math.Ceiling(cnt / 3.0); + } + + return res; + } +} +``` + ::tabs-end ### Time & Space Complexity diff --git a/articles/number-of-subsequences-that-satisfy-the-given-sum-condition.md b/articles/number-of-subsequences-that-satisfy-the-given-sum-condition.md index d54c5e2c2..daed91891 100644 --- a/articles/number-of-subsequences-that-satisfy-the-given-sum-condition.md +++ b/articles/number-of-subsequences-that-satisfy-the-given-sum-condition.md @@ -100,6 +100,32 @@ class Solution { } ``` +```csharp +public class Solution { + const int MOD = 1000000007; + int[] nums; + int target; + + public int NumSubseq(int[] nums, int target) { + this.nums = nums; + this.target = target; + return Dfs(int.MinValue, int.MaxValue, 0); + } + + int Dfs(int maxi, int mini, int i) { + if (i == nums.Length) { + if (mini != int.MaxValue && (maxi + mini) <= target) + return 1; + return 0; + } + + int skip = Dfs(maxi, mini, i + 1); + int include = Dfs(Math.Max(maxi, nums[i]), Math.Min(mini, nums[i]), i + 1); + return (int)(((long)skip + include) % MOD); + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -263,6 +289,42 @@ class Solution { } ``` +```csharp +public class Solution { + public int NumSubseq(int[] nums, int target) { + Array.Sort(nums); + const int MOD = 1000000007; + long res = 0; + + for (int i = 0; i < nums.Length; i++) { + if (nums[i] * 2 > target) break; + + int l = i, r = nums.Length - 1; + while (l <= r) { + int mid = (l + r) / 2; + if (nums[i] + nums[mid] <= target) l = mid + 1; + else r = mid - 1; + } + + long count = ModPow(2, r - i, MOD); + res = (res + count) % MOD; + } + + return (int)res; + } + + long ModPow(long a, int b, int mod) { + long result = 1; + while (b > 0) { + if ((b & 1) == 1) result = (result * a) % mod; + a = (a * a) % mod; + b >>= 1; + } + return result; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -393,6 +455,38 @@ class Solution { } ``` +```csharp +public class Solution { + public int NumSubseq(int[] nums, int target) { + Array.Sort(nums); + const int MOD = 1000000007; + long res = 0; + int r = nums.Length - 1; + + for (int i = 0; i < nums.Length; i++) { + int left = nums[i]; + while (i <= r && left + nums[r] > target) r--; + if (i <= r) { + res += ModPow(2, r - i, MOD); + res %= MOD; + } + } + + return (int)res; + } + + long ModPow(long a, int b, int mod) { + long result = 1; + while (b > 0) { + if ((b & 1) == 1) result = (result * a) % mod; + a = (a * a) % mod; + b >>= 1; + } + return result; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -515,6 +609,35 @@ class Solution { } ``` +```csharp +public class Solution { + public int NumSubseq(int[] nums, int target) { + Array.Sort(nums); + const int MOD = 1000000007; + int n = nums.Length; + long res = 0; + int l = 0, r = n - 1; + + long[] power = new long[n]; + power[0] = 1; + for (int i = 1; i < n; i++) { + power[i] = (power[i - 1] * 2) % MOD; + } + + while (l <= r) { + if (nums[l] + nums[r] <= target) { + res = (res + power[r - l]) % MOD; + l++; + } else { + r--; + } + } + + return (int)res; + } +} +``` + ::tabs-end ### Time & Space Complexity diff --git a/articles/sort-an-array.md b/articles/sort-an-array.md index 4dbf28c54..ad599d8b6 100644 --- a/articles/sort-an-array.md +++ b/articles/sort-an-array.md @@ -274,7 +274,7 @@ public class Solution { class Solution: def sortArray(self, nums: List[int]) -> List[int]: def merge(arr, L, M, R): - left, right = arr[L : M + 1], arr[M + 1 : R + 1] + left, right = arr[L:M+1], arr[M+1:R+1] i, j, k = L, 0, 0 while j < len(left) and k < len(right): @@ -285,26 +285,26 @@ class Solution: arr[i] = right[k] k += 1 i += 1 + while j < len(left): - nums[i] = left[j] + arr[i] = left[j] j += 1 i += 1 + while k < len(right): - nums[i] = right[k] + arr[i] = right[k] k += 1 i += 1 def mergeSort(arr, l, r): - if l == r: + if l >= r: return - m = (l + r) // 2 mergeSort(arr, l, m) mergeSort(arr, m + 1, r) merge(arr, l, m, r) - return - mergeSort(nums, 0, len(nums)) + mergeSort(nums, 0, len(nums) - 1) return nums ``` diff --git a/articles/sort-array-by-increasing-frequency.md b/articles/sort-array-by-increasing-frequency.md index b763527da..c793ee58a 100644 --- a/articles/sort-array-by-increasing-frequency.md +++ b/articles/sort-array-by-increasing-frequency.md @@ -71,6 +71,20 @@ class Solution { } ``` +```csharp +public class Solution { + public int[] FrequencySort(int[] nums) { + var count = new Dictionary(); + foreach (int n in nums) { + if (!count.ContainsKey(n)) count[n] = 0; + count[n]++; + } + + return nums.OrderBy(n => count[n]).ThenByDescending(n => n).ToArray(); + } +} +``` + ::tabs-end ### Time & Space Complexity From ca0c5774eca28b216d492a91df413552bddc0975 Mon Sep 17 00:00:00 2001 From: Srihari Date: Sun, 9 Nov 2025 08:17:07 +0530 Subject: [PATCH 4/5] fix golang-code lru-cache --- articles/lru-cache.md | 65 +++++++++++++++++++++---------------------- 1 file changed, 31 insertions(+), 34 deletions(-) diff --git a/articles/lru-cache.md b/articles/lru-cache.md index d36605c15..feb243bd9 100644 --- a/articles/lru-cache.md +++ b/articles/lru-cache.md @@ -1047,49 +1047,46 @@ public class LRUCache { ```go type LRUCache struct { - capacity int - keys []int - values map[int]int + capacity int + cache map[int]*list.Element + list *list.List +} + +type entry struct { + key, value int } func Constructor(capacity int) LRUCache { - return LRUCache{ - capacity: capacity, - keys: make([]int, 0, capacity), - values: make(map[int]int), - } + return LRUCache{ + capacity: capacity, + cache: make(map[int]*list.Element), + list: list.New(), + } } func (this *LRUCache) Get(key int) int { - if val, exists := this.values[key]; exists { - for i := range this.keys { - if this.keys[i] == key { - this.keys = append(this.keys[:i], this.keys[i+1:]...) - break - } - } - this.keys = append(this.keys, key) - return val - } - return -1 + if node, exists := this.cache[key]; exists { + this.list.MoveToFront(node) + return node.Value.(entry).value + } + return -1 } func (this *LRUCache) Put(key int, value int) { - if _, exists := this.values[key]; exists { - for i := range this.keys { - if this.keys[i] == key { - this.keys = append(this.keys[:i], this.keys[i+1:]...) - break - } - } - } else { - if len(this.keys) >= this.capacity { - delete(this.values, this.keys[0]) - this.keys = this.keys[1:] - } - } - this.values[key] = value - this.keys = append(this.keys, key) + if node, exists := this.cache[key]; exists { + this.list.MoveToFront(node) + node.Value = entry{key, value} + return + } + + if this.list.Len() == this.capacity { + back := this.list.Back() + this.list.Remove(back) + delete(this.cache, back.Value.(entry).key) + } + + node := this.list.PushFront(entry{key, value}) + this.cache[key] = node } ``` From 4c2b12d42630620a466c3df1f29582b5fae0133e Mon Sep 17 00:00:00 2001 From: Srihari Date: Wed, 19 Nov 2025 18:09:44 +0530 Subject: [PATCH 5/5] fix java code --- articles/validate-parentheses.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/articles/validate-parentheses.md b/articles/validate-parentheses.md index b900e101b..8a15f7c53 100644 --- a/articles/validate-parentheses.md +++ b/articles/validate-parentheses.md @@ -154,7 +154,7 @@ class Solution: public class Solution { public boolean isValid(String s) { Stack stack = new Stack<>(); - java.util.Map closeToOpen = new java.util.HashMap<>(); + Map closeToOpen = new HashMap<>(); closeToOpen.put(')', '('); closeToOpen.put(']', '['); closeToOpen.put('}', '{');