Skip to content

Commit 8b5c20c

Browse files
committed
Updated Notes, Fix Links and pages
1 parent 738a2ab commit 8b5c20c

30 files changed

Lines changed: 4261 additions & 269 deletions

pages/Activity Selection Problem.md

Lines changed: 29 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,6 @@ displayTitle: Activity Selection Problem
3939
- **Stability**: Not applicable.
4040
- **Greedy Choice Property**: Selecting the activity with the earliest finish time never eliminates a globally optimal set.
4141
- **Optimal Substructure**: After selecting activity $k$, the remaining problem is the same — find max activities compatible with $k$ from the remaining set.
42-
4342
- # How It Works
4443
collapsed:: true
4544
- ## The Core Idea
@@ -59,7 +58,7 @@ displayTitle: Activity Selection Problem
5958
F --> D
6059
G --> D
6160
D --> H["✅ Selected set = maximum non-overlapping activities"]
62-
61+
6362
classDef default fill:#1f2937,stroke:#3b82f6,stroke-width:2px,color:#fff;
6463
```
6564
-
@@ -68,10 +67,10 @@ displayTitle: Activity Selection Problem
6867
- ```
6968
Activities (start, finish):
7069
A1=(1,4), A2=(3,5), A3=(0,6), A4=(5,7), A5=(3,9), A6=(5,9), A7=(6,10), A8=(8,11), A9=(8,12), A10=(2,14)
71-
70+
7271
After sorting by finish time:
7372
A1=(1,4), A2=(3,5), A3=(0,6), A4=(5,7), A5=(3,9), A6=(5,9), A7=(6,10), A8=(8,11), A9=(8,12), A10=(2,14)
74-
73+
7574
Step 1: Select A1 (finish=4). last_finish=4
7675
Step 2: A2 start=3 < 4 → skip
7776
Step 3: A3 start=0 < 4 → skip
@@ -82,10 +81,9 @@ displayTitle: Activity Selection Problem
8281
Step 8: A8 start=8 >= 7 → SELECT A8. last_finish=11
8382
Step 9: A9 start=8 < 11 → skip
8483
Step 10: A10 start=2 < 11 → skip
85-
84+
8685
Selected: {A1, A4, A8} → 3 activities ✅
8786
```
88-
8987
- # Complexity Analysis
9088
collapsed:: true
9189
- | Scenario | Time Complexity | Space Complexity | Notes |
@@ -98,12 +96,11 @@ displayTitle: Activity Selection Problem
9896
collapsed:: true
9997
- Sorting takes $O(N \log N)$. The greedy sweep is a single linear pass $O(N)$. Total = $O(N \log N)$.
10098
- If activities are already sorted by finish time, the entire algorithm runs in $O(N)$.
101-
10299
- # Implementation
103100
collapsed:: true
104101
- > [!note] Activity Selection — Greedy (Unweighted) + Weighted DP Variant
105102
> The standard greedy returns the count and selected activities. The weighted variant uses DP + binary search to maximize total profit.
106-
- Languages: [[Python]] · [[Cpp]] · [[Java Script]] · [[Java]]
103+
- Languages: [[Python]] · [[Cpp]] · [[Java Script]] · [[Java]]
107104
-
108105
- :::code-tabs
109106
@@ -118,17 +115,17 @@ displayTitle: Activity Selection Problem
118115
sorted_acts = sorted(activities, key=lambda x: x[1])
119116
selected = [sorted_acts[0]]
120117
last_finish = sorted_acts[0][1]
121-
118+
122119
for start, finish in sorted_acts[1:]:
123120
if start >= last_finish:
124121
selected.append((start, finish))
125122
last_finish = finish
126-
123+
127124
return selected
128-
125+
129126
# Weighted Job Scheduling — O(N log N) DP
130127
from bisect import bisect_right
131-
128+
132129
def weighted_job_scheduling(jobs: list[tuple[int, int, int]]) -> int:
133130
"""
134131
jobs: list of (start, finish, profit).
@@ -138,22 +135,22 @@ displayTitle: Activity Selection Problem
138135
n = len(jobs)
139136
finish_times = [j[1] for j in jobs]
140137
dp = [0] * (n + 1)
141-
138+
142139
for i in range(1, n + 1):
143140
start, finish, profit = jobs[i - 1]
144141
# Find last job that doesn't conflict (finish <= start of current)
145142
j = bisect_right(finish_times, start, 0, i - 1)
146143
# Either include job i (profit + dp[j]) or exclude it (dp[i-1])
147144
dp[i] = max(dp[i - 1], profit + dp[j])
148-
145+
149146
return dp[n]
150-
147+
151148
# Examples
152149
activities = [(1,4),(3,5),(0,6),(5,7),(3,9),(5,9),(6,10),(8,11),(8,12),(2,14)]
153150
selected = activity_selection(activities)
154151
print(f"Selected: {selected}") # [(1,4), (5,7), (8,11)]
155152
print(f"Count: {len(selected)}") # 3
156-
153+
157154
jobs = [(1, 4, 20), (3, 5, 30), (0, 6, 15), (5, 7, 40)]
158155
print(f"Max Profit: {weighted_job_scheduling(jobs)}") # 60 (job1 + job4)
159156
```
@@ -162,16 +159,16 @@ displayTitle: Activity Selection Problem
162159
#include <iostream>
163160
#include <vector>
164161
#include <algorithm>
165-
162+
166163
using Activity = std::pair<int, int>; // (start, finish)
167-
164+
168165
std::vector<Activity> activitySelection(std::vector<Activity> activities) {
169166
std::sort(activities.begin(), activities.end(),
170167
[](const Activity& a, const Activity& b) { return a.second < b.second; });
171-
168+
172169
std::vector<Activity> selected = {activities[0]};
173170
int lastFinish = activities[0].second;
174-
171+
175172
for (size_t i = 1; i < activities.size(); ++i) {
176173
if (activities[i].first >= lastFinish) {
177174
selected.push_back(activities[i]);
@@ -180,7 +177,7 @@ displayTitle: Activity Selection Problem
180177
}
181178
return selected;
182179
}
183-
180+
184181
int main() {
185182
std::vector<Activity> acts = {{1,4},{3,5},{0,6},{5,7},{3,9},{5,9},{6,10},{8,11}};
186183
auto result = activitySelection(acts);
@@ -197,7 +194,7 @@ displayTitle: Activity Selection Problem
197194
activities.sort((a, b) => a.finish - b.finish);
198195
const selected = [activities[0]];
199196
let lastFinish = activities[0].finish;
200-
197+
201198
for (let i = 1; i < activities.length; i++) {
202199
if (activities[i].start >= lastFinish) {
203200
selected.push(activities[i]);
@@ -206,7 +203,7 @@ displayTitle: Activity Selection Problem
206203
}
207204
return selected;
208205
}
209-
206+
210207
const acts = [
211208
{start:1,finish:4},{start:3,finish:5},{start:0,finish:6},
212209
{start:5,finish:7},{start:8,finish:11}
@@ -218,15 +215,15 @@ displayTitle: Activity Selection Problem
218215
219216
```java
220217
import java.util.*;
221-
218+
222219
public class ActivitySelection {
223220
public static List<int[]> select(int[][] activities) {
224221
// activities[i] = {start, finish}
225222
Arrays.sort(activities, (a, b) -> a[1] - b[1]);
226223
List<int[]> selected = new ArrayList<>();
227224
selected.add(activities[0]);
228225
int lastFinish = activities[0][1];
229-
226+
230227
for (int i = 1; i < activities.length; i++) {
231228
if (activities[i][0] >= lastFinish) {
232229
selected.add(activities[i]);
@@ -235,7 +232,7 @@ displayTitle: Activity Selection Problem
235232
}
236233
return selected;
237234
}
238-
235+
239236
public static void main(String[] args) {
240237
int[][] acts = {{1,4},{3,5},{0,6},{5,7},{3,9},{8,11}};
241238
List<int[]> result = select(acts);
@@ -247,7 +244,6 @@ displayTitle: Activity Selection Problem
247244
```
248245
249246
:::
250-
251247
- # Alternative Variant (Interval Coloring — Minimum Machines)
252248
collapsed:: true
253249
- > [!tip] Interval Coloring — Find Minimum Number of Machines Needed
@@ -257,7 +253,7 @@ displayTitle: Activity Selection Problem
257253
258254
```python
259255
import heapq
260-
256+
261257
def min_machines(activities: list[tuple[int, int]]) -> int:
262258
"""
263259
Minimum machines to run all activities without conflicts.
@@ -267,22 +263,21 @@ displayTitle: Activity Selection Problem
267263
return 0
268264
activities.sort(key=lambda x: x[0]) # sort by start time
269265
heap = [] # min-heap of finish times (machines in use)
270-
266+
271267
for start, finish in activities:
272268
if heap and heap[0] <= start:
273269
heapq.heapreplace(heap, finish) # reuse freed machine
274270
else:
275271
heapq.heappush(heap, finish) # add new machine
276-
272+
277273
return len(heap)
278-
274+
279275
# Example
280276
activities = [(0,6),(1,4),(3,5),(5,7),(3,9),(5,9),(6,10),(8,11)]
281277
print(f"Min machines: {min_machines(activities)}") # 3
282278
```
283279
284280
:::
285-
286281
- # When to Use Activity Selection
287282
collapsed:: true
288283
- ```mermaid
@@ -294,7 +289,7 @@ displayTitle: Activity Selection Problem
294289
S1 -- No --> S2{"Do activities have\ndifferent profits/weights?"}
295290
S2 -- Yes --> R3["✅ Weighted Job Scheduling\nDP + Binary Search, O(N log N)"]
296291
S2 -- No --> R4["✅ Greedy: earliest finish first"]
297-
292+
298293
classDef default fill:#1f2937,stroke:#3b82f6,stroke-width:2px,color:#fff;
299294
```
300295
-
@@ -307,7 +302,6 @@ displayTitle: Activity Selection Problem
307302
- ## ❌ Avoid Simple Greedy When
308303
- Activities have **different profits/weights** — switch to Weighted Job Scheduling DP.
309304
- The constraint is not just non-overlap but involves **dependencies** between activities.
310-
311305
- # Key Takeaways
312306
collapsed:: true
313307
- **Earliest Finish First** — The greedy choice is always picking the activity with the earliest finish time, maximizing remaining time for future activities.
@@ -316,11 +310,10 @@ displayTitle: Activity Selection Problem
316310
- **Weighted Variant Needs DP** — When activities have different profits, greedy fails. Use DP + binary search ([[Dynamic Programming Concepts]]) for the weighted version.
317311
- **Interval Coloring Dual** — The minimum number of machines = the maximum overlap depth at any point (use min-heap of finish times).
318312
- **LeetCode Applications** — "Non-overlapping Intervals" (#435), "Meeting Rooms II" (#253), "Minimum Number of Arrows to Burst Balloons" (#452).
319-
320313
- # More Learn
321314
collapsed:: true
322315
- ## GitHub & Webs
323316
- [GeeksforGeeks → Activity Selection Problem](https://www.geeksforgeeks.org/activity-selection-problem-greedy-algo-1/)
324317
- [CP Algorithms → Scheduling](https://cp-algorithms.com/greedy/job_scheduling.html)
325318
- [LeetCode → Non-overlapping Intervals (Problem 435)](https://leetcode.com/problems/non-overlapping-intervals/)
326-
- [LeetCode → Meeting Rooms II (Problem 253)](https://leetcode.com/problems/meeting-rooms-ii/)
319+
- [LeetCode → Meeting Rooms II (Problem 253)](https://leetcode.com/problems/meeting-rooms-ii/)

pages/Boyer More Majority Vote.md

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,9 @@ displayTitle: Boyer More Majority Vote
1313
- ## Real-World Analogy
1414
collapsed:: true
1515
- Imagine an election 🗳️ where voters shout their candidate. The rule is:
16-
- Every time two different candidates "clash", one vote from each is cancelled.
17-
- At the end, whoever is left standing is the **majority candidate**.
18-
- This works only if a true majority (> N/2 votes) exists — otherwise the survivor needs a second verification pass.
16+
- Every time two different candidates "clash", one vote from each is cancelled.
17+
- At the end, whoever is left standing is the **majority candidate**.
18+
- This works only if a true majority (> N/2 votes) exists — otherwise the survivor needs a second verification pass.
1919
-
2020
- ## The Algorithm (2 passes)
2121
collapsed:: true
@@ -55,7 +55,6 @@ displayTitle: Boyer More Majority Vote
5555
|---|---|
5656
| **Time** | O(N) — two passes at most |
5757
| **Space** | O(1) — two variables: candidate + count |
58-
5958
- # Implementation
6059
collapsed:: true
6160
- > [!note] Standard majority (>N/2) + extended variant for elements appearing >N/3 times (returns up to 2 candidates).
@@ -277,15 +276,13 @@ displayTitle: Boyer More Majority Vote
277276
```
278277
279278
:::
280-
281279
- # Key Takeaways
282280
collapsed:: true
283281
- Two passes: **Pass 1** finds the candidate (cancel pairs of different elements). **Pass 2** verifies it appears > N/2 times.
284282
- **O(1) space** — only 2 variables (candidate + count) vs O(N) for a hash map.
285283
- Pass 2 is mandatory — without it, `[1, 2, 3]` would wrongly return 3.
286284
- **N/3 variant** maintains 2 candidates and 2 counts for elements appearing > N/3 times (at most 2 such elements can exist).
287285
- Related: [[Quick Select Algorithm]], [[Kadane's Algorithm]]
288-
289286
- # More Learn
290287
collapsed:: true
291288
- ## LeetCode Problems

pages/Constructor.md

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,6 @@ displayTitle: Constructor
3030
```
3131
-
3232
- > [!important] In Python, `__new__()` allocates memory and `__init__()` initializes it. You almost always only define `__init__`. In C++, the constructor does both.
33-
3433
- # Types of Constructors
3534
collapsed:: true
3635
- | Type | Description | Example |
@@ -49,10 +48,10 @@ displayTitle: Constructor
4948
CT --> COP["Copy\n(from existing object)"]
5049
CT --> DEL["Delegating / Chaining\n(calls another constructor)"]
5150
```
52-
5351
- # Constructor Chaining
5452
collapsed:: true
5553
- One constructor can call another constructor of the same class to avoid code duplication:
54+
- :::code-tabs
5655
- ```python
5756
# Python — via __init__ default arguments
5857
class Connection:
@@ -87,7 +86,7 @@ displayTitle: Constructor
8786
}
8887
}
8988
```
90-
89+
:::
9190
- # Implementation
9291
collapsed:: true
9392
- > [!note] A `DatabaseConnection` class demonstrating all constructor types, chaining, validation, and C++ initializer list.
@@ -368,15 +367,13 @@ displayTitle: Constructor
368367
```
369368
370369
:::
371-
372370
- # Key Takeaways
373371
collapsed:: true
374372
- A constructor **runs automatically** at object creation — you never call it explicitly.
375373
- Always **validate inputs** in the constructor to guarantee a valid initial state.
376374
- Use **constructor chaining** (`this(...)` in Java, `super(...)` in child classes, default args in Python) to avoid duplication.
377375
- **C++ initializer lists** (`: field_(value)`) initialize members before the constructor body runs — more efficient than assignment inside the body.
378376
- **Factory class methods** (`@classmethod` in Python, `static` in Java/C#) are alternative constructors with semantic names (`from_url()`, `local()`).
379-
380377
- # More Learn
381378
collapsed:: true
382379
- ## GitHub & Webs

pages/DSA Algo & System Design.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ keywords: "DSA, data structures, algorithms, system design, technical interview,
171171
- 10) [[Topological Sort Algorithm]] - used to order the vertices of a **directed acyclic graph**
172172
- 11) [[Flood Fill Algorithm]] - used to determine the area connected to a given node
173173
- 12) [[Lee Algorithm]] - BFS based algorithm used to find the shortest path
174-
- 13) [[Eukerian Path (Hierholzer's Algorithm)]] - path that visits every edge exactly once.
174+
- 13) [[Eukerian Path Hierholzers Algorithm]] - path that visits every edge exactly once.
175175
-
176176
- ## Arrays & Two Pointers:
177177
collapsed:: true
@@ -201,7 +201,7 @@ keywords: "DSA, data structures, algorithms, system design, technical interview,
201201
- **Time:** O((N + Q) × √N) · **Space:** O(√N) for block bookkeeping
202202
- **Key Insight:** Sort queries by (block of L, then R for even blocks / R descending for odd blocks). This minimizes total pointer movement across all queries to O((N + Q)√N).
203203
- **Use cases:** Range sum/product queries, count distinct elements in range, offline interval problems.
204-
- 6) [[Distinct elements in subarray using Mo's Algorithm]]
204+
- 6) [[Distinct elements in subarray using Mos Algorithm]]
205205
- **Purpose:** Count **distinct elements** across many arbitrary subarrays efficiently using MO's ordering.
206206
- **Time:** O((N + Q) × √N) · **Space:** O(N) for frequency map
207207
- **Key Insight:** Extend/shrink the window by one element at a time, updating a frequency table. Increment the distinct count only when a new frequency goes from 0 → 1, decrement when it goes 1 → 0.

pages/Distinct elements in subarray using Mo's Algorithm.md renamed to pages/Distinct elements in subarray using Mos Algorithm.md

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ seoTitle: Count Distinct Elements in Subarray – MO's Algorithm Variant | In-De
33
description: "Complete guide to counting distinct elements in subarrays using MO's Algorithm. Covers frequency map add/remove, offline query processing, O((N+Q)√N) complexity, and implementations in Python, C++, Java, JavaScript, and C#."
44
keywords: "distinct elements subarray, Mo's algorithm, count distinct, offline queries, frequency map, square root decomposition, range query, VR-Rathod, Code-Note, code note vr"
55
displayTitle: Distinct elements in subarray using Mo's Algorithm
6+
title: Distinct elements in subarray using Mos Algorithm
67
---
78

89
> [!info] What is this problem?
@@ -54,7 +55,6 @@ displayTitle: Distinct elements in subarray using Mo's Algorithm
5455
| **Time** | O((N + Q) × √N) |
5556
| **Space** | O(N) for frequency map + O(Q) for answers |
5657
| **Constraint** | Offline — all queries known upfront |
57-
5858
- # Implementation
5959
collapsed:: true
6060
- > [!note] Full MO's-based distinct count: frequency map, Mo ordering, pointer management, and result retrieval.
@@ -107,7 +107,7 @@ displayTitle: Distinct elements in subarray using Mo's Algorithm
107107
# Expand right
108108
while right < q.r: right += 1; add(right)
109109
# Expand left
110-
while left > q.l: left -= 1; add(left)
110+
while left > q.l: left -= 1; add(left)
111111
# Shrink right
112112
while right > q.r: remove(right); right -= 1
113113
# Shrink left
@@ -312,17 +312,15 @@ displayTitle: Distinct elements in subarray using Mo's Algorithm
312312
```
313313
314314
:::
315-
316315
- # Key Takeaways
317316
collapsed:: true
318317
- The core add/remove pattern: `freq[x]++; if freq[x]==1: distinct++` / `freq[x]--; if freq[x]==0: distinct--`.
319318
- This O(1) add/remove makes MO's work for this problem — total cost = number of pointer moves = O((N+Q)√N).
320319
- **Verification trick:** After computing, cross-check `len(set(arr[l:r+1]))` to verify answers.
321320
- This is a direct application of [[MOs Algorithm (Query square root decomposition)]] specialised to the distinct-count aggregate.
322321
- Related: [[MOs Algorithm (Query square root decomposition)]], [[Prefix Sum Array]], [[Sliding Window Technique]]
323-
324322
- # More Learn
325323
collapsed:: true
326324
- ## Resources
327325
- [GeeksForGeeks — MO's Algorithm for Distinct Count](https://www.geeksforgeeks.org/mos-algorithm-query-square-root-decomposition-set-1-introduction/)
328-
- [CP-Algorithms — MO's Algorithm](https://cp-algorithms.com/data_structures/sqrt_decomposition.html)
326+
- [CP-Algorithms — MO's Algorithm](https://cp-algorithms.com/data_structures/sqrt_decomposition.html)

0 commit comments

Comments
 (0)