-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path1851_minimum_interval_to_include_each_query.html
More file actions
535 lines (466 loc) · 19.7 KB
/
Copy path1851_minimum_interval_to_include_each_query.html
File metadata and controls
535 lines (466 loc) · 19.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>1851 - Minimum Interval to Include Each Query</title>
<link rel="stylesheet" href="styles.css">
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<div class="container">
<div class="problem-info">
<h1><span class="problem-number">#1851</span> Minimum Interval to Include Each Query</h1>
<p>
For each query, find the smallest interval containing that query point.
Uses sorting + min-heap: process queries in order, maintain valid intervals in heap.
</p>
<div class="problem-meta">
<span class="meta-tag">📏 Intervals</span>
<span class="meta-tag">⏱️ O(n log n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/1851_minimum_interval_to_include_each_query/1851_minimum_interval_to_include_each_query.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>Interval problems deal with <strong>ranges and overlaps</strong>:</p>
<ul>
<li><strong>Sort:</strong> Usually sort by start time</li>
<li><strong>Merge:</strong> Combine overlapping intervals</li>
<li><strong>Compare:</strong> Check if intervals overlap</li>
<li><strong>Track:</strong> Maintain current merged interval</li>
</ul>
</div>
<section class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<button id="autoRunBtn" class="btn">▶ Auto Run</button>
<button id="stepBtn" class="btn btn-success">Step</button>
<button id="resetBtn" class="btn btn-danger">Reset</button>
</div>
<div class="status" id="status">Click Auto Run to find minimum intervals</div>
<svg id="visualization"></svg>
</section>
<section class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>import heapq
from typing import List
"""
LeetCode Minimum Interval To Include Each Query
Problem from LeetCode: https://leetcode.com/problems/minimum-interval-to-include-each-query/
You are given a 2D integer array intervals, where intervals[i] = [lefti, righti]
describes the ith interval starting at lefti and ending at righti (inclusive).
The size of an interval is defined as the number of integers it contains, or more
formally righti - lefti + 1.
You are also given an integer array queries. The answer to the jth query is the
size of the smallest interval i such that lefti <= queries[j] <= righti. If no
such interval exists, the answer is -1.
Return an array containing the answers to the queries.
Example 1:
Input: intervals = [[1,4],[2,4],[3,6],[4,4]], queries = [2,3,4,5]
Output: [3,3,1,4]
Explanation: The queries are processed as follows:
- Query = 2: The interval [2,4] is the smallest interval containing 2. The answer is 4 - 2 + 1 = 3.
- Query = 3: The interval [2,4] is the smallest interval containing 3. The answer is 4 - 2 + 1 = 3.
- Query = 4: The interval [4,4] is the smallest interval containing 4. The answer is 4 - 4 + 1 = 1.
- Query = 5: The interval [3,6] is the smallest interval containing 5. The answer is 6 - 3 + 1 = 4.
Example 2:
Input: intervals = [[2,3],[2,5],[1,8],[20,25]], queries = [2,19,5,22]
Output: [2,-1,4,6]
Explanation: The queries are processed as follows:
- Query = 2: The interval [2,3] is the smallest interval containing 2. The answer is 3 - 2 + 1 = 2.
- Query = 19: None of the intervals contain 19. The answer is -1.
- Query = 5: The interval [2,5] is the smallest interval containing 5. The answer is 5 - 2 + 1 = 4.
- Query = 22: The interval [20,25] is the smallest interval containing 22. The answer is 25 - 20 + 1 = 6.
Constraints:
1 <= intervals.length <= 10^5
1 <= queries.length <= 10^5
intervals[i].length == 2
1 <= lefti <= righti <= 10^7
1 <= queries[j] <= 10^7
"""
class Solution:
def min_interval(self, intervals: List[List[int]], queries: List[int]) -> List[int]:
n = len(queries)
result = [-1] * n
query_indices = [(queries[i], i) for i in range(n)]
query_indices.sort()
intervals.sort()
min_heap = []
interval_idx = 0
for query, original_idx in query_indices:
while interval_idx < len(intervals) and intervals[interval_idx][0
] <= query:
start, end = intervals[interval_idx]
if end >= query:
heapq.heappush(min_heap, (end - start + 1, end))
interval_idx += 1
while min_heap and min_heap[0][1] < query:
heapq.heappop(min_heap)
if min_heap:
result[original_idx] = min_heap[0][0]
return result
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
intervals1 = [[1,4],[2,4],[3,6],[4,4]]
queries1 = [2,3,4,5]
result1 = solution.min_interval(intervals1, queries1)
print(f"Example 1: {result1}") # Output: [3,3,1,4]
# Example 2
intervals2 = [[2,3],[2,5],[1,8],[20,25]]
queries2 = [2,19,5,22]
result2 = solution.min_interval(intervals2, queries2)
print(f"Example 2: {result2}") # Output: [2,-1,4,6]
</pre>
</div>
</section>
</div>
<script>
const width = 900;
const height = 600;
const svg = d3.select("#visualization")
.attr("width", width)
.attr("height", height);
// Example data
const intervals = [[1, 4], [2, 4], [3, 6], [4, 4]];
const queries = [2, 3, 4, 5];
const numLineStart = 0;
const numLineEnd = 8;
let sortedIntervals = [];
let sortedQueries = [];
let currentQueryIdx = 0;
let intervalIdx = 0;
let minHeap = [];
let result = {};
let activeIntervals = [];
let animationTimer = null;
function reset() {
sortedIntervals = [...intervals].sort((a, b) => a[0] - b[0]);
sortedQueries = queries.map((q, i) => [q, i]).sort((a, b) => a[0] - b[0]);
currentQueryIdx = 0;
intervalIdx = 0;
minHeap = [];
result = {};
activeIntervals = [];
if (animationTimer) clearInterval(animationTimer);
document.getElementById("status").textContent = "Click Auto Run to find minimum intervals";
render();
}
function heapPush(heap, item) {
heap.push(item);
let i = heap.length - 1;
while (i > 0) {
const parent = Math.floor((i - 1) / 2);
if (heap[parent][0] <= heap[i][0]) break;
[heap[parent], heap[i]] = [heap[i], heap[parent]];
i = parent;
}
}
function heapPop(heap) {
if (heap.length === 0) return null;
const result = heap[0];
const last = heap.pop();
if (heap.length > 0) {
heap[0] = last;
let i = 0;
while (true) {
const left = 2 * i + 1;
const right = 2 * i + 2;
let smallest = i;
if (left < heap.length && heap[left][0] < heap[smallest][0]) smallest = left;
if (right < heap.length && heap[right][0] < heap[smallest][0]) smallest = right;
if (smallest === i) break;
[heap[i], heap[smallest]] = [heap[smallest], heap[i]];
i = smallest;
}
}
return result;
}
function render() {
svg.selectAll("*").remove();
// Draw number line
drawNumberLine();
// Draw intervals
drawIntervals();
// Draw queries
drawQueries();
// Draw min-heap
drawMinHeap();
// Draw results
drawResults();
}
function drawNumberLine() {
const y = 120;
const leftX = 80;
const rightX = 700;
const scale = (rightX - leftX) / (numLineEnd - numLineStart);
// Line
svg.append("line")
.attr("x1", leftX)
.attr("y1", y)
.attr("x2", rightX)
.attr("y2", y)
.attr("stroke", "#94a3b8")
.attr("stroke-width", 2);
// Ticks
for (let i = numLineStart; i <= numLineEnd; i++) {
const x = leftX + (i - numLineStart) * scale;
svg.append("line")
.attr("x1", x)
.attr("y1", y - 5)
.attr("x2", x)
.attr("y2", y + 5)
.attr("stroke", "#64748b")
.attr("stroke-width", 1);
svg.append("text")
.attr("x", x)
.attr("y", y + 20)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text(i);
}
}
function drawIntervals() {
const baseY = 60;
const leftX = 80;
const rightX = 700;
const scale = (rightX - leftX) / (numLineEnd - numLineStart);
svg.append("text")
.attr("x", 50)
.attr("y", 30)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Intervals (sorted by start):");
sortedIntervals.forEach((interval, idx) => {
const [start, end] = interval;
const x1 = leftX + (start - numLineStart) * scale;
const x2 = leftX + (end - numLineStart) * scale;
const y = baseY - idx * 15;
const isProcessed = idx < intervalIdx;
const isActive = activeIntervals.some(a => a[0] === start && a[1] === end);
svg.append("line")
.attr("x1", x1)
.attr("y1", y)
.attr("x2", x2)
.attr("y2", y)
.attr("stroke", () => {
if (isActive) return "#10b981";
if (isProcessed) return "#d1d5db";
return "#3b82f6";
})
.attr("stroke-width", isActive ? 5 : 3)
.attr("stroke-linecap", "round");
// Size label
const size = end - start + 1;
svg.append("text")
.attr("x", x2 + 10)
.attr("y", y + 4)
.attr("font-size", "10px")
.attr("fill", isActive ? "#10b981" : "#64748b")
.text(`size=${size}`);
});
}
function drawQueries() {
const y = 120;
const leftX = 80;
const rightX = 700;
const scale = (rightX - leftX) / (numLineEnd - numLineStart);
queries.forEach((query, idx) => {
const x = leftX + (query - numLineStart) * scale;
const isCurrentSorted = currentQueryIdx < sortedQueries.length &&
sortedQueries[currentQueryIdx][0] === query &&
sortedQueries[currentQueryIdx][1] === idx;
const isProcessed = result[idx] !== undefined;
svg.append("circle")
.attr("cx", x)
.attr("cy", y)
.attr("r", 8)
.attr("fill", () => {
if (isCurrentSorted) return "#fef3c7";
if (isProcessed) return "#d1fae5";
return "#f8fafc";
})
.attr("stroke", () => {
if (isCurrentSorted) return "#f59e0b";
if (isProcessed) return "#10b981";
return "#ec4899";
})
.attr("stroke-width", 2);
svg.append("text")
.attr("x", x)
.attr("y", y + 4)
.attr("text-anchor", "middle")
.attr("font-size", "10px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(query);
// Query index
svg.append("text")
.attr("x", x)
.attr("y", y + 38)
.attr("text-anchor", "middle")
.attr("font-size", "9px")
.attr("fill", "#64748b")
.text(`Q[${idx}]`);
});
svg.append("text")
.attr("x", 50)
.attr("y", y + 35)
.attr("font-size", "11px")
.attr("fill", "#64748b")
.text("Queries:");
}
function drawMinHeap() {
const x = 50;
const y = 200;
svg.append("text")
.attr("x", x)
.attr("y", y)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Min-Heap (by interval size):");
if (minHeap.length === 0) {
svg.append("text")
.attr("x", x)
.attr("y", y + 30)
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text("(empty)");
} else {
const sortedHeap = [...minHeap].sort((a, b) => a[0] - b[0]);
sortedHeap.forEach((item, idx) => {
const px = x + idx * 100;
svg.append("rect")
.attr("x", px)
.attr("y", y + 15)
.attr("width", 90)
.attr("height", 35)
.attr("rx", 4)
.attr("fill", idx === 0 ? "#d1fae5" : "#f8fafc")
.attr("stroke", idx === 0 ? "#10b981" : "#94a3b8");
svg.append("text")
.attr("x", px + 45)
.attr("y", y + 38)
.attr("text-anchor", "middle")
.attr("font-size", "11px")
.attr("font-weight", idx === 0 ? "bold" : "normal")
.attr("fill", "#1e293b")
.text(`size=${item[0]}, end=${item[1]}`);
});
}
}
function drawResults() {
const x = 50;
const y = 300;
svg.append("text")
.attr("x", x)
.attr("y", y)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Results:");
queries.forEach((query, idx) => {
const px = x + idx * 100;
svg.append("rect")
.attr("x", px)
.attr("y", y + 15)
.attr("width", 90)
.attr("height", 40)
.attr("rx", 4)
.attr("fill", result[idx] !== undefined ? "#d1fae5" : "#f8fafc")
.attr("stroke", result[idx] !== undefined ? "#10b981" : "#94a3b8");
svg.append("text")
.attr("x", px + 45)
.attr("y", y + 33)
.attr("text-anchor", "middle")
.attr("font-size", "10px")
.attr("fill", "#64748b")
.text(`Q[${idx}]=${query}`);
svg.append("text")
.attr("x", px + 45)
.attr("y", y + 48)
.attr("text-anchor", "middle")
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", result[idx] !== undefined ? "#10b981" : "#94a3b8")
.text(result[idx] !== undefined ? result[idx] : "?");
});
// Final result array
if (Object.keys(result).length === queries.length) {
const finalResult = queries.map((_, i) => result[i]);
svg.append("text")
.attr("x", x)
.attr("y", y + 85)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#10b981")
.text(`✓ Final: [${finalResult.join(", ")}]`);
}
}
function step() {
if (currentQueryIdx >= sortedQueries.length) {
document.getElementById("status").textContent =
`✓ Complete! Results: [${queries.map((_, i) => result[i]).join(", ")}]`;
return;
}
const [query, originalIdx] = sortedQueries[currentQueryIdx];
// Add intervals that start <= query
while (intervalIdx < sortedIntervals.length && sortedIntervals[intervalIdx][0] <= query) {
const [start, end] = sortedIntervals[intervalIdx];
if (end >= query) {
heapPush(minHeap, [end - start + 1, end, start]);
activeIntervals.push([start, end]);
}
intervalIdx++;
}
// Remove expired intervals
while (minHeap.length > 0 && minHeap[0][1] < query) {
const removed = heapPop(minHeap);
activeIntervals = activeIntervals.filter(a => !(a[1] === removed[1] && a[0] === removed[2]));
}
// Record result
if (minHeap.length > 0) {
result[originalIdx] = minHeap[0][0];
document.getElementById("status").textContent =
`Query ${query} (idx ${originalIdx}): Smallest interval has size ${minHeap[0][0]}`;
} else {
result[originalIdx] = -1;
document.getElementById("status").textContent =
`Query ${query} (idx ${originalIdx}): No interval contains this point → -1`;
}
currentQueryIdx++;
render();
}
function autoRun() {
if (animationTimer) {
clearInterval(animationTimer);
animationTimer = null;
document.getElementById("autoRunBtn").textContent = "▶ Auto Run";
return;
}
document.getElementById("autoRunBtn").textContent = "⏸ Pause";
animationTimer = setInterval(() => {
if (currentQueryIdx >= sortedQueries.length) {
clearInterval(animationTimer);
animationTimer = null;
document.getElementById("autoRunBtn").textContent = "▶ Auto Run";
return;
}
step();
}, 1000);
}
document.getElementById("autoRunBtn").addEventListener("click", autoRun);
document.getElementById("stepBtn").addEventListener("click", step);
document.getElementById("resetBtn").addEventListener("click", reset);
reset();
</script>
</body>
</html>