Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started
Dataford
Popular roles
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Browse
Browse All RolesEvery role hub, from analyst to MLBrowse All CompaniesCompany-specific interview loopsAll Interview GuidesThe full guide library
Top questions by role
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Top questions by skill
SQLPythonStatisticsMachine LearningA/B TestingSystem DesignGenerative AIProduct SenseMetricsBehavioral
Browse all questions →Try a mock interview
Experiences
Practice
Mock InterviewsTimed interview simulations with feedbackSuccess PathYour 6-week structured planModulesCurated lessons by topicWebinarsTalks from ex-Big Tech data leadsPlaygroundA free-form scratch editor
Learn
BlogInterview strategy and career adviceTech Job Market ReportHiring trends across data and AI rolesFor UniversitiesDataford for career centersAbout DatafordWho we are and how we build
Pricing
Build my plan
Balanced Binary Tree
00:00
5 left

Balanced Binary Tree

EasyPython

Problem

Binance may represent hierarchical structures such as referral or permission relationships as binary trees. Given a binary tree, determine whether it is height-balanced: at every node, the heights of its left and right subtrees differ by no more than one.

Use a single function that returns True for a balanced tree and False otherwise. The input tree is encoded recursively as [value, left, right], where left and right are either another encoded tree or null. An empty tree is represented by null. The node value can be any integer and does not affect balance.

Formal Specification

  • Input: root, a nested list or null. A non-empty node has the form [value, left, right].
  • Output: A boolean indicating whether the tree is height-balanced.

Your solution should avoid repeatedly calculating subtree heights, since that can make a skewed tree quadratic. Return as soon as an unbalanced subtree is detected.

Constraints

  • 0 <= number of nodes <= 10^5
  • value is an integer in [-10^9, 10^9]
  • The encoded tree contains no cycles
  • The solution should run in linear time

Function Signature

def is_balanced(root):
Interviewer

Your question is Balanced Binary Tree. Start with the requirements in the Question tab.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.
CodePython 3
Sign up free to run your codeLog inLn 2
Run your code to see test output here.