-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0128_longest_consecutive_sequence.html
More file actions
292 lines (260 loc) · 12.8 KB
/
0128_longest_consecutive_sequence.html
File metadata and controls
292 lines (260 loc) · 12.8 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
<!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><span class="keyword">def</span> <span class="function">longest_consecutive</span>(self, nums: <span class="class-name">List</span>[int]) -> int:
num_set = <span class="function">set</span>(nums)
longest_streak = <span class="number">0</span>
<span class="keyword">for</span> num <span class="keyword">in</span> num_set:
<span class="comment"># Only start counting if this is the start of a sequence</span>
<span class="keyword">if</span> num - <span class="number">1</span> <span class="keyword">not</span> <span class="keyword">in</span> num_set:
current_num = num
current_streak = <span class="number">1</span>
<span class="keyword">while</span> current_num + <span class="number">1</span> <span class="keyword">in</span> num_set:
current_num += <span class="number">1</span>
current_streak += <span class="number">1</span>
longest_streak = <span class="function">max</span>(longest_streak, current_streak)
<span class="keyword">return</span> longest_streak</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>