-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0217_contains_duplicate.html
More file actions
300 lines (252 loc) · 10.8 KB
/
Copy path0217_contains_duplicate.html
File metadata and controls
300 lines (252 loc) · 10.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LC 217: Contains Duplicate - 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">#217</span> Contains Duplicate</h1>
<p>Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.</p>
<div class="problem-meta">
<span class="meta-tag">📁 Array</span>
<span class="meta-tag">🔤 Hash Set</span>
<span class="meta-tag">⏱️ O(n)</span>
<span class="meta-tag">💾 O(n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0217_contains_duplicate/0217_contains_duplicate.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>Think of it like checking names at a party entrance:</p>
<ul>
<li>You have a guest list (empty set at first)</li>
<li>As each person arrives, you check: "Have I seen this person before?"</li>
<li>If <strong>YES</strong> → Duplicate found! Return true</li>
<li>If <strong>NO</strong> → Add their name to the list and continue</li>
<li>If everyone enters without a repeat → No duplicates, return false</li>
</ul>
<p>The <strong>set</strong> provides O(1) lookup, making this very efficient!</p>
</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 start visualization
</div>
<div class="array-section">
<div class="array-label">📥 Input Array:</div>
<div class="array-container" id="inputContainer"></div>
</div>
<div class="array-section">
<div class="array-label">👁️ Seen Set (Hash Set):</div>
<div class="array-container" id="seenContainer">
<div style="color: #999; padding: 10px;">{ empty }</div>
</div>
</div>
<div class="info-box" id="resultBox" style="display: none;">
Result will appear here
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List
"""
LeetCode 217: Contains Duplicate
Problem from LeetCode: https://leetcode.com/problems/contains-duplicate/
Given an integer array nums, return true if any value appears at least twice in the array,
and return false if every element is distinct.
Example 1:
Input: nums = [1,2,3,1]
Output: true
Example 2:
Input: nums = [1,2,3,4]
Output: false
Example 3:
Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true
Constraints:
- 1 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
"""
class Solution:
def contains_duplicate(self, nums: List[int]) ->bool:
"""
Determine if the array contains any duplicates.
Args:
nums: An array of integers
Returns:
bool: True if any value appears at least twice in the array, False otherwise
"""
seen = set()
for num in nums:
if num in seen:
return True
seen.add(num)
return False
def contains_duplicate_alternative(self, nums: List[int]) ->bool:
"""
Alternative implementation using set comparison.
Args:
nums: An array of integers
Returns:
bool: True if any value appears at least twice in the array, False otherwise
"""
return len(set(nums)) < len(nums)
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
nums = [1, 2, 3, 1]
result = solution.contains_duplicate(nums)
print(result) # Output: True
# Example 2
nums = [1, 2, 3, 4]
result = solution.contains_duplicate(nums)
print(result) # Output: False
# Example 3
nums = [1, 1, 1, 3, 3, 4, 3, 2, 4, 2]
result = solution.contains_duplicate(nums)
print(result) # Output: True
</pre>
</div>
</div>
</div>
<script>
const nums = [1, 2, 3, 1];
let seen = new Set();
let currentIndex = 0;
let foundDuplicate = false;
let autoInterval = null;
function init() {
renderInput();
renderSeen();
}
function renderInput() {
const container = document.getElementById('inputContainer');
container.innerHTML = '';
nums.forEach((num, idx) => {
const box = document.createElement('div');
box.className = 'array-box';
box.id = `input-${idx}`;
box.innerHTML = `${num}<span class="index-label">[${idx}]</span>`;
container.appendChild(box);
});
}
function renderSeen() {
const container = document.getElementById('seenContainer');
container.innerHTML = '';
if (seen.size === 0) {
container.innerHTML = '<div style="color: #999; padding: 10px;">{ empty }</div>';
return;
}
const setValues = Array.from(seen);
setValues.forEach(val => {
const box = document.createElement('div');
box.className = 'array-box';
box.id = `seen-${val}`;
box.style.background = '#e8f5e9';
box.style.borderColor = '#4caf50';
box.textContent = val;
container.appendChild(box);
});
}
function step() {
if (foundDuplicate || currentIndex >= nums.length) {
document.getElementById('stepBtn').disabled = true;
stopAuto();
return;
}
// Clear previous highlights
document.querySelectorAll('.array-box').forEach(box => {
box.classList.remove('highlight', 'current');
});
const currentNum = nums[currentIndex];
document.getElementById(`input-${currentIndex}`).classList.add('highlight');
if (seen.has(currentNum)) {
// Found duplicate!
foundDuplicate = true;
document.getElementById('statusMessage').className = 'status-message warning';
document.getElementById('statusMessage').textContent =
`🚨 Checking ${currentNum}: Already in set! DUPLICATE FOUND!`;
// Highlight the duplicate in the seen set
if (document.getElementById(`seen-${currentNum}`)) {
document.getElementById(`seen-${currentNum}`).classList.add('highlight');
document.getElementById(`seen-${currentNum}`).style.background = '#ffcdd2';
document.getElementById(`seen-${currentNum}`).style.borderColor = '#f44336';
}
document.getElementById(`input-${currentIndex}`).style.background = '#ffcdd2';
document.getElementById(`input-${currentIndex}`).style.borderColor = '#f44336';
const resultBox = document.getElementById('resultBox');
resultBox.style.display = 'block';
resultBox.className = 'info-box highlight';
resultBox.textContent = '✅ Return TRUE - Duplicate exists!';
document.getElementById('stepBtn').disabled = true;
stopAuto();
} else {
// Add to set
seen.add(currentNum);
document.getElementById('statusMessage').textContent =
`Checking ${currentNum}: Not in set → Adding to seen set`;
renderSeen();
currentIndex++;
if (currentIndex >= nums.length && !foundDuplicate) {
document.getElementById('statusMessage').className = 'status-message success';
document.getElementById('statusMessage').textContent =
'✅ Checked all elements. No duplicates found!';
const resultBox = document.getElementById('resultBox');
resultBox.style.display = 'block';
resultBox.className = 'info-box secondary';
resultBox.textContent = '❌ Return FALSE - All elements are unique!';
document.getElementById('stepBtn').disabled = true;
stopAuto();
}
}
}
function toggleAuto() {
if (autoInterval) {
stopAuto();
} else {
document.getElementById('autoBtn').textContent = 'Pause';
autoInterval = setInterval(() => {
if (foundDuplicate || currentIndex >= nums.length) {
stopAuto();
} else {
step();
}
}, 1000);
}
}
function stopAuto() {
if (autoInterval) {
clearInterval(autoInterval);
autoInterval = null;
}
document.getElementById('autoBtn').textContent = 'Auto Run';
}
function reset() {
stopAuto();
currentIndex = 0;
seen = new Set();
foundDuplicate = 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('resultBox').style.display = 'none';
init();
}
init();
</script>
</body>
</html>