-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0153_min_rotated_sorted.html
More file actions
389 lines (335 loc) · 14.9 KB
/
0153_min_rotated_sorted.html
File metadata and controls
389 lines (335 loc) · 14.9 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Find Minimum in Rotated Sorted Array - LeetCode 153</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">#153</span> Find Minimum in Rotated Sorted Array</h1>
<p>Find the minimum element in a rotated sorted array. Use binary search to find the "pivot" point where the rotation occurred!</p>
<div class="problem-meta">
<span class="meta-tag">🔍 Binary Search</span>
<span class="meta-tag">🔢 Array</span>
<span class="meta-tag">⏱️ O(log n)</span>
</div>
<div class="file-ref">
📄 Python: <a href="../python/0153_minimum_in_rotated_sorted_array/0153_minimum_in_rotated_sorted_array.py">0153_minimum_in_rotated_sorted_array.py</a>
</div>
</div>
<div class="explanation-panel">
<h4>💡 How It Works (Layman's Terms)</h4>
<ul>
<li><strong>Rotated array:</strong> A sorted array that's been "rotated" - part of the end moved to the beginning</li>
<li><strong>Example:</strong> [1,2,3,4,5] rotated 3 times → [3,4,5,1,2]</li>
<li><strong>Key insight:</strong> The array has two sorted portions. The minimum is at the "pivot" point.</li>
<li><strong>If nums[left] < nums[right]:</strong> The current range is fully sorted, min is at left</li>
<li><strong>If nums[left] <= nums[mid]:</strong> Left half is sorted, so min must be in right half</li>
<li><strong>Otherwise:</strong> Right half is sorted, so min must be in left half</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 find the minimum in the rotated array
</div>
<div class="variable-display">
<div class="variable-box">
<div class="variable-name">Left</div>
<div class="variable-value" id="leftVal">0</div>
</div>
<div class="variable-box">
<div class="variable-name">Mid</div>
<div class="variable-value" id="midVal">-</div>
</div>
<div class="variable-box">
<div class="variable-name">Right</div>
<div class="variable-value" id="rightVal">4</div>
</div>
<div class="variable-box">
<div class="variable-name">Current Min</div>
<div class="variable-value" id="minVal">-</div>
</div>
</div>
<div class="array-section">
<div class="array-label">Rotated Array (original: [1,2,3,4,5] rotated 3 times):</div>
<div class="array-container" id="arrayContainer"></div>
</div>
<div class="svg-container">
<svg id="chartSvg" width="600" height="200"></svg>
</div>
<div class="info-box" id="resultBox" style="display: none;"></div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List, Optional
"""
LeetCode 153. Find Minimum in Rotated Sorted Array
Problem from LeetCode: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/
Description:
Suppose an array of length n sorted in ascending order is rotated between 1 and n times.
For example, the array nums = [0,1,2,4,5,6,7] might become:
- [4,5,6,7,0,1,2] if it was rotated 4 times.
- [0,1,2,4,5,6,7] if it was rotated 7 times.
Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results
in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].
Given the sorted rotated array nums of unique elements, return the minimum element of this array.
You must write an algorithm that runs in O(log n) time.
Example 1:
Input: nums = [3,4,5,1,2]
Output: 1
Explanation: The original array was [1,2,3,4,5] rotated 3 times.
Example 2:
Input: nums = [4,5,6,7,0,1,2]
Output: 0
Explanation: The original array was [0,1,2,4,5,6,7] and it was rotated 4 times.
Example 3:
Input: nums = [11,13,15,17]
Output: 11
Explanation: The original array was [11,13,15,17] and it was rotated 4 times.
Constraints:
- n == nums.length
- 1 <= n <= 5000
- -5000 <= nums[i] <= 5000
- All the integers of nums are unique.
- nums is sorted and rotated between 1 and n times.
"""
class Solution:
def find_min(self, nums: list[int]) ->int:
left = 0
right = len(nums) - 1
ans = nums[0]
if len(nums) == 1:
return nums[0]
while left <= right:
if nums[left] < nums[right]:
ans = min(ans, nums[left])
mid = (left + right) // 2
ans = min(ans, nums[mid])
if nums[left] <= nums[mid]:
left = mid + 1
else:
right = mid - 1
return ans
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
nums1 = [3,4,5,1,2]
result1 = solution.find_min(nums1)
print(f"Input: nums = {nums1}")
print(f"Output: {result1}") # Expected output: 1
# Example 2
nums2 = [4,5,6,7,0,1,2]
result2 = solution.find_min(nums2)
print(f"Input: nums = {nums2}")
print(f"Output: {result2}") # Expected output: 0
# Example 3
nums3 = [11,13,15,17]
result3 = solution.find_min(nums3)
print(f"Input: nums = {nums3}")
print(f"Output: {result3}") # Expected output: 11
</pre>
</div>
</div>
</div>
<script>
const nums = [3, 4, 5, 1, 2];
let left = 0;
let right = nums.length - 1;
let mid = -1;
let result = nums[0];
let phase = 'init';
let autoInterval = null;
function init() {
left = 0;
right = nums.length - 1;
mid = -1;
result = nums[0];
renderArray();
drawChart();
document.getElementById('leftVal').textContent = '0';
document.getElementById('rightVal').textContent = (nums.length - 1).toString();
document.getElementById('midVal').textContent = '-';
document.getElementById('minVal').textContent = nums[0];
document.getElementById('resultBox').style.display = 'none';
}
function renderArray() {
const container = document.getElementById('arrayContainer');
container.innerHTML = '';
nums.forEach((num, idx) => {
const box = document.createElement('div');
box.className = 'array-box';
if (idx === left) box.classList.add('pointer-left');
if (idx === right) box.classList.add('pointer-right');
if (idx === mid) box.classList.add('highlight');
if (idx < left || idx > right) box.style.opacity = '0.3';
box.innerHTML = `${num}<span class="index-label">[${idx}]</span>`;
container.appendChild(box);
});
// Pointer labels
const oldLabels = container.parentElement.querySelector('.pointer-labels');
if (oldLabels) oldLabels.remove();
let labelHtml = '<div class="pointer-labels" style="display: flex; gap: 8px; margin-top: 5px;">';
for (let i = 0; i < nums.length; i++) {
labelHtml += '<div style="width: 60px; text-align: center; font-size: 0.8em;">';
if (i === left) labelHtml += '<span style="color: #ff5722;">L</span>';
if (i === mid) labelHtml += '<span style="color: #667eea; margin: 0 3px;">M</span>';
if (i === right) labelHtml += '<span style="color: #3f51b5;">R</span>';
labelHtml += '</div>';
}
labelHtml += '</div>';
container.insertAdjacentHTML('afterend', labelHtml);
}
function drawChart() {
const svg = d3.select("#chartSvg");
svg.selectAll("*").remove();
const margin = {top: 20, right: 30, bottom: 30, left: 40};
const width = 600 - margin.left - margin.right;
const height = 200 - margin.top - margin.bottom;
const g = svg.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);
const x = d3.scaleLinear()
.domain([0, nums.length - 1])
.range([0, width]);
const y = d3.scaleLinear()
.domain([0, Math.max(...nums) + 1])
.range([height, 0]);
// Bars
g.selectAll("rect")
.data(nums)
.enter()
.append("rect")
.attr("x", (d, i) => x(i) - 20)
.attr("y", d => y(d))
.attr("width", 40)
.attr("height", d => height - y(d))
.attr("fill", (d, i) => {
if (i === mid) return "#667eea";
if (i < left || i > right) return "#e0e0e0";
return "#4caf50";
})
.attr("rx", 4);
// Value labels
g.selectAll(".label")
.data(nums)
.enter()
.append("text")
.attr("x", (d, i) => x(i))
.attr("y", d => y(d) - 5)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("font-weight", "bold")
.text(d => d);
// Highlight minimum
const minIdx = nums.indexOf(Math.min(...nums));
g.append("text")
.attr("x", x(minIdx))
.attr("y", height + 20)
.attr("text-anchor", "middle")
.attr("font-size", "10px")
.attr("fill", "#f44336")
.text("← Min");
}
function step() {
// Remove old pointer labels
const oldLabels = document.querySelector('.pointer-labels');
if (oldLabels) {
oldLabels.remove();
}
if (phase === 'init') {
phase = 'searching';
document.getElementById('statusMessage').textContent =
'Binary search for the minimum (pivot point)...';
}
if (phase === 'searching') {
if (left > right) {
phase = 'done';
document.getElementById('resultBox').style.display = 'block';
document.getElementById('resultBox').className = 'info-box secondary';
document.getElementById('resultBox').textContent = `✅ Minimum found: ${result}`;
document.getElementById('statusMessage').textContent = 'Search complete!';
document.getElementById('stepBtn').disabled = true;
stopAuto();
return;
}
// Check if already sorted
if (nums[left] < nums[right]) {
result = Math.min(result, nums[left]);
phase = 'done';
document.getElementById('minVal').textContent = result;
document.getElementById('resultBox').style.display = 'block';
document.getElementById('resultBox').className = 'info-box secondary';
document.getElementById('resultBox').textContent = `✅ Minimum found: ${result}`;
document.getElementById('statusMessage').textContent =
`nums[${left}] < nums[${right}] → Range is sorted, min = nums[${left}] = ${nums[left]}`;
document.getElementById('stepBtn').disabled = true;
stopAuto();
return;
}
mid = Math.floor((left + right) / 2);
result = Math.min(result, nums[mid]);
document.getElementById('midVal').textContent = mid;
document.getElementById('minVal').textContent = result;
document.getElementById('leftVal').textContent = left;
document.getElementById('rightVal').textContent = right;
renderArray();
drawChart();
if (nums[left] <= nums[mid]) {
document.getElementById('statusMessage').textContent =
`nums[${left}]=${nums[left]} ≤ nums[${mid}]=${nums[mid]} → Left half sorted, min in right half. left = ${mid + 1}`;
left = mid + 1;
} else {
document.getElementById('statusMessage').textContent =
`nums[${left}]=${nums[left]} > nums[${mid}]=${nums[mid]} → Right half sorted, min in left half. right = ${mid - 1}`;
right = mid - 1;
}
}
}
function toggleAuto() {
if (autoInterval) {
stopAuto();
} else {
document.getElementById('autoBtn').textContent = 'Pause';
autoInterval = setInterval(() => {
if (phase === 'done') {
stopAuto();
} else {
step();
}
}, 1500);
}
}
function stopAuto() {
if (autoInterval) {
clearInterval(autoInterval);
autoInterval = null;
}
document.getElementById('autoBtn').textContent = 'Auto Run';
}
function reset() {
stopAuto();
phase = 'init';
const oldLabels = document.querySelector('.pointer-labels');
if (oldLabels) {
oldLabels.remove();
}
document.getElementById('stepBtn').disabled = false;
document.getElementById('statusMessage').textContent =
'Click "Step" or "Auto Run" to find the minimum in the rotated array';
init();
}
init();
</script>
</body>
</html>