Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Trees/Binary Lifting & LCA

Technique · CP 2400+

Virtual (Auxiliary) Tree

For a query that marks k vertices: sort them by DFS entry time, add the LCAs of adjacent pairs, and build an O(k)-node tree that keeps the ancestor relations. Running the per-query tree DP on it costs O(sum k log n) in total.

Learn firstBinary Lifting & LCAEuler Tour / Tree FlatteningDP on Trees
0%
mastery
0/3 solved
Practise nextKingdom and its Cities
IdeaPracticePitfalls

Recognise it

The signal

many queries, each with a small vertex set, and sum of k <= 1e5-2e5

  1. 1Brute force

    Full tree DP per query: O(nq).

  2. 2The observation

    Unmarked vertices off the paths between marked ones do not matter, but a full DP still visits them.

  3. 3Why it works

    Marked vertices plus the LCAs of DFS-order neighbours form a set closed under LCA, so its induced tree has at most 2k - 1 nodes.

Reach for it when

  • +a per-query tree DP that would be O(n)
  • +'remove the fewest vertices so that no two marked vertices are connected'

Not when

  • ×a single query
  • ×large marked sets (sum of k unbounded)

Practice

Next

Kingdom and its Cities

0/3 solved
  • Kingdom and its CitiesCodeforces2800
  • Count PathsCodeforces2000
  • Chaotic V.Codeforces2700

Pitfalls

Misconceptions

  • !only LCAs of consecutive vertices in DFS order are needed, not all pairs
Go deeper1 combinations · resources

Combinations

  • Virtual (Auxiliary) Tree+DP on Trees+Binary Lifting & LCA

    many queries with a small vertex set each and sum of k bounded

    Virtual (Auxiliary) Tree:
    shrink the tree to the O(k) marked vertices and their LCAs
    DP on Trees:
    run the separation/cover DP on the small tree
    Binary Lifting & LCA:
    LCA queries while building the virtual tree

    Kingdom and its CitiesCount Paths

Resources

  • Binary Tree explore cardLeetCode · course
  • Tree cheatsheetTech Interview Handbook · article
  • BST visualizerVisuAlgo · tool
  • Introduction to Tree AlgorithmsUSACO Guide · course
  • Lowest Common Ancestorcp-algorithms · article
  • NeetCode RoadmapNeetCode · sheet
TodayReviewPatternsProblems