-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0238_product_of_array_except_self.html
More file actions
421 lines (371 loc) · 16.1 KB
/
0238_product_of_array_except_self.html
File metadata and controls
421 lines (371 loc) · 16.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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Product of Array Except Self - LeetCode 238</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">#0238</span> Product of Array Except Self</h1>
<p><strong>Problem:</strong> Given an integer array nums, return an array where each element is the product of all elements except itself. No division allowed!</p>
<p><strong>Pattern:</strong> Prefix & Suffix Products</p>
<p><strong>File:</strong> 0238_product_of_array_except_self/0238_product_of_array_except_self.py</p>
<div class="problem-meta">
<span class="meta-tag">📊 Array</span>
<span class="meta-tag">⏱️ O(n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0238_product_of_array_except_self/0238_product_of_array_except_self.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="controls">
<button id="stepBtn">Step</button>
<button id="autoBtn">Auto Run</button>
<button id="resetBtn">Reset</button>
<div class="speed-control">
<label for="speed">Speed:</label>
<input type="range" id="speed" min="100" max="2000" value="800">
</div>
</div>
<div class="status" id="status">Click "Step" or "Auto Run" to begin</div>
<div class="variables">
<div class="var-item">
<span class="var-label">Phase:</span>
<span id="phaseDisplay">Prefix Pass</span>
</div>
<div class="var-item">
<span class="var-label">Current Index:</span>
<span id="indexDisplay">-</span>
</div>
<div class="var-item">
<span class="var-label">Running Product:</span>
<span id="productDisplay">1</span>
</div>
</div>
<div class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="visualization">
<svg id="mainSvg"></svg>
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre><span class="keyword">def</span> <span class="function">product_except_self</span>(nums):
<span class="string">"""
Product of array except self without division.
Uses prefix products (left to right) then suffix products (right to left).
Time: O(n), Space: O(1) extra (result array doesn't count)
"""</span>
n = <span class="function">len</span>(nums)
result = [<span class="number">1</span>] * n
<span class="comment"># Pass 1: Calculate prefix products (product of all elements to the left)</span>
prefix = <span class="number">1</span>
<span class="keyword">for</span> i <span class="keyword">in</span> <span class="function">range</span>(n):
result[i] = prefix
prefix *= nums[i]
<span class="comment"># Pass 2: Multiply by suffix products (product of all elements to the right)</span>
postfix = <span class="number">1</span>
<span class="keyword">for</span> i <span class="keyword">in</span> <span class="function">range</span>(n - <span class="number">1</span>, <span class="number">-1</span>, <span class="number">-1</span>):
result[i] *= postfix
postfix *= nums[i]
<span class="keyword">return</span> result</pre>
</div>
</div>
</div>
<script>
// Visualization state
const nums = [1, 2, 3, 4];
let result = new Array(nums.length).fill(1);
let prefix = 1;
let postfix = 1;
let phase = "prefix"; // "prefix" or "postfix"
let currentIndex = -1;
let autoRunning = false;
let autoTimer = null;
// SVG setup
const width = 800;
const height = 350;
const svg = d3.select("#mainSvg")
.attr("width", width)
.attr("height", height);
const cellWidth = 80;
const cellHeight = 50;
const startX = (width - nums.length * cellWidth) / 2;
function drawArrays() {
svg.selectAll("*").remove();
// Input array label
svg.append("text")
.attr("x", startX - 80)
.attr("y", 50)
.attr("class", "label")
.text("nums:");
// Input array
const inputCells = svg.selectAll(".input-cell")
.data(nums)
.enter()
.append("g")
.attr("transform", (d, i) => `translate(${startX + i * cellWidth}, 25)`);
inputCells.append("rect")
.attr("width", cellWidth - 4)
.attr("height", cellHeight)
.attr("rx", 5)
.attr("class", "cell input-cell-rect")
.attr("id", (d, i) => `input-${i}`);
inputCells.append("text")
.attr("x", (cellWidth - 4) / 2)
.attr("y", cellHeight / 2)
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.attr("class", "cell-text")
.text(d => d);
// Index labels
inputCells.append("text")
.attr("x", (cellWidth - 4) / 2)
.attr("y", cellHeight + 18)
.attr("text-anchor", "middle")
.attr("class", "index-label")
.text((d, i) => `[${i}]`);
// Result array label
svg.append("text")
.attr("x", startX - 80)
.attr("y", 150)
.attr("class", "label")
.text("result:");
// Result array
const resultCells = svg.selectAll(".result-cell")
.data(result)
.enter()
.append("g")
.attr("transform", (d, i) => `translate(${startX + i * cellWidth}, 125)`);
resultCells.append("rect")
.attr("width", cellWidth - 4)
.attr("height", cellHeight)
.attr("rx", 5)
.attr("class", "cell result-cell-rect")
.attr("id", (d, i) => `result-${i}`);
resultCells.append("text")
.attr("x", (cellWidth - 4) / 2)
.attr("y", cellHeight / 2)
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.attr("class", "cell-text result-text")
.attr("id", (d, i) => `result-text-${i}`)
.text(d => d);
// Arrows for prefix (left to right)
if (phase === "prefix" && currentIndex >= 0) {
const arrowY = 210;
svg.append("line")
.attr("x1", startX)
.attr("y1", arrowY)
.attr("x2", startX + (currentIndex + 1) * cellWidth - 20)
.attr("y2", arrowY)
.attr("class", "arrow-line prefix-arrow");
svg.append("polygon")
.attr("points", `${startX + (currentIndex + 1) * cellWidth - 20},${arrowY - 5} ${startX + (currentIndex + 1) * cellWidth - 20},${arrowY + 5} ${startX + (currentIndex + 1) * cellWidth - 10},${arrowY}`)
.attr("class", "arrow-head prefix-arrow");
svg.append("text")
.attr("x", startX + (currentIndex + 1) * cellWidth / 2)
.attr("y", arrowY + 25)
.attr("text-anchor", "middle")
.attr("class", "phase-label")
.text(`prefix = ${prefix}`);
}
// Arrows for postfix (right to left)
if (phase === "postfix" && currentIndex >= 0 && currentIndex < nums.length) {
const arrowY = 250;
svg.append("line")
.attr("x1", startX + nums.length * cellWidth)
.attr("y1", arrowY)
.attr("x2", startX + currentIndex * cellWidth + 20)
.attr("y2", arrowY)
.attr("class", "arrow-line postfix-arrow");
svg.append("polygon")
.attr("points", `${startX + currentIndex * cellWidth + 20},${arrowY - 5} ${startX + currentIndex * cellWidth + 20},${arrowY + 5} ${startX + currentIndex * cellWidth + 10},${arrowY}`)
.attr("class", "arrow-head postfix-arrow");
svg.append("text")
.attr("x", startX + (currentIndex + nums.length) * cellWidth / 2)
.attr("y", arrowY + 25)
.attr("text-anchor", "middle")
.attr("class", "phase-label")
.text(`postfix = ${postfix}`);
}
// Final result display
if (phase === "done") {
svg.append("text")
.attr("x", width / 2)
.attr("y", 320)
.attr("text-anchor", "middle")
.attr("class", "result-final")
.text(`Final Result: [${result.join(", ")}]`);
}
}
function step() {
if (phase === "prefix") {
currentIndex++;
if (currentIndex >= nums.length) {
phase = "postfix";
currentIndex = nums.length - 1;
document.getElementById("phaseDisplay").textContent = "Postfix Pass";
document.getElementById("status").textContent = "Prefix pass complete! Starting postfix pass (right to left)...";
highlightCode("postfix = 1");
drawArrays();
return true;
}
result[currentIndex] = prefix;
prefix *= nums[currentIndex];
document.getElementById("indexDisplay").textContent = currentIndex;
document.getElementById("productDisplay").textContent = prefix;
document.getElementById("status").textContent =
`Prefix Pass: result[${currentIndex}] = ${result[currentIndex]} (product of elements to the left), then prefix = ${prefix / nums[currentIndex]} × ${nums[currentIndex]} = ${prefix}`;
highlightCode("result[i] = prefix");
drawArrays();
return true;
} else if (phase === "postfix") {
if (currentIndex < 0) {
phase = "done";
document.getElementById("phaseDisplay").textContent = "Complete!";
document.getElementById("status").textContent = `Done! Result: [${result.join(", ")}]`;
highlightCode("return result");
drawArrays();
return false;
}
result[currentIndex] *= postfix;
postfix *= nums[currentIndex];
document.getElementById("indexDisplay").textContent = currentIndex;
document.getElementById("productDisplay").textContent = postfix;
document.getElementById("status").textContent =
`Postfix Pass: result[${currentIndex}] *= ${postfix / nums[currentIndex]} = ${result[currentIndex]}, then postfix = ${postfix / nums[currentIndex]} × ${nums[currentIndex]} = ${postfix}`;
highlightCode("result[i] *= postfix");
// Highlight current cell
svg.select(`#result-${currentIndex}`).attr("class", "cell result-cell-rect current");
currentIndex--;
drawArrays();
return true;
}
return false;
}
function highlightCode(text) {
const codeDisplay = document.getElementById("codeDisplay");
const code = codeDisplay.textContent;
const highlighted = code.replace(
new RegExp(`(.*${text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}.*)`),
'<span class="highlight-line">$1</span>'
);
codeDisplay.innerHTML = highlighted;
}
function reset() {
result = new Array(nums.length).fill(1);
prefix = 1;
postfix = 1;
phase = "prefix";
currentIndex = -1;
autoRunning = false;
if (autoTimer) {
clearInterval(autoTimer);
autoTimer = null;
}
document.getElementById("phaseDisplay").textContent = "Prefix Pass";
document.getElementById("indexDisplay").textContent = "-";
document.getElementById("productDisplay").textContent = "1";
document.getElementById("status").textContent = 'Click "Step" or "Auto Run" to begin';
document.getElementById("autoBtn").textContent = "Auto Run";
drawArrays();
document.getElementById("codeDisplay").innerHTML = document.getElementById("codeDisplay").textContent;
}
function autoRun() {
if (autoRunning) {
autoRunning = false;
clearInterval(autoTimer);
autoTimer = null;
document.getElementById("autoBtn").textContent = "Auto Run";
} else {
autoRunning = true;
document.getElementById("autoBtn").textContent = "Pause";
const speed = 2100 - document.getElementById("speed").value;
autoTimer = setInterval(() => {
if (!step()) {
autoRunning = false;
clearInterval(autoTimer);
autoTimer = null;
document.getElementById("autoBtn").textContent = "Auto Run";
}
}, speed);
}
}
// Event listeners
document.getElementById("stepBtn").addEventListener("click", step);
document.getElementById("autoBtn").addEventListener("click", autoRun);
document.getElementById("resetBtn").addEventListener("click", reset);
// Initialize
drawArrays();
</script>
<style>
.cell {
fill: #e3f2fd;
stroke: #1976d2;
stroke-width: 2;
}
.cell.current {
fill: #fff3e0;
stroke: #f57c00;
stroke-width: 3;
}
.cell.result-cell-rect {
fill: #e8f5e9;
stroke: #43a047;
}
.cell-text {
font-size: 18px;
font-weight: bold;
fill: #333;
}
.label {
font-size: 16px;
font-weight: bold;
fill: #333;
}
.index-label {
font-size: 12px;
fill: #666;
}
.arrow-line {
stroke-width: 3;
}
.arrow-head {
}
.prefix-arrow {
stroke: #2196f3;
fill: #2196f3;
}
.postfix-arrow {
stroke: #ff9800;
fill: #ff9800;
}
.phase-label {
font-size: 14px;
fill: #333;
font-weight: bold;
}
.result-final {
font-size: 20px;
font-weight: bold;
fill: #388e3c;
}
</style>
</body>
</html>