-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0167_two_sum_ii.html
More file actions
294 lines (256 loc) · 11.5 KB
/
0167_two_sum_ii.html
File metadata and controls
294 lines (256 loc) · 11.5 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Two Sum II - LeetCode 167</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">#167</span> Two Sum II - Input Array Is Sorted</h1>
<p>Given a sorted array and a target, find two numbers that add up to the target. Return their 1-indexed positions. The two-pointer technique makes this elegant!</p>
<div class="problem-meta">
<span class="meta-tag">👉👉 Two Pointers</span>
<span class="meta-tag">📊 Sorted Array</span>
<span class="meta-tag">⏱️ O(n)</span>
<span class="meta-tag">💾 O(1)</span>
</div>
<div class="file-ref">
📄 Python: <a href="../python/0167_two_sum_2/0167_two_sum_2.py">0167_two_sum_2.py</a>
</div>
</div>
<div class="explanation-panel">
<h4>💡 How It Works (Layman's Terms)</h4>
<ul>
<li><strong>Key Insight:</strong> The array is SORTED! This changes everything.</li>
<li><strong>Two Pointers:</strong> Start with one pointer at the beginning (smallest) and one at the end (largest)</li>
<li><strong>Sum too big?</strong> Move the right pointer left to get a smaller number</li>
<li><strong>Sum too small?</strong> Move the left pointer right to get a bigger number</li>
<li><strong>Why it works:</strong> Because it's sorted, moving left makes sum smaller, moving right makes it bigger</li>
<li><strong>Result:</strong> 1-indexed positions (add 1 to 0-indexed positions)</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" id="targetBox">
Target Sum = 9
</div>
<div class="status-message" id="statusMessage">
Click "Step" or "Auto Run" to find two numbers that sum to target
</div>
<div class="variable-display">
<div class="variable-box">
<div class="variable-name">Left Pointer</div>
<div class="variable-value" id="leftVal">0</div>
</div>
<div class="variable-box">
<div class="variable-name">Right Pointer</div>
<div class="variable-value" id="rightVal">3</div>
</div>
<div class="variable-box">
<div class="variable-name">Current Sum</div>
<div class="variable-value" id="sumVal">-</div>
</div>
</div>
<div class="array-section">
<div class="array-label">Sorted Array (numbers):</div>
<div class="array-container" id="arrayContainer"></div>
</div>
<div id="pointerContainer" style="margin-top: 10px;">
<!-- Pointer indicators will be drawn here -->
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List, Optional
"""
LeetCode Two Sum II - Input Array Is Sorted
Problem from LeetCode: https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
Description:
Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number.
Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2.
The tests are generated such that there is exactly one solution. You may not use the same element twice.
Your solution must use only constant extra space.
Example 1:
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2].
Example 2:
Input: numbers = [2,3,4], target = 6
Output: [1,3]
Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3].
Example 3:
Input: numbers = [-1,0], target = -1
Output: [1,2]
Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2].
"""
class Solution:
def two_sum(self, numbers: list[int], target: int) ->list[int]:
left = 0
right = len(numbers) - 1
while left < right:
current_sum = numbers[left] + numbers[right]
if current_sum > target:
right -= 1
elif current_sum < target:
left += 1
else:
return [left + 1, right + 1]
return None
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
numbers1 = [2, 7, 11, 15]
target1 = 9
result1 = solution.two_sum(numbers1, target1)
print(f"Example 1: {result1}") # Expected output: [1, 2]
# Example 2
numbers2 = [2, 3, 4]
target2 = 6
result2 = solution.two_sum(numbers2, target2)
print(f"Example 2: {result2}") # Expected output: [1, 3]
# Example 3
numbers3 = [-1, 0]
target3 = -1
result3 = solution.two_sum(numbers3, target3)
print(f"Example 3: {result3}") # Expected output: [1, 2]
</pre>
</div>
</div>
</div>
<script>
const numbers = [2, 7, 11, 15];
const target = 9;
let left = 0;
let right = numbers.length - 1;
let phase = 'init';
let autoInterval = null;
function init() {
renderArray();
document.getElementById('leftVal').textContent = '0';
document.getElementById('rightVal').textContent = (numbers.length - 1).toString();
document.getElementById('sumVal').textContent = '-';
}
function renderArray() {
const container = document.getElementById('arrayContainer');
container.innerHTML = '';
numbers.forEach((num, idx) => {
const box = document.createElement('div');
box.className = 'array-box';
box.id = `num-${idx}`;
box.innerHTML = `${num}<span class="index-label">[${idx}]</span>`;
container.appendChild(box);
});
updatePointers();
}
function updatePointers() {
document.querySelectorAll('.array-box').forEach(b => {
b.classList.remove('pointer-left', 'pointer-right', 'complete');
});
if (left < numbers.length) {
document.getElementById(`num-${left}`).classList.add('pointer-left');
}
if (right >= 0) {
document.getElementById(`num-${right}`).classList.add('pointer-right');
}
// Draw pointer indicators
const pointerContainer = document.getElementById('pointerContainer');
const arrayContainer = document.getElementById('arrayContainer');
const boxes = arrayContainer.getElementsByClassName('array-box');
let html = '<div style="display: flex; gap: 8px; padding-left: 0;">';
for (let i = 0; i < numbers.length; i++) {
html += '<div style="width: 60px; text-align: center;">';
if (i === left) {
html += '<span style="color: #ff5722; font-weight: bold;">↑ L</span>';
} else if (i === right) {
html += '<span style="color: #3f51b5; font-weight: bold;">↑ R</span>';
}
html += '</div>';
}
html += '</div>';
pointerContainer.innerHTML = html;
}
function step() {
if (phase === 'init') {
phase = 'searching';
document.getElementById('statusMessage').textContent =
'Starting two-pointer search: left at smallest, right at largest';
}
if (phase === 'searching') {
if (left >= right) {
phase = 'done';
document.getElementById('statusMessage').textContent = 'No solution found (pointers crossed)';
document.getElementById('stepBtn').disabled = true;
stopAuto();
return;
}
const sum = numbers[left] + numbers[right];
document.getElementById('sumVal').textContent = sum.toString();
document.getElementById('leftVal').textContent = left.toString();
document.getElementById('rightVal').textContent = right.toString();
if (sum === target) {
phase = 'done';
document.getElementById(`num-${left}`).classList.add('complete');
document.getElementById(`num-${right}`).classList.add('complete');
document.getElementById('statusMessage').textContent =
`✅ Found! numbers[${left}] + numbers[${right}] = ${numbers[left]} + ${numbers[right]} = ${target}. Answer: [${left + 1}, ${right + 1}] (1-indexed)`;
document.getElementById('stepBtn').disabled = true;
stopAuto();
} else if (sum > target) {
document.getElementById('statusMessage').textContent =
`Sum ${sum} > target ${target} → Move RIGHT pointer left to get smaller number`;
right--;
updatePointers();
} else {
document.getElementById('statusMessage').textContent =
`Sum ${sum} < target ${target} → Move LEFT pointer right to get bigger number`;
left++;
updatePointers();
}
}
}
function toggleAuto() {
if (autoInterval) {
stopAuto();
} else {
document.getElementById('autoBtn').textContent = 'Pause';
autoInterval = setInterval(() => {
if (phase === 'done') {
stopAuto();
} else {
step();
}
}, 1200);
}
}
function stopAuto() {
if (autoInterval) {
clearInterval(autoInterval);
autoInterval = null;
}
document.getElementById('autoBtn').textContent = 'Auto Run';
}
function reset() {
stopAuto();
phase = 'init';
left = 0;
right = numbers.length - 1;
document.getElementById('stepBtn').disabled = false;
document.getElementById('statusMessage').textContent =
'Click "Step" or "Auto Run" to find two numbers that sum to target';
init();
}
init();
</script>
</body>
</html>