-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0128_longest_consecutive_sequence.html
More file actions
410 lines (354 loc) · 15.9 KB
/
0128_longest_consecutive_sequence.html
File metadata and controls
410 lines (354 loc) · 15.9 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LC 128: Longest Consecutive Sequence - Algorithm Visualization</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">#128</span> Longest Consecutive Sequence</h1>
<p>Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. Must run in O(n) time.</p>
<div class="problem-meta">
<span class="meta-tag">📁 Array</span>
<span class="meta-tag">🔤 Hash Set</span>
<span class="meta-tag">⏱️ O(n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0128_longest_consecutive_sequence/0128_longest_consecutive_sequence.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>Imagine you have scattered puzzle pieces numbered 1, 2, 3, 4, 100, 200. You want to find the longest chain of consecutive numbers.</p>
<ul>
<li><strong>Step 1:</strong> Put all numbers in a set for fast lookup</li>
<li><strong>Step 2:</strong> For each number, check if it's the START of a sequence (no number before it)</li>
<li><strong>Step 3:</strong> If it's a start, count how far the sequence goes (1→2→3→4...)</li>
<li><strong>Step 4:</strong> Track the longest chain found</li>
</ul>
<p>The key insight: Only start counting from sequence starts (where n-1 doesn't exist). This ensures O(n) time!</p>
</div>
<div class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<button class="btn btn-primary" id="stepBtn" onclick="step()">Step</button>
<button class="btn btn-success" id="autoBtn" onclick="toggleAuto()">Auto Run</button>
<button class="btn btn-warning" onclick="reset()">Reset</button>
</div>
<div class="status-message" id="statusMessage">
Click "Step" or "Auto Run" to start visualization
</div>
<div class="variable-display">
<div class="variable-box">
<div class="variable-name">Current Number</div>
<div class="variable-value" id="currentNum">-</div>
</div>
<div class="variable-box">
<div class="variable-name">Current Streak</div>
<div class="variable-value" id="currentStreak">0</div>
</div>
<div class="variable-box">
<div class="variable-name">Longest Streak</div>
<div class="variable-value" id="longestStreak" style="color: #4caf50;">0</div>
</div>
</div>
<div class="array-section">
<div class="array-label">📥 Input Array (as Set):</div>
<div class="array-container" id="setContainer"></div>
</div>
<div class="array-section">
<div class="array-label">🔗 Current Sequence Being Built:</div>
<div class="array-container" id="sequenceContainer">
<div style="color: #999; padding: 10px;">Sequence will appear here</div>
</div>
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List
"""
LeetCode Longest Consecutive Sequence
Problem from LeetCode: https://leetcode.com/problems/longest-consecutive-sequence/
Description:
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in O(n) time.
Example 1:
Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
Example 2:
Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9
"""
class Solution:
def longest_consecutive(self, nums: List[int]) -> int:
"""
Find the length of the longest consecutive sequence.
Uses a hash set to achieve O(n) time complexity.
Args:
nums: Unsorted array of integers
Returns:
int: Length of longest consecutive sequence
"""
if not nums:
return 0
# Convert the list to a set for O(1) lookups
num_set = set(nums)
longest_streak = 0
for num in num_set:
# Only check sequences starting from the smallest number in the sequence
# Skip if there's already a smaller number before the current number
if num - 1 not in num_set:
current_num = num
current_streak = 1
# Count consecutive numbers
while current_num + 1 in num_set:
current_num += 1
current_streak += 1
# Update the longest streak
longest_streak = max(longest_streak, current_streak)
return longest_streak
def longest_consecutive_union_find(self, nums: List[int]) -> int:
"""
Find the longest consecutive sequence using Union-Find.
Args:
nums: Unsorted array of integers
Returns:
int: Length of longest consecutive sequence
"""
if not nums:
return 0
# Create parent dictionary for Union-Find
parent = {}
size = {}
# Initialize parent and size for each number
for num in nums:
parent[num] = num
size[num] = 1
# Find function for Union-Find with path compression
def find(x):
if parent[x] != x:
parent[x] = find(parent[x])
return parent[x]
# Union function
def union(x, y):
root_x = find(x)
root_y = find(y)
if root_x != root_y:
# Make the larger root the parent of the smaller root
if size[root_x] < size[root_y]:
parent[root_x] = root_y
size[root_y] += size[root_x]
else:
parent[root_y] = root_x
size[root_x] += size[root_y]
# Union consecutive numbers
num_set = set(nums)
for num in num_set:
if num + 1 in num_set:
union(num, num + 1)
# Find the maximum size
max_size = 0
for num in num_set:
if parent[num] == num: # Only consider roots
max_size = max(max_size, size[num])
return max_size
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
nums1 = [100, 4, 200, 1, 3, 2]
result1 = solution.longest_consecutive(nums1)
print(f"Example 1: nums={nums1}, result={result1}") # Expected output: 4
# Example 2
nums2 = [0, 3, 7, 2, 5, 8, 4, 6, 0, 1]
result2 = solution.longest_consecutive(nums2)
print(f"Example 2: nums={nums2}, result={result2}") # Expected output: 9
# Edge case
nums3 = []
result3 = solution.longest_consecutive(nums3)
print(f"Edge case: nums={nums3}, result={result3}") # Expected output: 0
# Compare with Union-Find approach
print("\nUsing Union-Find approach:")
print(f"Example 1: {solution.longest_consecutive_union_find(nums1)}")
print(f"Example 2: {solution.longest_consecutive_union_find(nums2)}")
</pre>
</div>
</div>
</div>
<script>
const nums = [100, 4, 200, 1, 3, 2];
const numSet = new Set(nums);
const sortedNums = Array.from(numSet).sort((a, b) => a - b);
let setIndex = 0;
let currentNum = null;
let currentStreak = 0;
let longestStreak = 0;
let currentSequence = [];
let phase = 'check'; // 'check' or 'extend'
let autoInterval = null;
function init() {
renderSet();
document.getElementById('currentNum').textContent = '-';
document.getElementById('currentStreak').textContent = '0';
document.getElementById('longestStreak').textContent = '0';
document.getElementById('sequenceContainer').innerHTML = '<div style="color: #999; padding: 10px;">Sequence will appear here</div>';
}
function renderSet() {
const container = document.getElementById('setContainer');
container.innerHTML = '';
sortedNums.forEach((num) => {
const box = document.createElement('div');
box.className = 'array-box';
box.id = `set-${num}`;
box.textContent = num;
container.appendChild(box);
});
}
function renderSequence() {
const container = document.getElementById('sequenceContainer');
container.innerHTML = '';
if (currentSequence.length === 0) {
container.innerHTML = '<div style="color: #999; padding: 10px;">Sequence will appear here</div>';
return;
}
currentSequence.forEach((num, idx) => {
if (idx > 0) {
const arrow = document.createElement('span');
arrow.textContent = '→';
arrow.style.fontSize = '1.5em';
arrow.style.color = '#4caf50';
container.appendChild(arrow);
}
const box = document.createElement('div');
box.className = 'array-box';
box.style.background = '#e8f5e9';
box.style.borderColor = '#4caf50';
box.textContent = num;
container.appendChild(box);
});
}
function clearHighlights() {
sortedNums.forEach(num => {
const el = document.getElementById(`set-${num}`);
if (el) {
el.classList.remove('highlight', 'current', 'visited');
el.style.background = '';
el.style.borderColor = '';
}
});
}
function step() {
if (setIndex >= sortedNums.length) {
document.getElementById('statusMessage').className = 'status-message success';
document.getElementById('statusMessage').textContent =
`✅ Done! Longest consecutive sequence has length ${longestStreak}`;
document.getElementById('stepBtn').disabled = true;
stopAuto();
return;
}
if (phase === 'check') {
const num = sortedNums[setIndex];
clearHighlights();
document.getElementById(`set-${num}`).classList.add('highlight');
document.getElementById('currentNum').textContent = num;
// Check if this is start of sequence (num-1 not in set)
if (!numSet.has(num - 1)) {
// Start of a new sequence
currentNum = num;
currentStreak = 1;
currentSequence = [num];
renderSequence();
document.getElementById('currentStreak').textContent = currentStreak;
document.getElementById(`set-${num}`).style.background = '#e8f5e9';
document.getElementById(`set-${num}`).style.borderColor = '#4caf50';
document.getElementById('statusMessage').textContent =
`${num} is a sequence START (${num-1} not in set). Starting new sequence...`;
// Check if we can extend
if (numSet.has(num + 1)) {
phase = 'extend';
} else {
// Single number sequence
longestStreak = Math.max(longestStreak, currentStreak);
document.getElementById('longestStreak').textContent = longestStreak;
setIndex++;
}
} else {
document.getElementById('statusMessage').textContent =
`${num} is NOT a sequence start (${num-1} exists). Skipping...`;
document.getElementById(`set-${num}`).style.background = '#f5f5f5';
setIndex++;
}
} else if (phase === 'extend') {
currentNum++;
if (numSet.has(currentNum)) {
currentStreak++;
currentSequence.push(currentNum);
renderSequence();
document.getElementById('currentNum').textContent = currentNum;
document.getElementById('currentStreak').textContent = currentStreak;
document.getElementById(`set-${currentNum}`).classList.add('highlight');
document.getElementById(`set-${currentNum}`).style.background = '#e8f5e9';
document.getElementById(`set-${currentNum}`).style.borderColor = '#4caf50';
document.getElementById('statusMessage').textContent =
`Found ${currentNum} in set! Sequence extended to length ${currentStreak}`;
if (!numSet.has(currentNum + 1)) {
// Sequence ends
longestStreak = Math.max(longestStreak, currentStreak);
document.getElementById('longestStreak').textContent = longestStreak;
phase = 'check';
setIndex++;
}
} else {
// Should not happen in this logic, but safety
longestStreak = Math.max(longestStreak, currentStreak);
document.getElementById('longestStreak').textContent = longestStreak;
phase = 'check';
setIndex++;
}
}
}
function toggleAuto() {
if (autoInterval) {
stopAuto();
} else {
document.getElementById('autoBtn').textContent = 'Pause';
autoInterval = setInterval(() => {
if (setIndex >= sortedNums.length) {
step();
stopAuto();
} else {
step();
}
}, 800);
}
}
function stopAuto() {
if (autoInterval) {
clearInterval(autoInterval);
autoInterval = null;
}
document.getElementById('autoBtn').textContent = 'Auto Run';
}
function reset() {
stopAuto();
setIndex = 0;
currentNum = null;
currentStreak = 0;
longestStreak = 0;
currentSequence = [];
phase = 'check';
document.getElementById('stepBtn').disabled = false;
document.getElementById('statusMessage').className = 'status-message';
document.getElementById('statusMessage').textContent = 'Click "Step" or "Auto Run" to start visualization';
init();
}
init();
</script>
</body>
</html>