-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0015_3_sum.html
More file actions
403 lines (345 loc) · 15.1 KB
/
0015_3_sum.html
File metadata and controls
403 lines (345 loc) · 15.1 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LC 15: 3Sum - 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">#15</span> 3Sum</h1>
<p>Given an integer array nums, return all unique triplets [nums[i], nums[j], nums[k]] where i ≠ j ≠ k and nums[i] + nums[j] + nums[k] == 0.</p>
<div class="problem-meta">
<span class="meta-tag">📁 Array</span>
<span class="meta-tag">👉👈 Two Pointers</span>
<span class="meta-tag">📊 Sorting</span>
<span class="meta-tag">⏱️ O(n²)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0015_3_sum/0015_3_sum.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>We want to find three numbers that add up to zero. The trick is:</p>
<ul>
<li><strong>Sort first:</strong> This lets us use two pointers efficiently</li>
<li><strong>Fix one number:</strong> For each number, find two others that complete the sum</li>
<li><strong>Two pointers:</strong> After fixing one number, use left/right pointers on the rest</li>
<li><strong>Adjust pointers:</strong> If sum too small → move left up. If too big → move right down</li>
<li><strong>Skip duplicates:</strong> To avoid duplicate triplets</li>
</ul>
</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">Fixed (i)</div>
<div class="variable-value" id="fixedVal" style="color: #9c27b0;">-</div>
</div>
<div class="variable-box">
<div class="variable-name">Left</div>
<div class="variable-value" id="leftVal" style="color: #ff5722;">-</div>
</div>
<div class="variable-box">
<div class="variable-name">Right</div>
<div class="variable-value" id="rightVal" style="color: #3f51b5;">-</div>
</div>
<div class="variable-box">
<div class="variable-name">Sum</div>
<div class="variable-value" id="sumVal">-</div>
</div>
</div>
<div class="array-section">
<div class="array-label">📥 Sorted Array:</div>
<div class="array-container" id="arrayContainer"></div>
</div>
<div class="array-section">
<div class="array-label">✅ Found Triplets:</div>
<div id="tripletsContainer">
<div style="color: #999; padding: 10px;">No triplets found yet</div>
</div>
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List
"""
LeetCode 3Sum
Problem from LeetCode: https://leetcode.com/problems/3sum/
Description:
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
Notice that the solution set must not contain duplicate triplets.
Example 1:
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Explanation:
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.
The distinct triplets are [-1,0,1] and [-1,-1,2].
Notice that the order of the output and the order of the triplets does not matter.
Example 2:
Input: nums = [0,1,1]
Output: []
Explanation: The only possible triplet does not sum up to 0.
Example 3:
Input: nums = [0,0,0]
Output: [[0,0,0]]
Explanation: The only possible triplet sums up to 0.
"""
class Solution:
def three_sum(self, nums: List[int]) -> List[List[int]]:
"""
Find all unique triplets in the array that sum to zero.
Args:
nums: Array of integers
Returns:
List[List[int]]: List of all unique triplets that sum to zero
"""
if len(nums) < 3:
return []
# Sort the array to make it easier to handle duplicates
nums.sort()
result = []
for i in range(len(nums) - 2):
# Early exit: if the smallest number is positive, no triplet can sum to zero
if nums[i] > 0:
break
# Skip duplicate values for the first element
if i > 0 and nums[i] == nums[i-1]:
continue
# Two-pointer approach for the remaining two elements
left, right = i + 1, len(nums) - 1
while left < right:
total = nums[i] + nums[left] + nums[right]
if total < 0:
left += 1
elif total > 0:
right -= 1
else:
# Found a triplet
result.append([nums[i], nums[left], nums[right]])
# Skip duplicates for the second element
while left < right and nums[left] == nums[left+1]:
left += 1
# Skip duplicates for the third element
while left < right and nums[right] == nums[right-1]:
right -= 1
left += 1
right -= 1
return result
def three_sum_hash_set(self, nums: List[int]) -> List[List[int]]:
"""
Alternative implementation using a hash set approach.
Args:
nums: Array of integers
Returns:
List[List[int]]: List of all unique triplets that sum to zero
"""
res = set() # Use set to avoid duplicate triplets
nums.sort()
for i in range(len(nums) - 2):
# Early exit: if the smallest number is positive, no triplet can sum to zero
if nums[i] > 0:
break
# Skip duplicates
if i > 0 and nums[i] == nums[i-1]:
continue
# Use a hash set to find pairs
seen = set()
for j in range(i + 1, len(nums)):
complement = -nums[i] - nums[j]
if complement in seen:
# Store as tuple in set to avoid duplicates
res.add((nums[i], complement, nums[j]))
seen.add(nums[j])
# Convert back to list of lists
return [list(triplet) for triplet in res]
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
nums1 = [-1, 0, 1, 2, -1, -4]
result1 = solution.three_sum(nums1)
print(f"Example 1: {nums1} -> {result1}") # Expected output: [[-1,-1,2],[-1,0,1]]
# Example 2
nums2 = [0, 1, 1]
result2 = solution.three_sum(nums2)
print(f"Example 2: {nums2} -> {result2}") # Expected output: []
# Example 3
nums3 = [0, 0, 0]
result3 = solution.three_sum(nums3)
print(f"Example 3: {nums3} -> {result3}") # Expected output: [[0,0,0]]
# Additional example
nums4 = [-2, 0, 0, 2, 2]
result4 = solution.three_sum(nums4)
print(f"Example 4: {nums4} -> {result4}") # Expected output: [[-2,0,2]]
</pre>
</div>
</div>
</div>
<script>
const originalNums = [-1, 0, 1, 2, -1, -4];
const nums = [...originalNums].sort((a, b) => a - b);
let i = 0, left = 1, right = nums.length - 1;
let triplets = [];
let phase = 'init';
let autoInterval = null;
function init() {
renderArray();
document.getElementById('fixedVal').textContent = '-';
document.getElementById('leftVal').textContent = '-';
document.getElementById('rightVal').textContent = '-';
document.getElementById('sumVal').textContent = '-';
}
function renderArray() {
const container = document.getElementById('arrayContainer');
container.innerHTML = '';
nums.forEach((num, idx) => {
const box = document.createElement('div');
box.className = 'array-box';
box.id = `arr-${idx}`;
box.innerHTML = `${num}<span class="index-label">[${idx}]</span>`;
if (idx === i) {
box.style.background = '#e1bee7';
box.style.borderColor = '#9c27b0';
}
if (idx === left && phase !== 'init') {
box.style.background = '#ffccbc';
box.style.borderColor = '#ff5722';
}
if (idx === right && phase !== 'init') {
box.style.background = '#c5cae9';
box.style.borderColor = '#3f51b5';
}
container.appendChild(box);
});
}
function renderTriplets() {
const container = document.getElementById('tripletsContainer');
if (triplets.length === 0) {
container.innerHTML = '<div style="color: #999; padding: 10px;">No triplets found yet</div>';
return;
}
container.innerHTML = '';
triplets.forEach((triplet, idx) => {
const tripletDiv = document.createElement('div');
tripletDiv.style.cssText = 'display: inline-block; padding: 10px 20px; background: #e8f5e9; border: 2px solid #4caf50; border-radius: 8px; margin: 5px; font-weight: bold;';
tripletDiv.textContent = `[${triplet.join(', ')}]`;
container.appendChild(tripletDiv);
});
}
function step() {
if (i >= nums.length - 2) {
document.getElementById('statusMessage').className = 'status-message success';
document.getElementById('statusMessage').textContent =
`✅ Done! Found ${triplets.length} unique triplet(s).`;
document.getElementById('stepBtn').disabled = true;
stopAuto();
return;
}
if (phase === 'init') {
phase = 'searching';
left = i + 1;
right = nums.length - 1;
}
// Skip duplicate i values
if (i > 0 && nums[i] === nums[i - 1]) {
document.getElementById('statusMessage').textContent =
`Skipping duplicate fixed value: ${nums[i]}`;
i++;
left = i + 1;
right = nums.length - 1;
renderArray();
return;
}
document.getElementById('fixedVal').textContent = nums[i];
document.getElementById('leftVal').textContent = nums[left];
document.getElementById('rightVal').textContent = nums[right];
if (left >= right) {
// Move to next i
i++;
left = i + 1;
right = nums.length - 1;
document.getElementById('statusMessage').textContent =
`Pointers crossed. Moving to next fixed value.`;
renderArray();
return;
}
const total = nums[i] + nums[left] + nums[right];
document.getElementById('sumVal').textContent = total;
if (total < 0) {
document.getElementById('statusMessage').textContent =
`Sum = ${nums[i]} + ${nums[left]} + ${nums[right]} = ${total} < 0. Move left →`;
left++;
} else if (total > 0) {
document.getElementById('statusMessage').textContent =
`Sum = ${nums[i]} + ${nums[left]} + ${nums[right]} = ${total} > 0. Move right ←`;
right--;
} else {
// Found a triplet!
triplets.push([nums[i], nums[left], nums[right]]);
renderTriplets();
document.getElementById('statusMessage').className = 'status-message success';
document.getElementById('statusMessage').textContent =
`🎯 Found triplet: [${nums[i]}, ${nums[left]}, ${nums[right]}]!`;
// Skip duplicates
while (left < right && nums[left] === nums[left + 1]) left++;
while (left < right && nums[right] === nums[right - 1]) right--;
left++;
right--;
}
renderArray();
}
function toggleAuto() {
if (autoInterval) {
stopAuto();
} else {
document.getElementById('autoBtn').textContent = 'Pause';
autoInterval = setInterval(() => {
if (i >= nums.length - 2) {
step();
stopAuto();
} else {
step();
}
}, 1000);
}
}
function stopAuto() {
if (autoInterval) {
clearInterval(autoInterval);
autoInterval = null;
}
document.getElementById('autoBtn').textContent = 'Auto Run';
}
function reset() {
stopAuto();
i = 0;
left = 1;
right = nums.length - 1;
triplets = [];
phase = 'init';
document.getElementById('stepBtn').disabled = false;
document.getElementById('statusMessage').className = 'status-message';
document.getElementById('statusMessage').textContent = 'Click "Step" or "Auto Run" to start visualization';
document.getElementById('tripletsContainer').innerHTML = '<div style="color: #999; padding: 10px;">No triplets found yet</div>';
init();
}
init();
</script>
</body>
</html>