LeetCode #3677 — HARD

Count Binary Palindromic Numbers

Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.

Solve on LeetCode
The Problem

Problem Statement

You are given a non-negative integer n.

A non-negative integer is called binary-palindromic if its binary representation (written without leading zeros) reads the same forward and backward.

Return the number of integers k such that 0 <= k <= n and the binary representation of k is a palindrome.

Note: The number 0 is considered binary-palindromic, and its representation is "0".

Example 1:

Input: n = 9

Output: 6

Explanation:

The integers k in the range [0, 9] whose binary representations are palindromes are:

  • 0 → "0"
  • 1 → "1"
  • 3 → "11"
  • 5 → "101"
  • 7 → "111"
  • 9 → "1001"

All other values in [0, 9] have non-palindromic binary forms. Therefore, the count is 6.

Example 2:

Input: n = 0

Output: 1

Explanation:

Since "0" is a palindrome, the count is 1.

Constraints:

  • 0 <= n <= 1015
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: You are given a non-negative integer n. A non-negative integer is called binary-palindromic if its binary representation (written without leading zeros) reads the same forward and backward. Return the number of integers k such that 0 <= k <= n and the binary representation of k is a palindrome. Note: The number 0 is considered binary-palindromic, and its representation is "0".

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Math · Bit Manipulation

Example 1

9

Example 2

0
Step 02

Core Insight

What unlocks the optimal approach

  • Try to think in terms of binary string length rather than brute forcing all numbers <code><= n</code>.
  • How many binary palindromes exist for a given length <code>L</code>? (only the first half determines the whole number.)
  • You can pre-count all palindromes of <code>length < len(n)</code> directly using powers of 2.
  • For palindromes of <code>length = len(n)</code>, extract the prefix of <code>n</code>, mirror it, and check if it exceeds <code>n</code>.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3677: Count Binary Palindromic Numbers
// Auto-generated Java example from go.
class Solution {
    public void exampleSolution() {
    }
}
// Reference (go):
// // Accepted solution for LeetCode #3677: Count Binary Palindromic Numbers
// package main
// 
// import (
// 	"math/bits"
// 	"strconv"
// )
// 
// // https://space.bilibili.com/206214
// func countBinaryPalindromes1(n int64) int {
// 	s := strconv.FormatUint(uint64(n), 2)
// 	m := len(s)
// 
// 	// 二进制长度小于 m,随便填
// 	ans := 1
// 	// 枚举二进制长度,最高位填 1,回文数左半的其余位置随便填
// 	for i := 1; i < m; i++ {
// 		ans += 1 << ((i - 1) / 2)
// 	}
// 
// 	var dfs func(int, int, bool) int
// 	dfs = func(i, pal int, limit bool) (res int) {
// 		if !limit {
// 			// 回文数左半的其余位置随便填
// 			return 1 << ((m+1)/2 - i)
// 		}
// 
// 		if i == (m+1)/2 {
// 			// 左半反转到右半
// 			// 如果 m 是奇数,那么去掉回文中心再反转
// 			for v := pal >> (m % 2); v > 0; v /= 2 {
// 				pal = pal*2 + v%2
// 			}
// 			if pal > int(n) {
// 				return 0
// 			}
// 			return 1
// 		}
// 
// 		up := int(s[i] - '0')
// 		for d := 0; d <= up; d++ {
// 			res += dfs(i+1, pal*2+d, limit && d == up)
// 		}
// 		return res
// 	}
// 
// 	// 最高位一定是 1,从 i=1 开始填
// 	return ans + dfs(1, 1, true)
// }
// 
// func countBinaryPalindromes(n int64) int {
// 	if n == 0 {
// 		return 1
// 	}
// 
// 	m := bits.Len(uint(n))
// 	k := (m - 1) / 2
// 
// 	// 二进制长度小于 m
// 	ans := 2<<k - 1
// 	if m%2 == 0 {
// 		ans += 1 << k
// 	}
// 
// 	// 二进制长度等于 m,且回文数的左半小于 n 的左半
// 	left := n >> (m / 2)
// 	ans += int(left) - 1<<k
// 
// 	// 二进制长度等于 m,且回文数的左半等于 n 的左半
// 	right := bits.Reverse32(uint32(left>>(m%2))) >> (32 - m/2)
// 	if left<<(m/2)|int64(right) <= n {
// 		ans++
// 	}
// 
// 	return ans
// }
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n)
Space
O(1)

Approach Breakdown

SORT + SCAN
O(n log n) time
O(n) space

Sort the array in O(n log n), then scan for the missing or unique element by comparing adjacent pairs. Sorting requires O(n) auxiliary space (or O(1) with in-place sort but O(n log n) time remains). The sort step dominates.

BIT MANIPULATION
O(n) time
O(1) space

Bitwise operations (AND, OR, XOR, shifts) are O(1) per operation on fixed-width integers. A single pass through the input with bit operations gives O(n) time. The key insight: XOR of a number with itself is 0, which eliminates duplicates without extra space.

Shortcut: Bit operations are O(1). XOR cancels duplicates. Single pass → O(n) time, O(1) space.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Overflow in intermediate arithmetic

Wrong move: Temporary multiplications exceed integer bounds.

Usually fails on: Large inputs wrap around unexpectedly.

Fix: Use wider types, modular arithmetic, or rearranged operations.