100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace

What is Heavy-Light Decomposition?

Learn how heavy-light decomposition splits a tree into chains for fast O(log^2 n) path queries, with steps and code.

hardQ208 of 234 in Data Structures & Algorithms Est. time: 6 minsLast updated:
Open Code Lab
208 / 234

Expected Interview Answer

Heavy-light decomposition splits a tree into vertical chains so that any root-to-node path crosses at most O(log n) chains, letting path queries (sum, max, update) run in O(log^2 n) using a segment tree over each chain.

For every node, the child with the largest subtree is marked as its 'heavy' child, and the edge to it is a heavy edge; every other child edge is 'light'. Chaining heavy edges together produces disjoint heavy paths that partition the whole tree, and each is mapped onto a contiguous range in an array so a segment tree or Fenwick tree can answer range queries on it. Moving from any node to the root crosses at most O(log n) light edges, because each light edge at least halves the subtree size, so a path query walks up chain by chain, querying each chain's segment tree once. This turns tree path problems into a bounded number of array range problems, which is why it underlies subtree/path sum, LCA, and path-update problems on large trees.

  • O(log^2 n) path queries and updates on trees
  • Reduces tree problems to segment-tree range problems
  • At most O(log n) light-edge jumps per root path
  • Foundation for LCA, path-sum, and path-max queries

AI Mentor Explanation

Think of a domestic cricket academy's coaching lineage as a tree, where each senior coach mentors several junior coaches. The academy designates one 'main successor' per coach — the junior who trains the most players — and that mentor-to-successor link is a heavy edge, chained together into a long coaching lineage. Tracing any coach's ancestry to the academy founder mostly slides along one lineage chain, only jumping to a different chain a few times, since each jump means the junior's group was less than half the size. This is why finding common coaching ancestry between two coaches only needs a handful of chain jumps, not a walk through every mentor individually.

Step-by-Step Explanation

  1. Step 1

    Compute subtree sizes

    One DFS pass computes the size of every subtree rooted at each node.

  2. Step 2

    Mark heavy children

    For each node, the child with the largest subtree becomes its heavy child; that edge is a heavy edge.

  3. Step 3

    Build chains and map to array positions

    A second DFS follows heavy edges first, assigning each node a contiguous array index within its chain.

  4. Step 4

    Answer queries by walking chains

    To query a path, repeatedly jump to the top of the current chain and query the segment tree, moving to the parent chain until both endpoints share a chain.

What Interviewer Expects

  • Explain why the heavy child is the largest-subtree child
  • Justify the O(log n) bound on light-edge jumps via the halving argument
  • Describe mapping chains to array ranges for a segment tree
  • State the overall complexity as O(log^2 n) per path query

Common Mistakes

  • Forgetting to recompute heavy children after tree modifications
  • Confusing heavy-light decomposition with simple binary lifting for LCA
  • Not realizing chains must be contiguous in the array for segment tree range queries to work
  • Underestimating implementation complexity of combining chain jumps with segment tree merges

Best Answer (HR Friendly)

Heavy-light decomposition breaks a tree into a small number of long chains so path queries feel like array range queries. I would use it whenever I need fast repeated path sum or path max queries on a large, mostly static tree, since it caps the number of chain switches at O(log n).

Code Example

Heavy-light decomposition setup
import sys
sys.setrecursionlimit(200000)

def build_hld(n, adj, root=0):
    parent = [-1] * n
    size = [1] * n
    heavy = [-1] * n
    order = []

    def dfs_size(u, p):
        parent[u] = p
        for v in adj[u]:
            if v != p:
                dfs_size(v, u)
                size[u] += size[v]
                if heavy[u] == -1 or size[v] > size[heavy[u]]:
                    heavy[u] = v

    dfs_size(root, -1)

    chain_head = [0] * n
    pos = [0] * n
    counter = [0]

    def dfs_chain(u, head):
        chain_head[u] = head
        pos[u] = counter[0]
        counter[0] += 1
        order.append(u)
        if heavy[u] != -1:
            dfs_chain(heavy[u], head)
        for v in adj[u]:
            if v != parent[u] and v != heavy[u]:
                dfs_chain(v, v)

    dfs_chain(root, root)
    return parent, chain_head, pos, order

def path_query(u, v, parent, chain_head, pos, depth, query_range):
    result = 0
    while chain_head[u] != chain_head[v]:
        if depth[chain_head[u]] < depth[chain_head[v]]:
            u, v = v, u
        result += query_range(pos[chain_head[u]], pos[u])
        u = parent[chain_head[u]]
    if depth[u] > depth[v]:
        u, v = v, u
    result += query_range(pos[u], pos[v])
    return result

Follow-up Questions

  • How would you combine heavy-light decomposition with a Fenwick tree instead of a segment tree?
  • How does heavy-light decomposition handle subtree updates as well as path updates?
  • How would you support dynamic tree edits without rebuilding all chains?
  • How does heavy-light decomposition compare to Euler tour techniques for LCA?

MCQ Practice

1. What determines which child of a node is its heavy child?

The heavy child is the one whose subtree has the most nodes, guaranteeing at most O(log n) light edges on any root path.

2. What is the time complexity of a single path query using heavy-light decomposition with a segment tree?

Each of the O(log n) chains crossed requires an O(log n) segment tree query, giving O(log^2 n) total.

3. Why can a root-to-node path cross at most O(log n) light edges?

A light child’s subtree is at most half the parent subtree’s size, so subtree size at least halves at each light edge, bounding the count to O(log n).

Flash Cards

What is a heavy edge in heavy-light decomposition?The edge from a node to the child whose subtree has the most nodes.

What is the complexity of a path query with HLD and a segment tree?O(log^2 n): O(log n) chains times O(log n) per segment tree query.

Why are chains stored as contiguous array ranges?So a segment tree or Fenwick tree can answer range queries on each chain efficiently.

What bounds the number of light edges on a root path?Each light edge at least halves the subtree size, giving an O(log n) bound.

1 / 4
208 / 234

Continue Learning

Frequently Asked Questions

21 categories · pick one to explore

Where can I practice technical interview questions for free in India?
SkillVeris offers a free interview questions section with readiness scoring, so you can practice technical interview questions at no cost from anywhere in India or worldwide. Questions span AI/ML, programming, web development, DevOps, cloud and security. Combine them with Code Lab for hands-on coding practice and the AI Mentor for instant explanations whenever an answer confuses you.
How do I prepare for a coding interview if I am a complete beginner?
Start by learning one language well, then practice small problems daily before attempting interview questions. On SkillVeris you can take a free structured programming course with 24–40 lessons, write code in the in-browser Code Lab across 6 languages, and then move to the interview questions bank with readiness scoring to measure how prepared you actually are.
What is interview readiness scoring and how does it work?
Interview readiness scoring measures how prepared you are for a technical interview based on your performance across practice questions. On SkillVeris, as you answer interview questions, your readiness score updates so you can see weak topics before the real interview. It turns vague confidence into a concrete signal, telling you which areas need more revision and which are already strong.
How long does it take to get interview ready for a developer job?
Most beginners need a few months of consistent practice to feel interview ready, though timelines vary with background and daily study time. A practical route is finishing a structured SkillVeris course, which includes 24–40 lessons, module assessments and a final exam at an 80 percent pass mark, then drilling the free interview questions until your readiness score is consistently strong.
What are the most common technical interview topics for freshers?
Freshers are commonly tested on programming fundamentals, data structures, problem solving, databases, and basics of the role's stack such as web development or cloud. SkillVeris covers these through 37 free courses, a glossary of around 2,000 terms for quick definitions, cheat sheets for revision, and interview questions with readiness scoring so you can practise exactly what interviewers usually ask.
Can I practice coding interview prep without installing anything?
Yes, SkillVeris Code Lab runs entirely in your browser, so you can practice coding interview prep without installing compilers or editors. It supports 6 languages across 15 categories of exercises. Pair Code Lab sessions with the interview questions bank and readiness scoring, and you have a complete free preparation setup that works on any machine with an internet connection.
How do I explain technical concepts clearly in an interview?
Practice explaining each concept through a simple analogy first, then add the technical detail, because interviewers value clarity over jargon. SkillVeris teaches with its Learn Through Hobbies method, explaining concepts through cricket, music, gaming, cooking and eight more domains. Learning a topic through an analogy gives you a ready-made, memorable way to explain it when an interviewer asks.
Are there free mock interview resources for software engineers?
SkillVeris provides free interview questions with readiness scoring, which works like a self-paced mock interview you can repeat any time. You answer real-style technical questions, get scored, and see where you stand. The AI Mentor is available 24/7 to explain any answer at Quick, Detailed or Deep-dive depth, acting like an always-available interviewer who never gets tired.
How should I prepare for an AI or machine learning interview?
Cover ML fundamentals, Python, and modern topics like LLMs and RAG, then practise explaining projects clearly. SkillVeris has free AI/ML courses including Python for AI and ML, Large Language Models and Retrieval-Augmented Generation, each with 24–40 lessons and assessments. After finishing, use the interview questions bank and readiness scoring to confirm you can answer under pressure.
What should I revise the night before a technical interview?
Revise concise summaries rather than learning anything new: core definitions, common patterns, and your own project stories. SkillVeris cheat sheets and study notes are built exactly for this kind of quick revision, and the glossary of around 2,000 terms lets you verify any definition fast. A short readiness-score check on the interview questions bank confirms nothing critical is shaky.
How do I prepare for a DevOps interview with no work experience?
Build demonstrable knowledge through structured learning and hands-on practice, since you cannot point to job experience. SkillVeris offers free DevOps, Docker and Kubernetes related courses within its 37-course catalog and a DevOps Engineer learning path. Complete the courses, earn certificates by passing the final exams, then use the interview questions section to rehearse common DevOps scenarios.
Do certificates help in clearing technical interviews?
Certificates alone do not clear interviews, but they signal structured learning and give interviewers a starting point for questions. SkillVeris awards certificates when you pass a course final exam at 80 percent, after 24–40 lessons and module assessments, so the certificate reflects genuine effort. Pair it with practised interview answers and Code Lab projects to make a stronger impression.
How can I improve my problem solving speed for coding interviews?
Speed comes from repetition on progressively harder problems, not from rushing. Practise daily in SkillVeris Code Lab, which offers in-browser coding in 6 languages across 15 categories, and time yourself on interview questions. Review every mistake with the AI Mentor, which explains solutions 24/7 at Quick, Detailed or Deep-dive depth, so each session genuinely improves your pattern recognition.
What questions are asked in a Python technical interview?
Python interviews typically cover data types, functions, comprehensions, OOP, error handling and libraries relevant to the role, such as ML packages for AI positions. SkillVeris interview questions include Python topics, and its free Python for AI and ML course builds the underlying knowledge across 24–40 lessons. Readiness scoring then shows whether your Python answers are interview grade.
How do I handle interview questions I don't know the answer to?
Say what you do know, reason aloud toward an approach, and be honest about the gap, because interviewers value thinking over bluffing. Reduce how often this happens by broadening fundamentals: SkillVeris study notes, cheat sheets and the roughly 2,000-term glossary fill knowledge gaps quickly, and readiness scoring highlights weak areas before an interviewer ever finds them.
Is there a free way to check my interview readiness before applying for jobs?
Yes, SkillVeris interview questions come with readiness scoring, all completely free, so you can measure preparation before applying. Once your score looks solid, browse the SkillVeris Jobs page, which aggregates live roles across India, UK, USA, Germany and Remote with salary and experience filters, and apply knowing your technical preparation has been objectively tested.
How do I prepare for web developer interview questions?
Focus on JavaScript fundamentals, your framework of choice, HTTP basics, and building things you can discuss. SkillVeris offers free web development courses among its 37-course catalog, plus a Full Stack Java Developer learning path. After the courses, drill the interview questions bank, practise coding tasks in Code Lab, and use readiness scoring to verify you cover typical frontend and backend topics.
Can the AI Mentor help me practice interview answers?
Yes, the SkillVeris AI Mentor answers questions 24/7 and can explain any concept at Quick, Detailed or Deep-dive depth, which makes it useful for rehearsing interview explanations. Ask it to clarify a topic, then try explaining it back in your own words. Combined with the interview questions bank and readiness scoring, it becomes a free, always-available practice partner.
What is the best free platform for technical interview prep in 2026?
SkillVeris is a strong free option because it combines structured learning with dedicated interview preparation in one place. You get 37 free courses, interview questions with readiness scoring, an in-browser Code Lab for hands-on practice, cheat sheets and study notes for revision, and a 24/7 AI Mentor. Everything is free, which matters for learners in India and worldwide.
How do I stay calm and confident during a technical interview?
Confidence comes from evidence of preparation, so build that evidence deliberately. Complete a SkillVeris course, pass its final exam at the 80 percent bar, and watch your readiness score climb on the interview questions bank. Knowing you have explained concepts through analogies, coded in Code Lab, and scored well on practice questions gives you genuine, grounded calm on the day.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse