-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0338_counting_bits.html
More file actions
427 lines (354 loc) · 14.8 KB
/
0338_counting_bits.html
File metadata and controls
427 lines (354 loc) · 14.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
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Counting Bits - LeetCode 338</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">#0338</span> Counting Bits</h1>
<p><strong>Problem:</strong> Given an integer n, return an array ans of length n + 1 such that for each i (0 ≤ i ≤ n), ans[i] is the number of 1's in the binary representation of i.</p>
<p><strong>Pattern:</strong> Dynamic Programming with Bit Manipulation - dp[i] = dp[i >> 1] + (i & 1)</p>
<div class="problem-meta">
<span class="meta-tag">💻 Bit</span>
<span class="meta-tag">⏱️ O(n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0338_counting_bits/0338_counting_bits.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>Bit manipulation works with <strong>binary representations</strong>:</p>
<ul>
<li><strong>AND (&):</strong> Both bits must be 1</li>
<li><strong>OR (|):</strong> At least one bit is 1</li>
<li><strong>XOR (^):</strong> Bits must be different</li>
<li><strong>Shift:</strong> Move bits left/right</li>
</ul>
</div>
<div class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="visualization">
<svg id="mainSvg"></svg>
</div>
<div class="controls">
<button id="stepBtn">Step</button>
<button id="autoBtn">Auto Run</button>
<button id="resetBtn">Reset</button>
<div class="speed-control">
<label for="speed">Speed:</label>
<input type="range" id="speed" min="100" max="2000" value="600">
</div>
</div>
<div class="status" id="status">Click "Step" to count bits for each number</div>
<div class="variables">
<div class="var-item">
<span class="var-label">Current Number:</span>
<span id="currentNum">-</span>
</div>
<div class="var-item">
<span class="var-label">Binary:</span>
<span id="binaryDisplay" class="mono">-</span>
</div>
<div class="var-item">
<span class="var-label">Formula:</span>
<span id="formulaDisplay">dp[i] = dp[i >> 1] + (i & 1)</span>
</div>
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List
"""
LeetCode Counting Bits
Problem from LeetCode: https://leetcode.com/problems/counting-bits/
Description:
Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i.
Example 1:
Input: n = 2
Output: [0,1,1]
Explanation:
0 --> 0 (0 '1' bits)
1 --> 1 (1 '1' bit)
2 --> 10 (1 '1' bit)
Example 2:
Input: n = 5
Output: [0,1,1,2,1,2]
Explanation:
0 --> 0 (0 '1' bits)
1 --> 1 (1 '1' bit)
2 --> 10 (1 '1' bit)
3 --> 11 (2 '1' bits)
4 --> 100 (1 '1' bit)
5 --> 101 (2 '1' bits)
Constraints:
0 <= n <= 10^5
Follow up:
- It is very easy to come up with a solution with a runtime of O(n log n). Can you do it in linear time O(n) and possibly in a single pass?
- Can you do it without using any built-in function (i.e., like __builtin_popcount in C++)?
"""
class Solution:
def count_bits(self, n: int) -> List[int]:
"""
Count the number of 1's in the binary representation of each integer from 0 to n.
This is the efficient dynamic programming approach with O(n) time complexity.
Args:
n: Upper limit of the range
Returns:
List[int]: Array where ans[i] is the count of 1 bits in integer i
"""
# Initialize the result array
ans = [0] * (n + 1)
# For each number from 1 to n
for i in range(1, n + 1):
# The number of 1's in i is equal to:
# The number of 1's in i//2 plus 1 if i is odd (has a 1 in the least significant bit)
ans[i] = ans[i >> 1] + (i & 1)
return ans
def count_bits_dp_offset(self, n: int) -> List[int]:
"""
Count the number of 1's using a dynamic programming approach with offset.
For a number x, if we know the last power of 2 less than or equal to x,
we can use it as an offset.
Args:
n: Upper limit of the range
Returns:
List[int]: Array where ans[i] is the count of 1 bits in integer i
"""
ans = [0] * (n + 1)
offset = 1
for i in range(1, n + 1):
# If i is a power of 2, update the offset
if offset * 2 == i:
offset = i
# Use the offset to calculate the number of 1's
ans[i] = 1 + ans[i - offset]
return ans
def count_bits_builtin(self, n: int) -> List[int]:
"""
Count the number of 1's using Python's built-in bin() function.
This is the most straightforward but least efficient solution.
Args:
n: Upper limit of the range
Returns:
List[int]: Array where ans[i] is the count of 1 bits in integer i
"""
ans = []
for i in range(n + 1):
# Count the number of '1' characters in the binary representation
ans.append(bin(i).count('1'))
return ans
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
n1 = 2
result1 = solution.count_bits(n1)
print(f"Example 1: {result1}") # Expected output: [0, 1, 1]
# Example 2
n2 = 5
result2 = solution.count_bits(n2)
print(f"Example 2: {result2}") # Expected output: [0, 1, 1, 2, 1, 2]
# Additional example
n3 = 10
result3 = solution.count_bits(n3)
print(f"Example 3: {result3}") # Expected output: [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2]
# Using offset-based DP approach
print("\nUsing offset-based DP approach:")
result4 = solution.count_bits_dp_offset(n2)
print(f"Example 2: {result4}") # Expected output: [0, 1, 1, 2, 1, 2]
# Using built-in function approach
print("\nUsing built-in function approach:")
result5 = solution.count_bits_builtin(n2)
print(f"Example 2: {result5}") # Expected output: [0, 1, 1, 2, 1, 2]
</pre>
</div>
</div>
</div>
<script>
const n = 8;
const dp = new Array(n + 1).fill(0);
let currentIndex = 0;
let autoRunning = false;
let autoTimer = null;
const width = 900;
const height = 400;
const svg = d3.select("#mainSvg")
.attr("width", width)
.attr("height", height);
function toBinary(num, bits = 4) {
return num.toString(2).padStart(bits, '0');
}
function draw() {
svg.selectAll("*").remove();
svg.append("text")
.attr("x", width / 2)
.attr("y", 25)
.attr("text-anchor", "middle")
.attr("font-weight", "bold")
.text(`Counting Bits from 0 to ${n}`);
// Headers
const headers = ["i", "Binary", "i >> 1", "dp[i>>1]", "i & 1", "dp[i]"];
const colWidths = [50, 80, 60, 70, 60, 60];
let xPos = 80;
headers.forEach((h, idx) => {
svg.append("text")
.attr("x", xPos + colWidths[idx] / 2)
.attr("y", 60)
.attr("text-anchor", "middle")
.attr("font-weight", "bold")
.attr("fill", "#333")
.text(h);
xPos += colWidths[idx];
});
// Draw grid
for (let i = 0; i <= n; i++) {
const y = 80 + i * 35;
const isProcessed = i < currentIndex;
const isCurrent = i === currentIndex;
// Row background
svg.append("rect")
.attr("x", 70)
.attr("y", y - 15)
.attr("width", 400)
.attr("height", 30)
.attr("rx", 4)
.attr("fill", isCurrent ? "#fff3e0" : isProcessed ? "#e8f5e9" : "#f5f5f5")
.attr("stroke", isCurrent ? "#f57c00" : isProcessed ? "#4caf50" : "#ddd")
.attr("stroke-width", isCurrent ? 2 : 1);
xPos = 80;
const rowData = [
i.toString(),
toBinary(i),
(i >> 1).toString(),
isProcessed || isCurrent ? dp[i >> 1].toString() : "-",
(i & 1).toString(),
isProcessed ? dp[i].toString() : (isCurrent && currentIndex > 0 ? "?" : "-")
];
rowData.forEach((val, idx) => {
svg.append("text")
.attr("x", xPos + colWidths[idx] / 2)
.attr("y", y)
.attr("text-anchor", "middle")
.attr("font-family", idx === 1 ? "monospace" : "inherit")
.attr("fill", isCurrent && idx === 5 ? "#f57c00" : "#333")
.attr("font-weight", idx === 5 ? "bold" : "normal")
.text(val);
xPos += colWidths[idx];
});
}
// Binary visualization on right
const vizX = 550;
svg.append("text")
.attr("x", vizX + 120)
.attr("y", 60)
.attr("text-anchor", "middle")
.attr("font-weight", "bold")
.text("Visual Pattern");
for (let i = 0; i <= n; i++) {
const y = 80 + i * 35;
const bits = toBinary(i);
bits.split('').forEach((bit, bitIdx) => {
svg.append("rect")
.attr("x", vizX + bitIdx * 30)
.attr("y", y - 12)
.attr("width", 25)
.attr("height", 25)
.attr("rx", 4)
.attr("fill", bit === '1' ? "#4caf50" : "#e0e0e0")
.attr("stroke", bit === '1' ? "#2e7d32" : "#bdbdbd");
svg.append("text")
.attr("x", vizX + bitIdx * 30 + 12.5)
.attr("y", y + 2)
.attr("text-anchor", "middle")
.attr("fill", bit === '1' ? "white" : "#666")
.attr("font-weight", "bold")
.text(bit);
});
// Count
svg.append("text")
.attr("x", vizX + 140)
.attr("y", y + 2)
.attr("text-anchor", "start")
.attr("fill", i < currentIndex ? "#4caf50" : "#999")
.text(`= ${dp[i]} ones`);
}
// Result array
svg.append("text")
.attr("x", width / 2)
.attr("y", height - 20)
.attr("text-anchor", "middle")
.attr("font-size", "14px")
.text(`Result: [${dp.slice(0, currentIndex).join(", ")}${currentIndex <= n ? "..." : ""}]`);
}
function step() {
if (currentIndex > n) return false;
if (currentIndex === 0) {
dp[0] = 0;
} else {
dp[currentIndex] = dp[currentIndex >> 1] + (currentIndex & 1);
}
document.getElementById("currentNum").textContent = currentIndex;
document.getElementById("binaryDisplay").textContent = toBinary(currentIndex);
const shifted = currentIndex >> 1;
const lastBit = currentIndex & 1;
document.getElementById("formulaDisplay").textContent =
`dp[${currentIndex}] = dp[${shifted}] + ${lastBit} = ${dp[shifted]} + ${lastBit} = ${dp[currentIndex]}`;
currentIndex++;
draw();
if (currentIndex > n) {
document.getElementById("status").textContent =
`Complete! Result: [${dp.join(", ")}]`;
return false;
} else {
document.getElementById("status").textContent =
`Computed dp[${currentIndex - 1}] = ${dp[currentIndex - 1]}`;
return true;
}
}
function reset() {
currentIndex = 0;
dp.fill(0);
autoRunning = false;
if (autoTimer) clearInterval(autoTimer);
document.getElementById("currentNum").textContent = "-";
document.getElementById("binaryDisplay").textContent = "-";
document.getElementById("formulaDisplay").textContent = "dp[i] = dp[i >> 1] + (i & 1)";
document.getElementById("status").textContent = 'Click "Step" to count bits for each number';
document.getElementById("autoBtn").textContent = "Auto Run";
draw();
}
function autoRun() {
if (autoRunning) {
autoRunning = false;
clearInterval(autoTimer);
document.getElementById("autoBtn").textContent = "Auto Run";
} else {
autoRunning = true;
document.getElementById("autoBtn").textContent = "Pause";
const speed = 2100 - document.getElementById("speed").value;
autoTimer = setInterval(() => {
if (!step()) {
autoRunning = false;
clearInterval(autoTimer);
document.getElementById("autoBtn").textContent = "Auto Run";
}
}, speed);
}
}
document.getElementById("stepBtn").addEventListener("click", step);
document.getElementById("autoBtn").addEventListener("click", autoRun);
document.getElementById("resetBtn").addEventListener("click", reset);
draw();
</script>
<style>
.mono { font-family: 'Consolas', monospace; }
</style>
</body>
</html>