-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0041_first_missing_positive.html
More file actions
441 lines (377 loc) · 16.3 KB
/
0041_first_missing_positive.html
File metadata and controls
441 lines (377 loc) · 16.3 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>First Missing Positive - LeetCode 41</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">#41</span> First Missing Positive</h1>
<p>Find the smallest missing positive integer in O(n) time and O(1) space.</p>
<div class="problem-meta">
<span class="meta-tag">Array</span>
<span class="meta-tag">Hash Table</span>
<span class="meta-tag">Hard</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0041_first_missing_positive/0041_first_missing_positive.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>This algorithm solves the problem <strong>step by step</strong>:</p>
<ul>
<li><strong>Understand:</strong> Parse the input data</li>
<li><strong>Process:</strong> Apply the core logic</li>
<li><strong>Optimize:</strong> Use efficient data structures</li>
<li><strong>Return:</strong> Output the computed result</li>
</ul>
</div>
<div class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<button id="stepBtn">Step</button>
<button id="autoBtn">Auto Run</button>
<button id="resetBtn">Reset</button>
</div>
<svg id="mainSvg" width="800" height="380"></svg>
<div class="status-message" id="status">Click "Step" to find first missing positive</div>
</div>
<div class="code-section">
<h3>Python Solution (Cyclic Sort)</h3>
<div class="code-block">
<pre>from typing import List
"""
LeetCode First Missing Positive
Problem from LeetCode: https://leetcode.com/problems/first-missing-positive/
Description:
Given an unsorted integer array nums, return the smallest missing positive integer.
You must implement an algorithm that runs in O(n) time and uses constant extra space.
Example 1:
Input: nums = [1,2,0]
Output: 3
Example 2:
Input: nums = [3,4,-1,1]
Output: 2
Example 3:
Input: nums = [7,8,9,11,12]
Output: 1
"""
class Solution:
def first_missing_positive(self, nums: List[int]) -> int:
"""
Find the smallest missing positive integer in an unsorted array.
Uses O(n) time and O(1) extra space by modifying the array in-place.
Args:
nums: Unsorted array of integers
Returns:
int: Smallest missing positive integer
"""
n = len(nums)
# Step 1: Ensure 1 is present in the array
contains_one = False
for num in nums:
if num == 1:
contains_one = True
break
if not contains_one:
return 1
# Step 2: Replace non-positive numbers and numbers greater than n with 1
# This simplifies the problem to finding the first missing in range [1, n+1]
for i in range(n):
if nums[i] <= 0 or nums[i] > n:
nums[i] = 1
# Step 3: Use the array itself as a hash table
# Mark presence of values by negating the value at corresponding index
for i in range(n):
num = abs(nums[i])
# If num is in range [1, n]
if num <= n:
# Make nums[num-1] negative to mark num as present
# Use abs() in case it's already negative
nums[num - 1] = -abs(nums[num - 1])
# Step 4: Find the first positive value in the array
# Its index + 1 will be the first missing positive
for i in range(n):
if nums[i] > 0:
return i + 1
# If all values in range [1, n] are present, return n+1
return n + 1
def first_missing_positive_cyclic_sort(self, nums: List[int]) -> int:
"""
Find the smallest missing positive integer using cyclic sort.
Places each number in its correct position, then finds the first mismatch.
Args:
nums: Unsorted array of integers
Returns:
int: Smallest missing positive integer
"""
n = len(nums)
# Place each number in its correct position
# nums[i] should be at position nums[i] - 1 if 1 <= nums[i] <= n
i = 0
while i < n:
correct_pos = nums[i] - 1
# If the number is positive, in range, and not already in correct position
if 0 < nums[i] <= n and nums[i] != nums[correct_pos]:
# Swap to place it in the correct position
nums[i], nums[correct_pos] = nums[correct_pos], nums[i]
else:
i += 1
# Find the first position where the number doesn't match its index + 1
for i in range(n):
if nums[i] != i + 1:
return i + 1
# If all positions are filled correctly, the answer is n+1
return n + 1
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
nums1 = [1, 2, 0]
result1 = solution.first_missing_positive(nums1.copy()) # Use copy to preserve original for comparison
print(f"Example 1: nums={nums1}, result={result1}") # Expected output: 3
# Example 2
nums2 = [3, 4, -1, 1]
result2 = solution.first_missing_positive(nums2.copy())
print(f"Example 2: nums={nums2}, result={result2}") # Expected output: 2
# Example 3
nums3 = [7, 8, 9, 11, 12]
result3 = solution.first_missing_positive(nums3.copy())
print(f"Example 3: nums={nums3}, result={result3}") # Expected output: 1
# Compare with cyclic sort approach
print("\nUsing cyclic sort approach:")
print(f"Example 1: {solution.first_missing_positive_cyclic_sort(nums1.copy())}")
print(f"Example 2: {solution.first_missing_positive_cyclic_sort(nums2.copy())}")
print(f"Example 3: {solution.first_missing_positive_cyclic_sort(nums3.copy())}")
</pre>
</div>
</div>
</div>
<script>
const originalNums = [3, 4, -1, 1];
let nums = [...originalNums];
let phase = 'cyclic_sort';
let i = 0;
let result = null;
const width = 800, height = 380;
const svg = d3.select("#mainSvg");
let autoTimer = null;
let autoRunning = false;
function draw() {
svg.selectAll("*").remove();
const cellWidth = 80, startX = 150, startY = 80;
const n = nums.length;
// Title
svg.append("text")
.attr("x", width / 2).attr("y", 30)
.attr("text-anchor", "middle")
.attr("font-weight", "bold")
.text(`Finding First Missing Positive in [${originalNums.join(", ")}]`);
// Expected positions header
svg.append("text")
.attr("x", 50).attr("y", startY + 20)
.attr("font-size", "12px")
.attr("fill", "#666")
.text("Expected:");
for (let idx = 0; idx < n; idx++) {
const x = startX + idx * cellWidth;
svg.append("text")
.attr("x", x + (cellWidth - 5) / 2)
.attr("y", startY + 20)
.attr("text-anchor", "middle")
.attr("font-size", "14px")
.attr("fill", "#999")
.text(idx + 1);
}
// Draw array
svg.append("text")
.attr("x", 50).attr("y", startY + 65)
.attr("font-size", "12px")
.attr("fill", "#666")
.text("Array:");
nums.forEach((num, idx) => {
const x = startX + idx * cellWidth;
let fill = "#e3f2fd", stroke = "#1976d2";
// Check if in correct position
const isCorrect = num === idx + 1;
if (phase === 'cyclic_sort' && idx === i) {
fill = "#fef3c7"; stroke = "#f59e0b";
} else if (phase === 'cyclic_sort' && num > 0 && num <= n && idx === num - 1) {
fill = "#e8f5e9"; stroke = "#4caf50";
} else if (phase === 'find_missing' && idx === i) {
fill = "#fce4ec"; stroke = "#e91e63";
} else if (isCorrect) {
fill = "#c8e6c9"; stroke = "#66bb6a";
} else if (num <= 0 || num > n) {
fill = "#ffccbc"; stroke = "#ff7043";
}
svg.append("rect")
.attr("x", x).attr("y", startY + 40)
.attr("width", cellWidth - 5).attr("height", 55)
.attr("rx", 8)
.attr("fill", fill).attr("stroke", stroke)
.attr("stroke-width", 2);
svg.append("text")
.attr("x", x + (cellWidth - 5) / 2)
.attr("y", startY + 75)
.attr("text-anchor", "middle")
.attr("font-size", "22px")
.attr("font-weight", "bold")
.text(num);
// Index
svg.append("text")
.attr("x", x + (cellWidth - 5) / 2)
.attr("y", startY + 110)
.attr("text-anchor", "middle")
.attr("font-size", "11px")
.attr("fill", "#666")
.text(`[${idx}]`);
});
// Current pointer
if (i < n && phase !== 'done') {
svg.append("text")
.attr("x", startX + i * cellWidth + (cellWidth - 5) / 2)
.attr("y", startY + 25)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("fill", "#f59e0b")
.text("▼ i");
}
// Phase indicator
const phaseY = 220;
const phases = [
{ name: "Cyclic Sort", active: phase === 'cyclic_sort' },
{ name: "Find Missing", active: phase === 'find_missing' }
];
phases.forEach((p, idx) => {
svg.append("rect")
.attr("x", 150 + idx * 200).attr("y", phaseY)
.attr("width", 150).attr("height", 40)
.attr("rx", 8)
.attr("fill", p.active ? "#e8f5e9" : "#f5f5f5")
.attr("stroke", p.active ? "#4caf50" : "#ddd");
svg.append("text")
.attr("x", 225 + idx * 200).attr("y", phaseY + 26)
.attr("text-anchor", "middle")
.attr("font-weight", p.active ? "bold" : "normal")
.text(p.name);
});
// Legend
const legendY = 280;
const legend = [
{ color: "#c8e6c9", text: "Correct position" },
{ color: "#ffccbc", text: "Invalid (≤0 or >n)" },
{ color: "#fef3c7", text: "Current" }
];
legend.forEach((item, idx) => {
svg.append("rect")
.attr("x", 100 + idx * 200).attr("y", legendY)
.attr("width", 18).attr("height", 18)
.attr("fill", item.color).attr("stroke", "#999");
svg.append("text")
.attr("x", 125 + idx * 200).attr("y", legendY + 14)
.attr("font-size", "12px")
.text(item.text);
});
// Result
if (phase === 'done' && result !== null) {
svg.append("rect")
.attr("x", width / 2 - 120).attr("y", 320)
.attr("width", 240).attr("height", 45)
.attr("rx", 10)
.attr("fill", "#d1fae5").attr("stroke", "#10b981")
.attr("stroke-width", 2);
svg.append("text")
.attr("x", width / 2).attr("y", 350)
.attr("text-anchor", "middle")
.attr("font-size", "20px")
.attr("font-weight", "bold")
.attr("fill", "#10b981")
.text(`First Missing Positive: ${result}`);
}
}
function step() {
if (phase === 'done') return false;
const n = nums.length;
if (phase === 'cyclic_sort') {
if (i >= n) {
phase = 'find_missing';
i = 0;
document.getElementById("status").textContent =
"Cyclic sort complete. Now finding first missing...";
} else {
const num = nums[i];
const correct = num - 1;
if (num > 0 && num <= n && nums[i] !== nums[correct]) {
// Swap
[nums[i], nums[correct]] = [nums[correct], nums[i]];
document.getElementById("status").textContent =
`Swapped ${num} to its correct position [${correct}]`;
} else {
document.getElementById("status").textContent =
num <= 0 || num > n
? `${num} is out of range [1, ${n}], skip`
: `${num} is already in correct position, move on`;
i++;
}
}
} else if (phase === 'find_missing') {
if (i >= n) {
result = n + 1;
phase = 'done';
document.getElementById("status").textContent =
`All positions filled correctly. Answer is ${result}`;
} else if (nums[i] !== i + 1) {
result = i + 1;
phase = 'done';
document.getElementById("status").textContent =
`Position ${i} should have ${i + 1} but has ${nums[i]}. Answer is ${result}`;
} else {
document.getElementById("status").textContent =
`Position ${i} has correct value ${nums[i]}, continue...`;
i++;
}
}
draw();
return phase !== 'done';
}
function reset() {
nums = [...originalNums];
phase = 'cyclic_sort';
i = 0;
result = null;
if (autoTimer) clearInterval(autoTimer);
autoRunning = false;
document.getElementById("autoBtn").textContent = "Auto Run";
document.getElementById("status").textContent = 'Click "Step" to find first missing positive';
draw();
}
function autoRun() {
if (autoRunning) {
clearInterval(autoTimer);
autoRunning = false;
document.getElementById("autoBtn").textContent = "Auto Run";
} else {
autoRunning = true;
document.getElementById("autoBtn").textContent = "Pause";
autoTimer = setInterval(() => {
if (!step()) {
clearInterval(autoTimer);
autoRunning = false;
document.getElementById("autoBtn").textContent = "Auto Run";
}
}, 700);
}
}
document.getElementById("stepBtn").addEventListener("click", step);
document.getElementById("autoBtn").addEventListener("click", autoRun);
document.getElementById("resetBtn").addEventListener("click", reset);
reset();
</script>
</body>
</html>