-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0066_plus_one.html
More file actions
436 lines (375 loc) · 15.2 KB
/
Copy path0066_plus_one.html
File metadata and controls
436 lines (375 loc) · 15.2 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>066 - Plus One</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">#066</span> Plus One</h1>
<p>
Given a large integer represented as an integer array digits, increment one to the integer.
Handle carry propagation when digit is 9. May need to prepend 1 for cases like 999 + 1 = 1000.
</p>
<div class="problem-meta">
<span class="meta-tag">🔢 Math</span>
<span class="meta-tag">⏱️ O(n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0066_plus_one/0066_plus_one.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>
<section class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<button id="autoRunBtn" class="btn">▶ Auto Run</button>
<button id="stepBtn" class="btn btn-success">Step</button>
<button id="resetBtn" class="btn btn-danger">Reset</button>
<select id="exampleSelect" style="margin-left: 15px; padding: 8px;">
<option value="129">Example: [1, 2, 9]</option>
<option value="999">Example: [9, 9, 9]</option>
<option value="123">Example: [1, 2, 3]</option>
</select>
</div>
<div class="status" id="status">Add 1 to the number</div>
<svg id="visualization"></svg>
</section>
<section class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List
"""
LeetCode Plus One
Problem from LeetCode: https://leetcode.com/problems/plus-one/
Description:
You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's.
Increment the large integer by one and return the resulting array of digits.
Example 1:
Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be [1,2,4].
Example 2:
Input: digits = [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
Incrementing by one gives 4321 + 1 = 4322.
Thus, the result should be [4,3,2,2].
Example 3:
Input: digits = [9]
Output: [1,0]
Explanation: The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be [1,0].
"""
class Solution:
def plus_one(self, digits: List[int]) ->List[int]:
"""
Add one to the integer represented by the digits array.
The array represents a non-negative integer, where each element
is a single digit, and the most significant digit is at the start.
Args:
digits: Array of digits representing a non-negative integer
Returns:
List[int]: The resulting array after adding one
"""
for i in range(len(digits) - 1, -1, -1):
if digits[i] < 9:
digits[i] += 1
return digits
digits[i] = 0
result = [0] * (len(digits) + 1)
result[0] = 1
return result
def plusOne_pythonic(self, digits: List[int]) ->List[int]:
"""
Add one using a more Pythonic approach by converting to integer and back.
Args:
digits: Array of digits representing a non-negative integer
Returns:
List[int]: The resulting array after adding one
"""
num = 0
for digit in digits:
num = num * 10 + digit
num += 1
return [int(digit) for digit in str(num)]
def plusOne_direct(self, digits: List[int]) ->List[int]:
"""
Add one directly to the array with explicit carry handling.
Args:
digits: Array of digits representing a non-negative integer
Returns:
List[int]: The resulting array after adding one
"""
result = digits.copy()
carry = 1
for i in range(len(result) - 1, -1, -1):
result[i] += carry
carry = result[i] // 10
result[i] %= 10
if carry == 0:
break
if carry > 0:
result.insert(0, carry)
return result
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
digits1 = [1, 2, 3]
result1 = solution.plus_one(digits1)
print(f"Example 1: {digits1} + 1 = {result1}") # Expected output: [1, 2, 4]
# Example 2
digits2 = [4, 3, 2, 1]
result2 = solution.plus_one(digits2)
print(f"Example 2: {digits2} + 1 = {result2}") # Expected output: [4, 3, 2, 2]
# Example 3
digits3 = [9]
result3 = solution.plus_one(digits3)
print(f"Example 3: {digits3} + 1 = {result3}") # Expected output: [1, 0]
# Additional example with all 9s
digits4 = [9, 9, 9]
result4 = solution.plus_one(digits4)
print(f"Example 4: {digits4} + 1 = {result4}") # Expected output: [1, 0, 0, 0]
# Compare different implementations
print("\nComparing implementations:")
digits5 = [4, 9, 9, 9]
print(f"Standard: {solution.plus_one(digits5.copy())}")
print(f"Pythonic: {solution.plusOne_pythonic(digits5.copy())}")
print(f"Direct: {solution.plusOne_direct(digits5.copy())}")
</pre>
</div>
</section>
</div>
<script>
const width = 900;
const height = 450;
const svg = d3.select("#visualization")
.attr("width", width)
.attr("height", height);
let originalDigits = [1, 2, 9];
let digits;
let currentIdx;
let phase = "init";
let animationTimer = null;
let carry = 1;
document.getElementById("exampleSelect").addEventListener("change", (e) => {
originalDigits = e.target.value.split('').map(Number);
reset();
});
function reset() {
digits = [...originalDigits];
currentIdx = digits.length - 1;
phase = "init";
carry = 1;
if (animationTimer) clearInterval(animationTimer);
animationTimer = null;
document.getElementById("autoRunBtn").textContent = "▶ Auto Run";
document.getElementById("status").textContent = `Add 1 to [${originalDigits.join(', ')}]`;
render();
}
function render() {
svg.selectAll("*").remove();
const cellWidth = 70;
const startX = 100;
const arrayY = 100;
// Title
svg.append("text")
.attr("x", 30)
.attr("y", 40)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(`Plus One: [${originalDigits.join(', ')}] + 1`);
// Draw current digits
svg.append("text")
.attr("x", 30)
.attr("y", arrayY + 30)
.attr("font-size", "13px")
.attr("fill", "#64748b")
.text("digits:");
digits.forEach((digit, idx) => {
const x = startX + idx * cellWidth;
const isCurrent = idx === currentIdx && phase !== "done";
const isModified = idx > currentIdx || (idx === currentIdx && phase === "done");
svg.append("rect")
.attr("x", x)
.attr("y", arrayY)
.attr("width", cellWidth - 10)
.attr("height", 55)
.attr("rx", 8)
.attr("fill", () => {
if (isCurrent) return "#fef3c7";
if (isModified) return "#d1fae5";
return "#f8fafc";
})
.attr("stroke", () => {
if (isCurrent) return "#f59e0b";
if (isModified) return "#10b981";
return "#94a3b8";
})
.attr("stroke-width", isCurrent ? 3 : 2);
svg.append("text")
.attr("x", x + (cellWidth - 10) / 2)
.attr("y", arrayY + 38)
.attr("text-anchor", "middle")
.attr("font-size", "24px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(digit);
// Index label
svg.append("text")
.attr("x", x + (cellWidth - 10) / 2)
.attr("y", arrayY + 75)
.attr("text-anchor", "middle")
.attr("font-size", "11px")
.attr("fill", "#64748b")
.text(`[${idx}]`);
// Current pointer
if (isCurrent) {
svg.append("text")
.attr("x", x + (cellWidth - 10) / 2)
.attr("y", arrayY - 15)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("font-weight", "bold")
.attr("fill", "#f59e0b")
.text("▼ checking");
}
});
// Carry indicator
if (carry && phase !== "done") {
svg.append("rect")
.attr("x", startX + digits.length * cellWidth + 20)
.attr("y", arrayY)
.attr("width", 80)
.attr("height", 55)
.attr("rx", 8)
.attr("fill", "#fce7f3")
.attr("stroke", "#ec4899");
svg.append("text")
.attr("x", startX + digits.length * cellWidth + 60)
.attr("y", arrayY + 25)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("fill", "#ec4899")
.text("carry");
svg.append("text")
.attr("x", startX + digits.length * cellWidth + 60)
.attr("y", arrayY + 45)
.attr("text-anchor", "middle")
.attr("font-size", "20px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("+1");
}
// Algorithm explanation
const algoY = 230;
svg.append("text")
.attr("x", 30)
.attr("y", algoY)
.attr("font-size", "13px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Algorithm:");
const steps = [
"1. Start from rightmost digit",
"2. If digit < 9: add 1 and return",
"3. If digit = 9: set to 0, carry to left",
"4. If all 9s: prepend 1 (e.g., 999 → 1000)"
];
steps.forEach((step, i) => {
svg.append("text")
.attr("x", 30)
.attr("y", algoY + 25 + i * 22)
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text(step);
});
// Result
if (phase === "done") {
svg.append("rect")
.attr("x", 30)
.attr("y", 360)
.attr("width", 450)
.attr("height", 55)
.attr("rx", 10)
.attr("fill", "#d1fae5")
.attr("stroke", "#10b981")
.attr("stroke-width", 2);
svg.append("text")
.attr("x", 255)
.attr("y", 395)
.attr("text-anchor", "middle")
.attr("font-size", "18px")
.attr("font-weight", "bold")
.attr("fill", "#10b981")
.text(`✓ [${originalDigits.join(', ')}] + 1 = [${digits.join(', ')}]`);
}
}
function step() {
if (phase === "done") return;
if (currentIdx < 0) {
// Need to prepend 1
digits.unshift(1);
phase = "done";
document.getElementById("status").textContent =
`All digits were 9! Prepending 1: [${digits.join(', ')}]`;
render();
return;
}
if (digits[currentIdx] < 9) {
digits[currentIdx]++;
carry = 0;
phase = "done";
document.getElementById("status").textContent =
`✓ digits[${currentIdx}] = ${digits[currentIdx]-1} + 1 = ${digits[currentIdx]}. Done!`;
} else {
digits[currentIdx] = 0;
document.getElementById("status").textContent =
`digits[${currentIdx}] = 9, set to 0, carry to left`;
currentIdx--;
}
render();
}
function autoRun() {
if (animationTimer) {
clearInterval(animationTimer);
animationTimer = null;
document.getElementById("autoRunBtn").textContent = "▶ Auto Run";
return;
}
document.getElementById("autoRunBtn").textContent = "⏸ Pause";
animationTimer = setInterval(() => {
if (phase === "done") {
clearInterval(animationTimer);
animationTimer = null;
document.getElementById("autoRunBtn").textContent = "▶ Auto Run";
return;
}
step();
}, 1000);
}
document.getElementById("autoRunBtn").addEventListener("click", autoRun);
document.getElementById("stepBtn").addEventListener("click", step);
document.getElementById("resetBtn").addEventListener("click", reset);
reset();
</script>
</body>
</html>