-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0031_next_permutation.html
More file actions
440 lines (379 loc) · 16.8 KB
/
0031_next_permutation.html
File metadata and controls
440 lines (379 loc) · 16.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
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
437
438
439
440
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Next Permutation - LeetCode 31</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">#31</span> Next Permutation</h1>
<p>Rearrange numbers into the lexicographically next greater permutation.</p>
<div class="problem-meta">
<span class="meta-tag">Array</span>
<span class="meta-tag">Two Pointers</span>
<span class="meta-tag">Medium</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0031_next_permutation/0031_next_permutation.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>Backtracking <strong>explores all possibilities</strong> like solving a maze:</p>
<ul>
<li><strong>Choose:</strong> Make a decision</li>
<li><strong>Explore:</strong> Recursively continue</li>
<li><strong>Validate:</strong> Check if path is valid</li>
<li><strong>Backtrack:</strong> Undo choice if stuck, try another</li>
</ul>
</div>
<div class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<button id="stepBtn">Step</button>
<button id="autoBtn">Auto Run</button>
<button id="resetBtn">Reset</button>
</div>
<svg id="mainSvg" width="800" height="400"></svg>
<div class="status-message" id="status">Click "Step" to find next permutation</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List
"""
LeetCode Next Permutation
Problem from LeetCode: https://leetcode.com/problems/next-permutation/
Description:
A permutation of an array of integers is an arrangement of its members into a sequence or linear order.
For example, for arr = [1,2,3], the following are all the permutations of arr: [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1].
The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order).
For example, the next permutation of arr = [1,2,3] is [1,3,2].
Similarly, the next permutation of arr = [2,3,1] is [3,1,2].
While the next permutation of arr = [3,2,1] is [1,2,3] because [3,2,1] does not have a lexicographical larger rearrangement.
Given an array of integers nums, find the next permutation of nums.
The replacement must be in place and use only constant extra memory.
Example 1:
Input: nums = [1,2,3]
Output: [1,3,2]
Example 2:
Input: nums = [3,2,1]
Output: [1,2,3]
Example 3:
Input: nums = [1,1,5]
Output: [1,5,1]
"""
class Solution:
def next_permutation(self, nums: List[int]) -> None:
"""
Rearrange numbers into the lexicographically next greater permutation.
Modifies the array in-place.
Args:
nums: List of integers
"""
# Step 1: Find the first decreasing element from the right
i = len(nums) - 2
while i >= 0 and nums[i] >= nums[i + 1]:
i -= 1
if i >= 0:
# Step 2: Find the element just larger than nums[i]
j = len(nums) - 1
while nums[j] <= nums[i]:
j -= 1
# Step 3: Swap nums[i] and nums[j]
nums[i], nums[j] = nums[j], nums[i]
# Step 4: Reverse the subarray starting at i+1
left, right = i + 1, len(nums) - 1
while left < right:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right -= 1
def next_permutation_alternate(self, nums: List[int]) -> None:
"""
Alternative implementation with more descriptive variable names.
Args:
nums: List of integers
"""
n = len(nums)
# Find the first pair of adjacent elements where the left is less than the right
pivot = n - 2
while pivot >= 0 and nums[pivot] >= nums[pivot + 1]:
pivot -= 1
# If no such pair is found, the array is in descending order
# Reverse the entire array to get the lowest permutation
if pivot < 0:
nums.reverse()
return
# Find the rightmost element greater than the pivot
swap_index = n - 1
while nums[swap_index] <= nums[pivot]:
swap_index -= 1
# Swap the pivot with the found element
nums[pivot], nums[swap_index] = nums[swap_index], nums[pivot]
# Reverse the subarray to the right of the pivot
left, right = pivot + 1, n - 1
while left < right:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right -= 1
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
nums1 = [1, 2, 3]
solution.next_permutation(nums1)
print(f"Example 1: {nums1}") # Expected output: [1, 3, 2]
# Example 2
nums2 = [3, 2, 1]
solution.next_permutation(nums2)
print(f"Example 2: {nums2}") # Expected output: [1, 2, 3]
# Example 3
nums3 = [1, 1, 5]
solution.next_permutation(nums3)
print(f"Example 3: {nums3}") # Expected output: [1, 5, 1]
# Additional example
nums4 = [1, 3, 2]
solution.next_permutation(nums4)
print(f"Example 4: {nums4}") # Expected output: [2, 1, 3]
</pre>
</div>
</div>
</div>
<script>
const originalNums = [1, 3, 5, 4, 2];
let nums = [...originalNums];
let phase = 'find_i';
let i, j;
let left, right;
const width = 800, height = 400;
const svg = d3.select("#mainSvg");
let autoTimer = null;
let autoRunning = false;
function draw() {
svg.selectAll("*").remove();
const cellWidth = 70, startX = 150, startY = 100;
// Title
svg.append("text")
.attr("x", width / 2).attr("y", 30)
.attr("text-anchor", "middle")
.attr("font-weight", "bold")
.text(`Finding Next Permutation of [${originalNums.join(", ")}]`);
// Draw array
nums.forEach((num, idx) => {
const x = startX + idx * cellWidth;
let fill = "#e3f2fd", stroke = "#1976d2";
if (phase === 'find_i' && idx === i) {
fill = "#fff3e0"; stroke = "#ff9800";
} else if (phase === 'find_j') {
if (idx === i) { fill = "#fff3e0"; stroke = "#ff9800"; }
if (idx === j) { fill = "#e8f5e9"; stroke = "#4caf50"; }
} else if (phase === 'swap' || phase === 'swapped') {
if (idx === i || idx === j) {
fill = "#fce4ec"; stroke = "#e91e63";
}
} else if (phase === 'reverse') {
if (idx === left || idx === right) {
fill = "#e1f5fe"; stroke = "#03a9f4";
} else if (idx > i && idx < left) {
fill = "#e0e0e0";
} else if (idx > right && idx < nums.length) {
fill = "#e0e0e0";
}
}
svg.append("rect")
.attr("x", x).attr("y", startY)
.attr("width", cellWidth - 5).attr("height", 55)
.attr("rx", 8)
.attr("fill", fill).attr("stroke", stroke)
.attr("stroke-width", 2);
svg.append("text")
.attr("x", x + (cellWidth - 5) / 2)
.attr("y", startY + 35)
.attr("text-anchor", "middle")
.attr("font-size", "24px")
.attr("font-weight", "bold")
.text(num);
svg.append("text")
.attr("x", x + (cellWidth - 5) / 2)
.attr("y", startY + 70)
.attr("text-anchor", "middle")
.attr("font-size", "11px")
.attr("fill", "#666")
.text(`[${idx}]`);
});
// Pointers
if (i !== undefined && i >= 0 && phase !== 'done') {
svg.append("text")
.attr("x", startX + i * cellWidth + (cellWidth - 5) / 2)
.attr("y", startY - 15)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("fill", "#ff9800")
.text("▼ i");
}
if (j !== undefined && phase === 'find_j') {
svg.append("text")
.attr("x", startX + j * cellWidth + (cellWidth - 5) / 2)
.attr("y", startY - 15)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("fill", "#4caf50")
.text("▼ j");
}
if (phase === 'reverse' && left !== undefined && right !== undefined) {
svg.append("text")
.attr("x", startX + left * cellWidth + (cellWidth - 5) / 2)
.attr("y", startY - 15)
.attr("text-anchor", "middle")
.attr("font-size", "11px")
.attr("fill", "#03a9f4")
.text("L");
svg.append("text")
.attr("x", startX + right * cellWidth + (cellWidth - 5) / 2)
.attr("y", startY - 15)
.attr("text-anchor", "middle")
.attr("font-size", "11px")
.attr("fill", "#03a9f4")
.text("R");
}
// Algorithm steps
const stepsY = 220;
const steps = [
{ text: "1. Find first decreasing from right (i)", active: phase === 'find_i' },
{ text: "2. Find element just larger than nums[i] (j)", active: phase === 'find_j' },
{ text: "3. Swap nums[i] and nums[j]", active: phase === 'swap' || phase === 'swapped' },
{ text: "4. Reverse suffix after i", active: phase === 'reverse' }
];
steps.forEach((step, idx) => {
svg.append("rect")
.attr("x", 100).attr("y", stepsY + idx * 35)
.attr("width", 320).attr("height", 28)
.attr("rx", 5)
.attr("fill", step.active ? "#e8f5e9" : "#f5f5f5")
.attr("stroke", step.active ? "#4caf50" : "#ddd");
svg.append("text")
.attr("x", 110).attr("y", stepsY + idx * 35 + 19)
.attr("font-size", "13px")
.attr("fill", step.active ? "#2e7d32" : "#666")
.text(step.text);
});
// Result
if (phase === 'done') {
svg.append("rect")
.attr("x", 450).attr("y", stepsY + 40)
.attr("width", 280).attr("height", 60)
.attr("rx", 10)
.attr("fill", "#d1fae5").attr("stroke", "#10b981")
.attr("stroke-width", 2);
svg.append("text")
.attr("x", 590).attr("y", stepsY + 65)
.attr("text-anchor", "middle")
.attr("font-size", "14px")
.text("Next Permutation:");
svg.append("text")
.attr("x", 590).attr("y", stepsY + 90)
.attr("text-anchor", "middle")
.attr("font-size", "20px")
.attr("font-weight", "bold")
.attr("fill", "#10b981")
.text(`[${nums.join(", ")}]`);
}
}
function step() {
if (phase === 'done') return false;
if (phase === 'find_i') {
if (i === undefined) i = nums.length - 2;
if (i >= 0 && nums[i] >= nums[i + 1]) {
document.getElementById("status").textContent =
`nums[${i}]=${nums[i]} >= nums[${i+1}]=${nums[i+1]}, continue searching...`;
i--;
} else if (i >= 0) {
document.getElementById("status").textContent =
`Found i=${i} where nums[${i}]=${nums[i]} < nums[${i+1}]=${nums[i+1]}`;
phase = 'find_j';
j = nums.length - 1;
} else {
document.getElementById("status").textContent =
"Array is in descending order, will reverse entire array";
phase = 'reverse';
left = 0;
right = nums.length - 1;
}
} else if (phase === 'find_j') {
if (nums[j] <= nums[i]) {
document.getElementById("status").textContent =
`nums[${j}]=${nums[j]} <= nums[${i}]=${nums[i]}, continue...`;
j--;
} else {
document.getElementById("status").textContent =
`Found j=${j} where nums[${j}]=${nums[j]} > nums[${i}]=${nums[i]}`;
phase = 'swap';
}
} else if (phase === 'swap') {
[nums[i], nums[j]] = [nums[j], nums[i]];
document.getElementById("status").textContent =
`Swapped nums[${i}] and nums[${j}]. Array: [${nums.join(", ")}]`;
phase = 'swapped';
} else if (phase === 'swapped') {
phase = 'reverse';
left = i + 1;
right = nums.length - 1;
document.getElementById("status").textContent =
`Now reversing suffix from index ${left} to ${right}`;
} else if (phase === 'reverse') {
if (left < right) {
[nums[left], nums[right]] = [nums[right], nums[left]];
document.getElementById("status").textContent =
`Swapped positions ${left} and ${right}`;
left++;
right--;
} else {
phase = 'done';
document.getElementById("status").textContent =
`Done! Next permutation: [${nums.join(", ")}]`;
}
}
draw();
return phase !== 'done';
}
function reset() {
nums = [...originalNums];
phase = 'find_i';
i = undefined;
j = undefined;
left = undefined;
right = undefined;
if (autoTimer) clearInterval(autoTimer);
autoRunning = false;
document.getElementById("autoBtn").textContent = "Auto Run";
document.getElementById("status").textContent = 'Click "Step" to find next permutation';
draw();
}
function autoRun() {
if (autoRunning) {
clearInterval(autoTimer);
autoRunning = false;
document.getElementById("autoBtn").textContent = "Auto Run";
} else {
autoRunning = true;
document.getElementById("autoBtn").textContent = "Pause";
autoTimer = setInterval(() => {
if (!step()) {
clearInterval(autoTimer);
autoRunning = false;
document.getElementById("autoBtn").textContent = "Auto Run";
}
}, 800);
}
}
document.getElementById("stepBtn").addEventListener("click", step);
document.getElementById("autoBtn").addEventListener("click", autoRun);
document.getElementById("resetBtn").addEventListener("click", reset);
reset();
</script>
</body>
</html>