Hi👋SpeedAlgo • Deliberate Practice & Cognitive Ergonomics for Software Engineers

An interactive algorithm mastery and technical interview preparation platform published by Hi👋WebEnterprise. Built for senior and staff software engineers preparing for rigorous coding screens at top tech companies (FAANG/MAMAA).

13 Core Algorithmic Patterns & 225 Practice Problems

  • 1. Two Pointers (16 Paradigms, 43 Problems): Opposite ends, sorted pair sums, palindrome verification, trapping rain water, 3Sum, container with most water — includes the Sliding Window and Fast & Slow Pointers paradigms (contiguous subarray invariants, longest substrings, Floyd's cycle detection, linked list middle).
  • 2. Binary Search (9 Paradigms, 14 Problems): Monotonic predicate partitioning (feasible(x)), boundary search, rotated sorted arrays, square roots, minimum ship capacity, median of two sorted arrays, matrix median on value range.
  • 3. Bit Manipulation (5 Paradigms, 11 Problems): Counting set bits, XOR cancellation, bit reversal, bitmask pairing, maximum XOR with a bitwise trie.
  • 4. Math & Geometry (8 Paradigms, 14 Problems): Sieve of Eratosthenes, integer/roman conversions, modular arithmetic, geometric simulation.
  • 5. Tree/Graph Depth-First Search (15 Paradigms, 24 Problems): Path sums, lowest common ancestor, tree diameter, validating BSTs, tree DP (House Robber III, Binary Tree Cameras).
  • 6. Tree/Graph Breadth-First Search (5 Paradigms, 12 Problems): Level-order traversals, shortest path in unweighted graphs, zig-zag traversals, rotting oranges, word ladders.
  • 7. Graphs (12 Paradigms, 22 Problems): Topological sort, cycle detection, Dijkstra's algorithm, bipartite graph validation, network delay.
  • 8. Backtracking (6 Paradigms, 14 Problems): Subsets, permutations, combinations, constraint satisfaction, pruning, N-Queens, Sudoku solver.
  • 9. Dynamic Programming (13 Paradigms, 28 Problems): Memoization vs tabulation, 0/1 knapsack, unbounded knapsack, coin change, edit distance, longest common subsequence.
  • 10. Heap / Priority Queue (9 Paradigms, 11 Problems): Running medians, top-k elements, interval scheduling, IPO, k-way merges.
  • 11. Advanced Data Structures (7 Paradigms, 17 Problems): Trie (prefix tree), Union-Find (Disjoint Set Union), LRU Cache, LFU Cache, range-sum queries with updates.
  • 12. Stack (5 Paradigms, 9 Problems): Next greater element, largest rectangle in histogram, remove k digits, decode string, min stack.
  • 13. Intervals & Greedy (2 Paradigms, 6 Problems): Merge intervals, interval scheduling, meeting rooms by sweep line, jump game.

4-Stage Deliberate Practice Framework

  1. Stage 1 (Compare & Learn): Read the pattern's mental model, loop invariant and Big-O proof, compare the pattern's template with the problem's solution side by side, and use the step-by-step debugger. The solution can also be shown in C#, Java, TypeScript, C++, Go or Rust for almost every problem.
  2. Stage 2 (Active Recall): Rebuild the solution from memory in a code editor, with an invariant checklist and optional progressive hints, and check it against a judged test suite.
  3. Stage 3 (AI Interview Coach, coming soon): A mock-interview stage still in development; for now, students go straight from Stage 2 to Stage 4.
  4. Stage 4 (Solve on Your Own): Solve a new problem on your own against a 15-minute timer; your code is graded against a test suite. Python and TypeScript run in your browser and C# runs on our server (design problems grade in Python and TypeScript).

Equipped with a spaced-repetition review hub on a fixed 7-step schedule (1 day up to 90 days), a two-pane Studio workspace, and study notes.

Pricing, Access & Commercial Terms

  • Core Curriculum: 100% Free. No credit card required.
  • Coins: New accounts get 40 free coins once, the daily claim adds +20 coins once a day, and inviting a friend earns you +25 coins when they complete their first practice step. These are the only ways to earn coins.
  • AI Coach: Each AI coach question costs 1-5 coins, priced by the server according to its size.
  • BYOK (Bring Your Own Key): AI coaching is free with your own Google Gemini, OpenAI or OpenRouter API key (BYOK).
  • Extras: Coins also unlock extras for 24 hours: a Recall hint level (1 coin), a Solve solution reveal (2), a LeetCode problem card's solutions (1) and a pattern's extra canonical problems (1).
  • Payments & Refunds: Nothing on the site is sold for money: coins can only be earned, never bought. There are no subscriptions or charges, so there is nothing to refund.
  • Platform Operator: Hi👋WebEnterprise. Support & policies at hispeedalgo.com.
Skip to main content
Hi👋SpeedAlgo

Invariant-First Algorithmic Mastery

Arena
238Items
Theory Context•Bit Manipulation
P1EasyMental model~3 min speedrun

Brian Kernighan's Algorithm / Popcount (n & (n-1))

Unlocks
Bit TricksFenwick Tree

Number of 1 Bits (LC 191)(opens leetcode.com)

Given a positive integer n, count how many bits equal 1 appear in its binary form — this count is known as the number's Hamming weight.

A set bit refers to a bit in the binary representation of a number that is equal to 1.

Example 1
Input:n = 11
Output:3
n = 11 is 1011 in binary, which contains three 1-bits.

Kernighan's Bit Trick

number ➔ lowest set bit ➔ one fewer bit
Spot it when: The problem counts 1 bits, asks whether a number is a power of two (or four), or needs to visit only the set bits of a mask.
Kernighan's Bit Trick
Python
1def count_set_bits(n: int) -> int:
2 """Number of 1 Bits: counts the 1s with Brian Kernighan's trick.
3 Time: O(K), K = number of set bits (<= 32) | Space: O(1)
4 """
5 count = 0
6 while n > 0:
7 n &= (n - 1) # Clear lowest set bit
8 count += 1
9 return count
10 
11def is_power_of_two(n: int) -> bool:
12 """Power of Two: exactly one set bit, and n must be positive.
13 Time: O(1) | Space: O(1)
14 """
15 return n > 0 and (n & (n - 1)) == 0 # n > 0 is mandatory: 0 & -1 == 0
Invariant: Each n &= (n - 1) removes exactly one set bit, so count plus the set bits still in n always equals the set bits of the original n.

n & (n - 1) clears the lowest set bit of n, so count_set_bits repeats it and counts the rounds until n is 0. Subtracting 1 turns the lowest 1 into 0 and every 0 below it into 1, while the higher bits stay the same, so the AND keeps exactly the higher bits: each round removes one set bit, and the loop runs once per set bit. The same fact makes is_power_of_two one test, since a power of two has exactly one set bit. The trap is n = 0: while n > 0 stops there because no set bit is left to clear, but 0 & -1 is also 0, so is_power_of_two needs the same n > 0 guard, or is_power_of_two(0) returns True.

See it run

Kernighan's Bit Trick, step by step

n 1011 · count 0

n 1011 · count 0

n 1010 · count 1

n 1010 · count 1

n 1000 · count 2

n 1000 · count 2

n 0000 · count 3

n 0000 · count 3

n 0000 · count 3 · answer 3

Each column is one bit position. The rows are n, n - 1, and n & (n - 1).

  • low 1 the lowest set bit of n
  • flipped the bits of n - 1 that differ from n
  • cleared the bit that n & (n - 1) removed

Start: n = 1011 (11) and count = 0. The loop runs while n > 0.

n - 1 = 1010. The lowest 1 of n is at bit 0, so that bit and every bit below it flip.

n & (n - 1) = 1011 & 1010 = 1010. n becomes 1010 and count becomes 1.

n - 1 = 1001. The lowest 1 of n is at bit 1, so that bit and every bit below it flip.

n & (n - 1) = 1010 & 1001 = 1000. n becomes 1000 and count becomes 2.

n - 1 = 0111. The lowest 1 of n is at bit 3, so that bit and every bit below it flip.

n & (n - 1) = 1000 & 0111 = 0000. n becomes 0000 and count becomes 3.

n is now 0, so n > 0 is false and the loop stops. For is_power_of_two, 0 & -1 is also 0, so that function needs the guard n > 0.

Done: 3 rounds removed 3 set bits. The answer is count = 3.

n
bit 31
bit 20
bit 11
bit 01
n - 1
n & (n - 1)
1 / 9
Gotchas1 of 3

Gotcha 1 of 3

  1. 1
    The trap

    Gotcha 1: Testing a power of two without n > 0

    Mistake
    return (n & (n - 1)) == 0
    Fix
    return n > 0 and (n & (n - 1)) == 0

    What happens: A power of two has exactly one set bit, so n & (n - 1) clears it and leaves 0. But 0 has no set bit, and 0 & -1 is also 0. So the test alone calls 0 a power of two. The guard n > 0 rules it out.

    Example: n = 0
    Mistake: returns TrueFix: returns False
  2. 2

    Gotcha 2: Shifting with n >>= 1 but counting every round

    Mistake
    n >>= 1
    Fix
    n &= (n - 1)

    What happens: n >>= 1 removes the lowest bit whether it is 1 or 0. The loop still adds 1 to count on every round. So it counts the length of n in bits, not its 1 bits. n &= (n - 1) removes exactly one set bit per round.

    Example: n = 11 (binary 1011)
    Mistake: returns 4Fix: returns 3
  3. 3

    Gotcha 3: Passing a negative n without the 32-bit mask

    Mistake
    count_set_bits(n)
    Fix
    count_set_bits(n & 0xFFFFFFFF)

    What happens: Some problems give a 32-bit value as a signed int, so it can be negative. A negative Python int has no fixed width. while n > 0 then stops at once and returns 0. n & 0xFFFFFFFF keeps the 32 bits the problem means.

    Example: n = -1 (32 set bits)
    Mistake: returns 0Fix: returns 32
Not this one if…
  • Every bit must move to a new position, as in Reverse Bits (LC 190), not just be counted or tested. See Bit Tricks

Deep Dive

Why n & (n - 1) clears the lowest set bit

Write n in binary as a prefix, then a lowest 1, then zeros: prefix 1 000. Subtracting 1 borrows from that lowest 1. It becomes 0, and every 0 below it becomes 1. The prefix does not change: prefix 0 111.

The AND of the two numbers keeps a bit only where both have a 1. The prefix is in both, so it stays. The position of the lowest 1 is 1 in n and 0 in n - 1, so it is cleared. The zeros below are 0 in n, so they stay 0.

Example: n = 12 is 1100 and n - 1 = 11 is 1011. The AND is 1000, which is 8. Exactly one set bit was removed.

Counting set bits: the loop runs once per set bit

count_set_bits repeats n &= (n - 1) and adds 1 to count each time. Each round removes one set bit, so the invariant holds: count plus the set bits still in n equals the set bits of the original n. When n is 0, no set bit is left, and count is the answer.

The cost is O(K) where K is the number of set bits. For n = 11 (1011) the loop runs 3 times, and for n = 2**30 it runs once. Checking every position would always take 32 rounds.

The loop condition is n > 0. It is correct for non-negative numbers. See the last section for negative values.

Power of two and the same trick for tests

A power of two has exactly one set bit. After one round of n & (n - 1), that bit is gone and the result is 0. So is_power_of_two is n > 0 and (n & (n - 1)) == 0.

The guard n > 0 is required. The number 0 has no set bit, but 0 & -1 is also 0, so the test alone calls 0 a power of two. A negative number is not a power of two either, and the guard rejects it.

For Power of Four (LC 342), add one more fact: the single set bit must be at an even position. The mask 0x55555555 has 1s at the even positions, so the extra test is n & 0x55555555 != 0.

Reuse: counting bits for every number up to n

Because i & (i - 1) is i with one set bit removed, it is a smaller number that was already computed. For Counting Bits (LC 338), write dp[i] = dp[i & (i - 1)] + 1. Each answer takes O(1) time, so all of 0..n costs O(n).

Example: dp[0..8] is [0, 1, 1, 2, 1, 2, 2, 3, 1]. For i = 6 (110), 6 & 5 = 4, dp[4] = 1, so dp[6] = 2.

Negative values need care. A negative Python integer has no fixed width, so while n > 0 ends at once and returns 0. When a problem gives a 32-bit value as a signed integer, use n & 0xFFFFFFFF first. For -1 the result is 32 set bits.

60-Second Pitch

"The simple way to count set bits tests all 32 positions. I use n & (n - 1) instead. Subtracting 1 turns the lowest 1 into 0 and the zeros below it into 1s, so the AND clears exactly the lowest set bit. The loop runs once per set bit, so the time is O(K) with K at most 32, and the space is O(1). The same fact tests a power of two in one line, n > 0 and (n & (n - 1)) == 0. I keep the n > 0 guard, because zero would otherwise pass. For a signed 32-bit input, I mask with 0xFFFFFFFF first."

Common Questions

Why does n & (n - 1) remove exactly one set bit?

Subtracting 1 flips the lowest set bit to 0 and every lower zero to 1. The bits above stay the same. The AND keeps the higher bits and clears the lowest set bit and the bits below. For 12 & 11, 1100 & 1011 gives 1000.

What is the time complexity of count_set_bits, and how does it compare with a loop over 32 bits?

It is O(K), where K is the number of set bits, at most 32. The loop over all positions always takes 32 rounds. For a sparse value such as 2**30, Kernighan's version takes 1 round.

How do you test for a power of two, and why is n > 0 needed?

Use n > 0 and (n & (n - 1)) == 0. A power of two has one set bit, so one clear step gives 0. The number 0 also gives 0 after the step, so without n > 0 it would be accepted. Negative numbers are rejected by the same guard.

How do you handle a negative input in Python?

A negative Python integer has no fixed width, so while n > 0 returns 0 at once. If the problem means a 32-bit value, apply n & 0xFFFFFFFF first. For -1, the count is then 32.

How does the trick give all bit counts from 0 to n in O(n)?

i & (i - 1) is i with its lowest set bit removed, a smaller number. So dp[i] = dp[i & (i - 1)] + 1. Each value takes O(1) time, as in Counting Bits (LC 338).

SWE Reasoning

Spot it

  • The problem asks for the number of 1 bits (Number of 1 Bits (LC 191), Hamming weight).
  • The problem asks whether a number is a power of two, or a power of four (Power of Two (LC 231), Power of Four (LC 342)).
  • The loop must visit only the set bits of a mask, not all 32 positions.
  • The answer for a number can be built from the answer for the same number with one set bit removed (Counting Bits (LC 338)).

The invariant, step by step

  1. count is 0 and n holds the input.
  2. While n > 0, n has at least one set bit.
  3. n &= (n - 1) clears the lowest set bit and changes nothing else.
  4. count += 1 records that one set bit was removed.
  5. So at every step, count plus the set bits still in n equals the set bits of the original n.
  6. When n reaches 0, no set bit is left, and count equals the set bits of the original n.

Traps

  • Power of two without n > 0. is_power_of_two(0) returns True, because 0 & -1 is 0. Add the guard.
  • Shifting instead of clearing. n >>= 1 removes the lowest bit whether it is 0 or 1. If count still grows each round, it counts the length of n in bits. count_set_bits(11) returns 4 instead of 3.
  • Negative input. while n > 0 stops at once for a negative Python integer and returns 0. Use n & 0xFFFFFFFF for a 32-bit signed value.
  • Power of four with only the one-bit test. 8 has one set bit but is not a power of four. Also check the position with 0x55555555.

Practice

Canonical LeetCode:Number of 1 Bits (LC 191)Counting Bits (LC 338)Prime Number of Set Bits in Binary Representation (LC 762)Power of Four (LC 342)Sort Integers by The Number of 1 Bits (LC 1356)Power of Two (LC 231)Hamming Distance (LC 461)K-th Symbol in Grammar (LC 779)
Theory Context•Bit Manipulation
P1EasyMental model~3 min speedrun

Brian Kernighan's Algorithm / Popcount (n & (n-1))

Unlocks
Bit TricksFenwick Tree

Number of 1 Bits (LC 191)(opens leetcode.com)

Given a positive integer n, count how many bits equal 1 appear in its binary form — this count is known as the number's Hamming weight.

A set bit refers to a bit in the binary representation of a number that is equal to 1.

Example 1
Input:n = 11
Output:3
n = 11 is 1011 in binary, which contains three 1-bits.

Kernighan's Bit Trick

number ➔ lowest set bit ➔ one fewer bit
Spot it when: The problem counts 1 bits, asks whether a number is a power of two (or four), or needs to visit only the set bits of a mask.
Kernighan's Bit Trick
Python
1def count_set_bits(n: int) -> int:
2 """Number of 1 Bits: counts the 1s with Brian Kernighan's trick.
3 Time: O(K), K = number of set bits (<= 32) | Space: O(1)
4 """
5 count = 0
6 while n > 0:
7 n &= (n - 1) # Clear lowest set bit
8 count += 1
9 return count
10 
11def is_power_of_two(n: int) -> bool:
12 """Power of Two: exactly one set bit, and n must be positive.
13 Time: O(1) | Space: O(1)
14 """
15 return n > 0 and (n & (n - 1)) == 0 # n > 0 is mandatory: 0 & -1 == 0
Invariant: Each n &= (n - 1) removes exactly one set bit, so count plus the set bits still in n always equals the set bits of the original n.

n & (n - 1) clears the lowest set bit of n, so count_set_bits repeats it and counts the rounds until n is 0. Subtracting 1 turns the lowest 1 into 0 and every 0 below it into 1, while the higher bits stay the same, so the AND keeps exactly the higher bits: each round removes one set bit, and the loop runs once per set bit. The same fact makes is_power_of_two one test, since a power of two has exactly one set bit. The trap is n = 0: while n > 0 stops there because no set bit is left to clear, but 0 & -1 is also 0, so is_power_of_two needs the same n > 0 guard, or is_power_of_two(0) returns True.

See it run

Kernighan's Bit Trick, step by step

n 1011 · count 0

n 1011 · count 0

n 1010 · count 1

n 1010 · count 1

n 1000 · count 2

n 1000 · count 2

n 0000 · count 3

n 0000 · count 3

n 0000 · count 3 · answer 3

Each column is one bit position. The rows are n, n - 1, and n & (n - 1).

  • low 1 the lowest set bit of n
  • flipped the bits of n - 1 that differ from n
  • cleared the bit that n & (n - 1) removed

Start: n = 1011 (11) and count = 0. The loop runs while n > 0.

n - 1 = 1010. The lowest 1 of n is at bit 0, so that bit and every bit below it flip.

n & (n - 1) = 1011 & 1010 = 1010. n becomes 1010 and count becomes 1.

n - 1 = 1001. The lowest 1 of n is at bit 1, so that bit and every bit below it flip.

n & (n - 1) = 1010 & 1001 = 1000. n becomes 1000 and count becomes 2.

n - 1 = 0111. The lowest 1 of n is at bit 3, so that bit and every bit below it flip.

n & (n - 1) = 1000 & 0111 = 0000. n becomes 0000 and count becomes 3.

n is now 0, so n > 0 is false and the loop stops. For is_power_of_two, 0 & -1 is also 0, so that function needs the guard n > 0.

Done: 3 rounds removed 3 set bits. The answer is count = 3.

n
bit 31
bit 20
bit 11
bit 01
n - 1
n & (n - 1)
1 / 9
Gotchas1 of 3

Gotcha 1 of 3

  1. 1
    The trap

    Gotcha 1: Testing a power of two without n > 0

    Mistake
    return (n & (n - 1)) == 0
    Fix
    return n > 0 and (n & (n - 1)) == 0

    What happens: A power of two has exactly one set bit, so n & (n - 1) clears it and leaves 0. But 0 has no set bit, and 0 & -1 is also 0. So the test alone calls 0 a power of two. The guard n > 0 rules it out.

    Example: n = 0
    Mistake: returns TrueFix: returns False
  2. 2

    Gotcha 2: Shifting with n >>= 1 but counting every round

    Mistake
    n >>= 1
    Fix
    n &= (n - 1)

    What happens: n >>= 1 removes the lowest bit whether it is 1 or 0. The loop still adds 1 to count on every round. So it counts the length of n in bits, not its 1 bits. n &= (n - 1) removes exactly one set bit per round.

    Example: n = 11 (binary 1011)
    Mistake: returns 4Fix: returns 3
  3. 3

    Gotcha 3: Passing a negative n without the 32-bit mask

    Mistake
    count_set_bits(n)
    Fix
    count_set_bits(n & 0xFFFFFFFF)

    What happens: Some problems give a 32-bit value as a signed int, so it can be negative. A negative Python int has no fixed width. while n > 0 then stops at once and returns 0. n & 0xFFFFFFFF keeps the 32 bits the problem means.

    Example: n = -1 (32 set bits)
    Mistake: returns 0Fix: returns 32
Not this one if…
  • Every bit must move to a new position, as in Reverse Bits (LC 190), not just be counted or tested. See Bit Tricks

Deep Dive

Why n & (n - 1) clears the lowest set bit

Write n in binary as a prefix, then a lowest 1, then zeros: prefix 1 000. Subtracting 1 borrows from that lowest 1. It becomes 0, and every 0 below it becomes 1. The prefix does not change: prefix 0 111.

The AND of the two numbers keeps a bit only where both have a 1. The prefix is in both, so it stays. The position of the lowest 1 is 1 in n and 0 in n - 1, so it is cleared. The zeros below are 0 in n, so they stay 0.

Example: n = 12 is 1100 and n - 1 = 11 is 1011. The AND is 1000, which is 8. Exactly one set bit was removed.

Counting set bits: the loop runs once per set bit

count_set_bits repeats n &= (n - 1) and adds 1 to count each time. Each round removes one set bit, so the invariant holds: count plus the set bits still in n equals the set bits of the original n. When n is 0, no set bit is left, and count is the answer.

The cost is O(K) where K is the number of set bits. For n = 11 (1011) the loop runs 3 times, and for n = 2**30 it runs once. Checking every position would always take 32 rounds.

The loop condition is n > 0. It is correct for non-negative numbers. See the last section for negative values.

Power of two and the same trick for tests

A power of two has exactly one set bit. After one round of n & (n - 1), that bit is gone and the result is 0. So is_power_of_two is n > 0 and (n & (n - 1)) == 0.

The guard n > 0 is required. The number 0 has no set bit, but 0 & -1 is also 0, so the test alone calls 0 a power of two. A negative number is not a power of two either, and the guard rejects it.

For Power of Four (LC 342), add one more fact: the single set bit must be at an even position. The mask 0x55555555 has 1s at the even positions, so the extra test is n & 0x55555555 != 0.

Reuse: counting bits for every number up to n

Because i & (i - 1) is i with one set bit removed, it is a smaller number that was already computed. For Counting Bits (LC 338), write dp[i] = dp[i & (i - 1)] + 1. Each answer takes O(1) time, so all of 0..n costs O(n).

Example: dp[0..8] is [0, 1, 1, 2, 1, 2, 2, 3, 1]. For i = 6 (110), 6 & 5 = 4, dp[4] = 1, so dp[6] = 2.

Negative values need care. A negative Python integer has no fixed width, so while n > 0 ends at once and returns 0. When a problem gives a 32-bit value as a signed integer, use n & 0xFFFFFFFF first. For -1 the result is 32 set bits.

60-Second Pitch

"The simple way to count set bits tests all 32 positions. I use n & (n - 1) instead. Subtracting 1 turns the lowest 1 into 0 and the zeros below it into 1s, so the AND clears exactly the lowest set bit. The loop runs once per set bit, so the time is O(K) with K at most 32, and the space is O(1). The same fact tests a power of two in one line, n > 0 and (n & (n - 1)) == 0. I keep the n > 0 guard, because zero would otherwise pass. For a signed 32-bit input, I mask with 0xFFFFFFFF first."

Common Questions

Why does n & (n - 1) remove exactly one set bit?

Subtracting 1 flips the lowest set bit to 0 and every lower zero to 1. The bits above stay the same. The AND keeps the higher bits and clears the lowest set bit and the bits below. For 12 & 11, 1100 & 1011 gives 1000.

What is the time complexity of count_set_bits, and how does it compare with a loop over 32 bits?

It is O(K), where K is the number of set bits, at most 32. The loop over all positions always takes 32 rounds. For a sparse value such as 2**30, Kernighan's version takes 1 round.

How do you test for a power of two, and why is n > 0 needed?

Use n > 0 and (n & (n - 1)) == 0. A power of two has one set bit, so one clear step gives 0. The number 0 also gives 0 after the step, so without n > 0 it would be accepted. Negative numbers are rejected by the same guard.

How do you handle a negative input in Python?

A negative Python integer has no fixed width, so while n > 0 returns 0 at once. If the problem means a 32-bit value, apply n & 0xFFFFFFFF first. For -1, the count is then 32.

How does the trick give all bit counts from 0 to n in O(n)?

i & (i - 1) is i with its lowest set bit removed, a smaller number. So dp[i] = dp[i & (i - 1)] + 1. Each value takes O(1) time, as in Counting Bits (LC 338).

SWE Reasoning

Spot it

  • The problem asks for the number of 1 bits (Number of 1 Bits (LC 191), Hamming weight).
  • The problem asks whether a number is a power of two, or a power of four (Power of Two (LC 231), Power of Four (LC 342)).
  • The loop must visit only the set bits of a mask, not all 32 positions.
  • The answer for a number can be built from the answer for the same number with one set bit removed (Counting Bits (LC 338)).

The invariant, step by step

  1. count is 0 and n holds the input.
  2. While n > 0, n has at least one set bit.
  3. n &= (n - 1) clears the lowest set bit and changes nothing else.
  4. count += 1 records that one set bit was removed.
  5. So at every step, count plus the set bits still in n equals the set bits of the original n.
  6. When n reaches 0, no set bit is left, and count equals the set bits of the original n.

Traps

  • Power of two without n > 0. is_power_of_two(0) returns True, because 0 & -1 is 0. Add the guard.
  • Shifting instead of clearing. n >>= 1 removes the lowest bit whether it is 0 or 1. If count still grows each round, it counts the length of n in bits. count_set_bits(11) returns 4 instead of 3.
  • Negative input. while n > 0 stops at once for a negative Python integer and returns 0. Use n & 0xFFFFFFFF for a 32-bit signed value.
  • Power of four with only the one-bit test. 8 has one set bit but is not a power of four. Also check the position with 0x55555555.

Practice

Canonical LeetCode:Number of 1 Bits (LC 191)Counting Bits (LC 338)Prime Number of Set Bits in Binary Representation (LC 762)Power of Four (LC 342)Sort Integers by The Number of 1 Bits (LC 1356)Power of Two (LC 231)Hamming Distance (LC 461)K-th Symbol in Grammar (LC 779)
© 2026 Hi👋WebEnterprise. All rights reserved.
Sitemap•llms.txt•