Count Nodes in a Complete Binary Heap Tree Faster Than Linear

Last updated: November 29, 2026

Quick Overview

A priority scheduler stores tasks in a complete binary tree (every level full except possibly the last, which fills left to right). Count its nodes in less than O(n) time.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Medium

0

0

0 solved


A priority scheduler stores tasks in a complete binary tree (every level full except possibly the last, which fills left to right). Count its nodes in less than O(n) time.

A well-known Google onsite question that tests whether you exploit structure instead of traversing. The interviewer expects the O(log^2 n) argument and will often ask for the O(log^2 n) binary search over the last level as an alternative.

What the Interviewer Expects
  • Note that a plain traversal is O(n) and not acceptable
  • Compare leftmost and rightmost heights to detect perfect subtrees
  • Use 2^h - 1 for perfect subtrees
  • Recurse into only one non-perfect side per level
  • Prove the O(log^2 n) bound
Key Topics to Cover
binary trees
complete binary tree
divide and conquer
complexity analysis
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • Count by binary searching the last level with path bits instead.
  • What if the tree is only guaranteed to be balanced, not complete?
  • Find the parent slot for the next insertion in O(log n).
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

Input: root of a complete binary tree. Output: node count. Target time is better than O(n). Empty tree returns 0....

High-Level Design

Measure the height by walking only left pointers and the height by walking only right pointers from a node. If they are equal, the subtree is perfect and has 2^h - 1 nodes, no traversal needed. If n...


Submit Your Answer
Markdown supported