↓Skip to main content
  1. LeetCode/

LeetCode 3950: Exactly One Consecutive Set Bits Pair

·1 min· ·
LeetCode Easy Bit-Manipulation
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2026-06-11

  • Submissions: Accepted (first try)

Approach
#

n >> 1 shifts every bit right by one; ANDing with n, bit i is 1 when bits i and i + 1 of n are both 1 (Bit Manipulation Template 2). So the number of ones in pairs = n & (n >> 1) is the number of adjacent pairs; exactly one means pairs is non-zero with a single 1. Overlapping pairs count, e.g. 111 has two.

My Solution
#

class Solution:
    def consecutiveSetBits(self, n: int) -> bool:
        pairs = n & (n >> 1)
        return pairs != 0 and pairs & (pairs - 1) == 0

I originally converted bin(n) to a string and counted "11" position by position, which also counts overlaps.

Complexity
#

Time O(1), space O(1).

Mistakes to Avoid
#

  • str.count("11") skips overlaps ("111".count("11") is 1); compare position by position or use bit operations.

Interview Explanation
#

Each 1 in n & (n >> 1) marks one adjacent pair, so I check it is non-zero and that x & (x - 1) is 0, i.e. exactly one 1. Time O(1).

Related

LeetCode 3827: Count Monobit Integers
·1 min
LeetCode Easy Bit-Manipulation Enumeration
LeetCode 3827 note: the only numbers with all-equal bits are 0 and 2^k - 1, so the count is (n + 1).bit_length()
LeetCode 1763: Longest Nice Substring
·2 mins
LeetCode Easy Sliding-Window Divide-and-Conquer Hash-Table String Bit-Manipulation
LeetCode 1763 note: a character whose other case never appears cannot be in the answer, so split on it and recurse, preferring the left side on ties
LeetCode 3750: Minimum Number of Flips to Reverse Binary String
·2 mins
LeetCode Easy Two-Pointers Bit-Manipulation String
LeetCode 3750 note: compare the binary string with its reverse bit by bit; the number of mismatches is the answer
LeetCode 3688: Bitwise OR of Even Numbers in an Array
·1 min
LeetCode Easy Bit-Manipulation Array Simulation
LeetCode 3688 note: OR only the even numbers; the starting value 0 is also the answer when there are none
LeetCode 2859: Sum of Values at Indices With K Set Bits
·1 min
LeetCode Easy Array Bit-Manipulation
LeetCode 2859 note: count the set bits of the index, not of the value
LeetCode 762: Prime Number of Set Bits in Binary Representation
·1 min
LeetCode Easy Math Bit-Manipulation Primality-Test
LeetCode 762 note: numbers are below 10^6 < 2^20, so the set-bit count is at most 19; check it against a small set of primes