-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0412_fizz_buzz.html
More file actions
298 lines (252 loc) · 11.3 KB
/
0412_fizz_buzz.html
File metadata and controls
298 lines (252 loc) · 11.3 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LC 412: Fizz Buzz - 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">#412</span> Fizz Buzz</h1>
<p>Given an integer n, return a string array where: "FizzBuzz" if i divisible by 3 and 5, "Fizz" if divisible by 3, "Buzz" if divisible by 5, else the number.</p>
<div class="problem-meta">
<span class="meta-tag">🔢 Math</span>
<span class="meta-tag">📝 String</span>
<span class="meta-tag">⏱️ O(n)</span>
<span class="meta-tag">💾 O(n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0412_fizz_buzz/0412_fizz_buzz.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<ul>
<li><strong>Divisibility:</strong> Check if number is divisible by 3, 5, or both</li>
<li><strong>Priority:</strong> Check 15 (FizzBuzz) first, then 3 (Fizz), then 5 (Buzz)</li>
<li><strong>Default:</strong> If not divisible by 3 or 5, use the number itself</li>
</ul>
</div>
<div class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<label>n = </label>
<input type="range" id="nSlider" min="1" max="100" value="30" oninput="updateN()">
<span id="nValue">30</span>
<button class="btn btn-primary" id="startBtn" onclick="start()">▶ Start</button>
<button class="btn btn-warning" onclick="reset()">Reset</button>
</div>
<div class="status-message" id="statusMessage">
Click Start to generate FizzBuzz sequence
</div>
<div style="margin-top: 20px;">
<div id="gridDisplay" style="display: grid; grid-template-columns: repeat(10, 1fr); gap: 5px; padding: 15px; background: #f5f5f5; border-radius: 12px;"></div>
</div>
<div style="display: flex; gap: 20px; margin-top: 20px; flex-wrap: wrap;">
<div style="flex: 1; padding: 15px; background: #e8f5e9; border-radius: 12px; text-align: center;">
<div style="font-size: 2em; font-weight: bold; color: #4caf50;" id="fizzCount">0</div>
<div>Fizz (÷3)</div>
</div>
<div style="flex: 1; padding: 15px; background: #e3f2fd; border-radius: 12px; text-align: center;">
<div style="font-size: 2em; font-weight: bold; color: #2196f3;" id="buzzCount">0</div>
<div>Buzz (÷5)</div>
</div>
<div style="flex: 1; padding: 15px; background: #fce4ec; border-radius: 12px; text-align: center;">
<div style="font-size: 2em; font-weight: bold; color: #e91e63;" id="fizzBuzzCount">0</div>
<div>FizzBuzz (÷15)</div>
</div>
<div style="flex: 1; padding: 15px; background: #fff3e0; border-radius: 12px; text-align: center;">
<div style="font-size: 2em; font-weight: bold; color: #ff9800;" id="numberCount">0</div>
<div>Numbers</div>
</div>
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List
"""
LeetCode Fizz Buzz
Problem from LeetCode: https://leetcode.com/problems/fizz-buzz/
Given an integer n, return a string array answer (1-indexed) where:
- answer[i] == "FizzBuzz" if i is divisible by 3 and 5.
- answer[i] == "Fizz" if i is divisible by 3.
- answer[i] == "Buzz" if i is divisible by 5.
- answer[i] == i (as a string) if none of the above conditions are true.
Example 1:
Input: n = 3
Output: ["1","2","Fizz"]
Example 2:
Input: n = 5
Output: ["1","2","Fizz","4","Buzz"]
Example 3:
Input: n = 15
Output: ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]
Constraints:
1 <= n <= 10^4
"""
class Solution:
def fizz_buzz(self, n: int) ->List[str]:
"""
Return the string representation of numbers from 1 to n.
For multiples of 3, return "Fizz" instead of the number.
For multiples of 5, return "Buzz" instead of the number.
For multiples of both 3 and 5, return "FizzBuzz".
Args:
n: Upper limit
Returns:
List[str]: String representations from 1 to n following the FizzBuzz rules
"""
result = []
for i in range(1, n + 1):
if i % 3 == 0 and i % 5 == 0:
result.append('FizzBuzz')
elif i % 3 == 0:
result.append('Fizz')
elif i % 5 == 0:
result.append('Buzz')
else:
result.append(str(i))
return result
def fizz_buzz_concatenation(self, n: int) ->List[str]:
"""
Alternative implementation using string concatenation.
This is more extensible if more divisors need to be added.
Args:
n: Upper limit
Returns:
List[str]: String representations from 1 to n following the FizzBuzz rules
"""
result = []
for i in range(1, n + 1):
answer = ''
if i % 3 == 0:
answer += 'Fizz'
if i % 5 == 0:
answer += 'Buzz'
if not answer:
answer = str(i)
result.append(answer)
return result
def fizz_buzz_comprehension(self, n: int) ->List[str]:
"""
Pythonic implementation using list comprehension.
Args:
n: Upper limit
Returns:
List[str]: String representations from 1 to n following the FizzBuzz rules
"""
return [('FizzBuzz' if i % 15 == 0 else 'Fizz' if i % 3 == 0 else
'Buzz' if i % 5 == 0 else str(i)) for i in range(1, n + 1)]
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1: n = 3
print("Example 1:")
result = solution.fizz_buzz(3)
print(f"Output: {result}") # Expected: ["1","2","Fizz"]
# Example 2: n = 5
print("\nExample 2:")
result = solution.fizz_buzz(5)
print(f"Output: {result}") # Expected: ["1","2","Fizz","4","Buzz"]
# Example 3: n = 15
print("\nExample 3:")
result = solution.fizz_buzz(15)
print(f"Output: {result}") # Expected: ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]
# Test with alternative implementations
print("\nAlternative implementations:")
print("Concatenation approach:", solution.fizz_buzz_concatenation(15))
print("List comprehension approach:", solution.fizz_buzz_comprehension(15))
</pre>
</div>
</div>
</div>
<script>
let n = 30;
let result = [];
let currentIndex = 0;
let isRunning = false;
function getFizzBuzz(num) {
if (num % 15 === 0) return { text: 'FizzBuzz', type: 'fizzbuzz' };
if (num % 3 === 0) return { text: 'Fizz', type: 'fizz' };
if (num % 5 === 0) return { text: 'Buzz', type: 'buzz' };
return { text: String(num), type: 'number' };
}
function updateN() {
n = parseInt(document.getElementById('nSlider').value);
document.getElementById('nValue').textContent = n;
reset();
}
function render() {
const container = document.getElementById('gridDisplay');
container.innerHTML = result.map((item, i) => {
const colors = {
fizz: '#4caf50',
buzz: '#2196f3',
fizzbuzz: '#e91e63',
number: '#ff9800'
};
const bg = colors[item.type] || '#999';
const isNew = i === currentIndex - 1;
return `<div style="
padding: 8px 4px;
background: ${bg};
color: white;
border-radius: 6px;
font-size: ${item.type === 'fizzbuzz' ? '0.6em' : '0.75em'};
font-weight: bold;
text-align: center;
${isNew ? 'transform: scale(1.1); box-shadow: 0 0 10px rgba(0,0,0,0.3);' : ''}
transition: all 0.2s;
">${item.text}</div>`;
}).join('');
// Update counts
const counts = { fizz: 0, buzz: 0, fizzbuzz: 0, number: 0 };
result.forEach(item => counts[item.type]++);
document.getElementById('fizzCount').textContent = counts.fizz;
document.getElementById('buzzCount').textContent = counts.buzz;
document.getElementById('fizzBuzzCount').textContent = counts.fizzbuzz;
document.getElementById('numberCount').textContent = counts.number;
}
async function start() {
if (isRunning) {
isRunning = false;
document.getElementById('startBtn').textContent = '▶ Start';
return;
}
isRunning = true;
document.getElementById('startBtn').textContent = '⏸ Pause';
while (currentIndex < n && isRunning) {
currentIndex++;
const fb = getFizzBuzz(currentIndex);
result.push(fb);
document.getElementById('statusMessage').textContent =
`i = ${currentIndex}: ${currentIndex} % 15 = ${currentIndex % 15}, % 3 = ${currentIndex % 3}, % 5 = ${currentIndex % 5} → "${fb.text}"`;
render();
await new Promise(r => setTimeout(r, 100));
}
if (currentIndex >= n) {
document.getElementById('statusMessage').textContent = `Done! Generated FizzBuzz from 1 to ${n}`;
}
isRunning = false;
document.getElementById('startBtn').textContent = '▶ Start';
}
function reset() {
isRunning = false;
result = [];
currentIndex = 0;
document.getElementById('statusMessage').textContent = 'Click Start to generate FizzBuzz sequence';
document.getElementById('startBtn').textContent = '▶ Start';
document.getElementById('gridDisplay').innerHTML = '<span style="color: #999; grid-column: span 10; text-align: center;">Sequence will appear here...</span>';
document.getElementById('fizzCount').textContent = '0';
document.getElementById('buzzCount').textContent = '0';
document.getElementById('fizzBuzzCount').textContent = '0';
document.getElementById('numberCount').textContent = '0';
}
reset();
</script>
</body>
</html>