-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0704_binary_search.html
More file actions
362 lines (307 loc) · 13.2 KB
/
0704_binary_search.html
File metadata and controls
362 lines (307 loc) · 13.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LC 704: Binary Search - 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">#704</span> Binary Search</h1>
<p>Given a sorted array of integers and a target, return the index of the target if found, otherwise return -1. Must run in O(log n) time.</p>
<div class="problem-meta">
<span class="meta-tag">📁 Array</span>
<span class="meta-tag">🔍 Binary Search</span>
<span class="meta-tag">⏱️ O(log n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0704_binary_search/0704_binary_search.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>Imagine looking for a word in a dictionary - you don't start from page 1:</p>
<ul>
<li><strong>Open to middle:</strong> Check if target is before or after the middle</li>
<li><strong>Too small:</strong> Target is in the right half → ignore left half</li>
<li><strong>Too big:</strong> Target is in the left half → ignore right half</li>
<li><strong>Found:</strong> Middle equals target → return index</li>
<li><strong>Each step halves the search space → O(log n)!</strong></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="info-box secondary" style="margin-bottom: 20px;">
🎯 Target: <strong id="targetDisplay">9</strong>
</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">Left</div>
<div class="variable-value" id="leftVal" style="color: #ff5722;">0</div>
</div>
<div class="variable-box">
<div class="variable-name">Right</div>
<div class="variable-value" id="rightVal" style="color: #3f51b5;">5</div>
</div>
<div class="variable-box">
<div class="variable-name">Mid</div>
<div class="variable-value" id="midVal" style="color: #4caf50;">-</div>
</div>
<div class="variable-box">
<div class="variable-name">nums[mid]</div>
<div class="variable-value" id="midNumVal">-</div>
</div>
</div>
<div class="array-section">
<div class="array-label">📥 Sorted Array:</div>
<div class="array-container" id="arrayContainer"></div>
</div>
<div class="info-box" id="resultBox" style="display: none; margin-top: 20px;">
Result will appear here
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List
"""
LeetCode Binary Search
Problem from LeetCode: https://leetcode.com/problems/binary-search/
Description:
Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4
Example 2:
Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1
Constraints:
1 <= nums.length <= 10^4
-10^4 <= nums[i], target <= 10^4
All the integers in nums are unique.
nums is sorted in ascending order.
"""
class Solution:
def search(self, nums: List[int], target: int) ->int:
"""
Binary search implementation to find target in a sorted array.
Args:
nums: A sorted array of distinct integers
target: The target value to search for
Returns:
int: The index of target if found, otherwise -1
"""
left, right = 0, len(nums) - 1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
def search_recursive(self, nums: List[int], target: int) ->int:
"""
Recursive binary search implementation.
Args:
nums: A sorted array of distinct integers
target: The target value to search for
Returns:
int: The index of target if found, otherwise -1
"""
def binary_search(left, right):
if left > right:
return -1
mid = left + (right - left) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
return binary_search(mid + 1, right)
else:
return binary_search(left, mid - 1)
return binary_search(0, len(nums) - 1)
def search_bisect(self, nums: List[int], target: int) ->int:
"""
Binary search using Python's bisect module.
Args:
nums: A sorted array of distinct integers
target: The target value to search for
Returns:
int: The index of target if found, otherwise -1
"""
import bisect
index = bisect.bisect_left(nums, target)
if index < len(nums) and nums[index] == target:
return index
else:
return -1
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
nums1 = [-1, 0, 3, 5, 9, 12]
target1 = 9
result1 = solution.search(nums1, target1)
print(f"Example 1: {result1}") # Expected: 4
# Example 2
nums2 = [-1, 0, 3, 5, 9, 12]
target2 = 2
result2 = solution.search(nums2, target2)
print(f"Example 2: {result2}") # Expected: -1
# Test recursive method
print("\nRecursive method:")
result3 = solution.search_recursive(nums1, target1)
print(f"Example 1: {result3}") # Expected: 4
# Test bisect method
print("\nBisect method:")
result4 = solution.search_bisect(nums1, target1)
print(f"Example 1: {result4}") # Expected: 4
</pre>
</div>
</div>
</div>
<script>
const nums = [-1, 0, 3, 5, 9, 12];
const target = 9;
let left = 0;
let right = nums.length - 1;
let mid = -1;
let found = false;
let autoInterval = null;
document.getElementById('targetDisplay').textContent = target;
function init() {
renderArray();
}
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>`;
// Gray out elements outside current range
if (idx < left || idx > right) {
box.style.background = '#e0e0e0';
box.style.opacity = '0.5';
}
// Highlight mid
if (idx === mid) {
box.style.background = '#c8e6c9';
box.style.borderColor = '#4caf50';
box.style.borderWidth = '3px';
}
// Left pointer
if (idx === left && idx !== mid) {
box.style.borderColor = '#ff5722';
box.style.borderWidth = '3px';
}
// Right pointer
if (idx === right && idx !== mid) {
box.style.borderColor = '#3f51b5';
box.style.borderWidth = '3px';
}
// Found!
if (found && idx === mid) {
box.classList.add('complete');
}
container.appendChild(box);
});
}
function step() {
if (found || left > right) {
if (found) {
document.getElementById('statusMessage').className = 'status-message success';
document.getElementById('statusMessage').textContent = `✅ Found ${target} at index ${mid}!`;
document.getElementById('resultBox').style.display = 'block';
document.getElementById('resultBox').className = 'info-box secondary';
document.getElementById('resultBox').textContent = `Return ${mid}`;
} else {
document.getElementById('statusMessage').className = 'status-message warning';
document.getElementById('statusMessage').textContent = `❌ ${target} not found in array!`;
document.getElementById('resultBox').style.display = 'block';
document.getElementById('resultBox').className = 'info-box highlight';
document.getElementById('resultBox').textContent = 'Return -1';
}
document.getElementById('stepBtn').disabled = true;
stopAuto();
return;
}
// Calculate mid
mid = left + Math.floor((right - left) / 2);
document.getElementById('leftVal').textContent = left;
document.getElementById('rightVal').textContent = right;
document.getElementById('midVal').textContent = mid;
document.getElementById('midNumVal').textContent = nums[mid];
if (nums[mid] === target) {
found = true;
document.getElementById('statusMessage').textContent =
`mid = ${mid}, nums[${mid}] = ${nums[mid]} = target. FOUND!`;
} else if (nums[mid] < target) {
document.getElementById('statusMessage').textContent =
`mid = ${mid}, nums[${mid}] = ${nums[mid]} < ${target}. Search right half (left = ${mid + 1})`;
left = mid + 1;
} else {
document.getElementById('statusMessage').textContent =
`mid = ${mid}, nums[${mid}] = ${nums[mid]} > ${target}. Search left half (right = ${mid - 1})`;
right = mid - 1;
}
renderArray();
}
function toggleAuto() {
if (autoInterval) {
stopAuto();
} else {
document.getElementById('autoBtn').textContent = 'Pause';
autoInterval = setInterval(() => {
if (found || left > right) {
step();
stopAuto();
} else {
step();
}
}, 1200);
}
}
function stopAuto() {
if (autoInterval) {
clearInterval(autoInterval);
autoInterval = null;
}
document.getElementById('autoBtn').textContent = 'Auto Run';
}
function reset() {
stopAuto();
left = 0;
right = nums.length - 1;
mid = -1;
found = false;
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('leftVal').textContent = '0';
document.getElementById('rightVal').textContent = nums.length - 1;
document.getElementById('midVal').textContent = '-';
document.getElementById('midNumVal').textContent = '-';
document.getElementById('resultBox').style.display = 'none';
init();
}
init();
</script>
</body>
</html>