Spread the word.

Share the link on social media.

Share
  • Facebook
Have an account? Sign In Now

Sign Up Sign Up


Have an account? Sign In Now

Sign In Sign In


Forgot Password?

Don't have account, Sign Up Here

Forgot Password Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.


Have an account? Sign In Now

You must login to ask a question.


Forgot Password?

Need An Account, Sign Up Here

You must login to add post.


Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

RTSALL Logo RTSALL Logo
Sign InSign Up

RTSALL

RTSALL Navigation

  • Home
  • Tools
    • Run Code
    • JSON Beautifier
    • Regex Tester
    • Diff Checker
    • JWT Decoder
    • UUID Generator
    • .htaccess Generator
    • YAML/JSON Converter
    • SQL Formatter
    • Cron Generator
    • JSON to CSV/Excel
    • System Design Estimator
  • DSA
    • All DSA Problems
    • Online C++ Runner
    • Arrays, Strings & Cache
    • Two Pointers & Sliding Window
    • Linked Lists & Custom Allocators
    • Stacks, Queues & Ring Buffers
    • Trees, BSTs & Indexes
    • Tries & Prefix Search
    • Heaps & Priority Schedulers
    • Hashing & Collision Resolution
    • Graphs & Network Topologies
    • Dynamic Programming
    • Advanced Bitmask & Tree DP
    • Greedy & Resource Allocation
    • Binary Search & State Spaces
    • Bit Manipulation & Low-Level
    • System-Scale & Probabilistic
  • AI Utilities
    • Token Counter
    • JSON Schema Compiler
    • Fine-Tuning JSONL Converter
    • Vector RAG Playground
    • Prompt Optimizer & Architect
    • LLM GPU VRAM Calculator
  • Finance Tools
    • Compound Interest Calculator
    • Simple Interest Calculator
    • Present Value (PV) Calculator
    • Future Value (FV) Calculator
    • NPV Calculator
    • IRR Calculator
    • CAGR Calculator
    • Dividend Income Calculator
    • Yield on Cost Calculator
    • Dividend Payout Ratio
    • WACC Calculator
    • CAPM & Cost of Equity
    • Cost of Debt Calculator
    • DCF Valuation Calculator
    • Enterprise Value Calculator
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Tools
    • Run Code
    • JSON Beautifier
    • Regex Tester
    • Diff Checker
    • JWT Decoder
    • UUID Generator
    • .htaccess Generator
    • YAML/JSON Converter
    • SQL Formatter
    • Cron Generator
    • JSON to CSV/Excel
    • System Design Estimator
  • DSA
    • All DSA Problems
    • Online C++ Runner
    • Arrays, Strings & Cache
    • Two Pointers & Sliding Window
    • Linked Lists & Custom Allocators
    • Stacks, Queues & Ring Buffers
    • Trees, BSTs & Indexes
    • Tries & Prefix Search
    • Heaps & Priority Schedulers
    • Hashing & Collision Resolution
    • Graphs & Network Topologies
    • Dynamic Programming
    • Advanced Bitmask & Tree DP
    • Greedy & Resource Allocation
    • Binary Search & State Spaces
    • Bit Manipulation & Low-Level
    • System-Scale & Probabilistic
  • AI Utilities
    • Token Counter
    • JSON Schema Compiler
    • Fine-Tuning JSONL Converter
    • Vector RAG Playground
    • Prompt Optimizer & Architect
    • LLM GPU VRAM Calculator
  • Finance Tools
    • Compound Interest Calculator
    • Simple Interest Calculator
    • Present Value (PV) Calculator
    • Future Value (FV) Calculator
    • NPV Calculator
    • IRR Calculator
    • CAGR Calculator
    • Dividend Income Calculator
    • Yield on Cost Calculator
    • Dividend Payout Ratio
    • WACC Calculator
    • CAPM & Cost of Equity
    • Cost of Debt Calculator
    • DCF Valuation Calculator
    • Enterprise Value Calculator
  • About Us
  • Blog
  • Contact Us
Home/Questions/Q 3539
Next
In Process

RTSALL Latest Articles

aarav0
aarav0
Asked: September 11, 20262026-09-11T09:53:58-05:00 2026-09-11T09:53:58-05:00In: Data Structures & Algorithms, Trees, BSTs & Hierarchical Indexes

Lowest Common Ancestor: Why Binary Lifting in O(log N) beats naive DFS in high-scale DAGs

In standard coding questions, Lowest Common Ancestor (LCA) in a binary tree is solved with post-order recursive DFS in O(N) time. But in production systems (like corporate organization charts or Git commit graph merges), we need to answer thousands of LCA queries per second on the same immutable tree.

Running an O(N) DFS for each query is way too slow. How does Binary Lifting precompute jump tables to answer any LCA query in O(log N) time?

  • 0
  • 2 2 Answers
  • 0 Followers
  • 0
  • Share
    Share
    • Share on Facebook
    • Share on Twitter
    • Share on LinkedIn
    • Share on WhatsApp

Leave an answer
Cancel reply

You must login to add an answer.


Forgot Password?

Need An Account, Sign Up Here

2 Answers

  • Voted
  • Oldest
  • Recent
  • Random
  1. Anonymous
    Anonymous Begginer
    2026-09-11T21:27:27-05:00Added an answer on September 11, 2026 at 9:27 pm

    Here is the full C++20 Binary Lifting LCA implementation. Any LCA query runs in O(log N) time.

    Modern C++20 Solution (Fully Runnable)

    #include <iostream>
    #include <vector>
    #include <cmath>
    #include <algorithm>
    
    class TreeLCA {
        int n, max_log;
        std::vector<int> depth;
        std::vector<std::vector<int>> up;
    
        void dfs(int u, int p, int d, const std::vector<std::vector<int>>& adj) {
            depth[u] = d;
            up[u][0] = p;
            for (int i = 1; i < max_log; ++i) {
                up[u][i] = up[ up[u][i - 1] ][i - 1];
            }
            for (int v : adj[u]) {
                if (v != p) dfs(v, u, d + 1, adj);
            }
        }
    
    public:
        TreeLCA(int nodes, int root, const std::vector<std::vector<int>>& adj) : n(nodes) {
            max_log = std::ceil(std::log2(n)) + 1;
            depth.assign(n, 0);
            up.assign(n, std::vector<int>(max_log, root));
            dfs(root, root, 0, adj);
        }
    
        int queryLCA(int u, int v) const {
            if (depth[u] < depth[v]) std::swap(u, v);
    
            int diff = depth[u] - depth[v];
            for (int i = 0; i < max_log; ++i) {
                if ((diff >> i) & 1) u = up[u][i];
            }
            if (u == v) return u;
    
            for (int i = max_log - 1; i >= 0; --i) {
                if (up[u][i] != up[v][i]) {
                    u = up[u][i];
                    v = up[v][i];
                }
            }
            return up[u][0];
        }
    };
    
    int main() {
        int n = 7;
        std::vector<std::vector<int>> adj(n);
        adj[0] = {1, 2};
        adj[1] = {0, 3, 4};
        adj[2] = {0, 5, 6};
        adj[3] = {1}; adj[4] = {1};
        adj[5] = {2}; adj[6] = {2};
    
        TreeLCA lca(n, 0, adj);
        std::cout << "LCA(3, 4): " << lca.queryLCA(3, 4) << "n"; // Expected: 1
        std::cout << "LCA(3, 6): " << lca.queryLCA(3, 6) << "n"; // Expected: 0
        return 0;
    }
    

    Complexity: O(N log N) preprocessing and O(log N) per query.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
  2. Anonymous
    Anonymous Begginer
    2026-09-11T09:54:00-05:00Added an answer on September 11, 2026 at 9:54 am

    When you have multiple online LCA queries on a static tree, the gold standard is Binary Lifting (used in compiler dominance frontiers, distributed network routing, and Git commit histories).

    1. The Core Idea: Powers of 2 Parent Jumps

    Instead of storing only a node’s immediate parent (which forces you to step up the tree one node at a time in $O(N)$), what if every node stored its ancestor at distance $2^0, 2^1, 2^2, 2^3, dots, 2^k$?

    We define a 2D table: up[u][i] = the (2^i)-th ancestor of node u.

    The state transition is pure dynamic programming:

    up[u][i] = up[ up[u][i-1] ][i-1]
    

    In English: ‘To jump $2^i$ steps up from $u$, first jump $2^{i-1}$ steps up to reach intermediate node $v$, and then from $v$ jump another $2^{i-1}$ steps!’ ($2^{i-1} + 2^{i-1} = 2^i$).


    2. Answering an LCA Query in 2 Steps

    To find the LCA of nodes u and v:

    1. Level the Depths: If depth[u] < depth[v], swap them. Use binary powers to jump u upwards until depth[u] == depth[v] in $O(log N)$ steps. If u == v, they were on the same branch → return u!
    2. Simultaneous Binary Leap: Jump both u and v upwards together using the largest possible power of 2 such that their ancestors are still different (up[u][i] != up[v][i]). When no more jumps can be made, their immediate parent (up[u][0]) is their Lowest Common Ancestor!

    Clean C++20 Implementation

    #include <vector>
    #include <cmath>
    #include <algorithm>
    
    class TreeLCA {
        int n, max_log;
        std::vector<int> depth;
        std::vector<std::vector<int>> up;
    
        void dfs(int u, int p, int d, const std::vector<std::vector<int>>& adj) {
            depth[u] = d;
            up[u][0] = p;
            for (int i = 1; i < max_log; ++i) {
                up[u][i] = up[ up[u][i - 1] ][i - 1];
            }
            for (int v : adj[u]) {
                if (v != p) {
                    dfs(v, u, d + 1, adj);
                }
            }
        }
    
    public:
        TreeLCA(int nodes, int root, const std::vector<std::vector<int>>& adj) : n(nodes) {
            max_log = std::ceil(std::log2(n)) + 1;
            depth.assign(n, 0);
            up.assign(n, std::vector<int>(max_log, root));
            dfs(root, root, 0, adj);
        }
    
        int queryLCA(int u, int v) {
            if (depth[u] < depth[v]) std::swap(u, v);
    
            // Step 1: Bring u and v to same depth
            int diff = depth[u] - depth[v];
            for (int i = 0; i < max_log; ++i) {
                if ((diff >> i) & 1) {
                    u = up[u][i];
                }
            }
            if (u == v) return u;
    
            // Step 2: Jump together
            for (int i = max_log - 1; i >= 0; --i) {
                if (up[u][i] != up[v][i]) {
                    u = up[u][i];
                    v = up[v][i];
                }
            }
            return up[u][0];
        }
    };
    

    Complexity Breakdown

    • Preprocessing Time: O(N log N) via a single DFS pass.
    • Preprocessing Memory: O(N log N) to store the jump table.
    • Per Query Time: Strictly O(log N). For $N = 1,000,000$, $log_2(1,000,000) pprox 20$ operations. You can evaluate 50,000 queries in a fraction of a second!
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp

Sidebar

Ask A Question
  • Popular
  • Answers
  • Queryiest

    What is a database?

    • 3 Answers
  • Anonymous

    How to rotate an array in-place with O(1) space and ...

    • 3 Answers
  • hannah

    What steps can businesses take to identify the most valuable ...

    • 2 Answers
  • Vikram
    aarav0 added an answer Direct Technical Solution: Unlike IVFFlat (which partitions vector spaces with… September 11, 2026 at 9:57 pm
  • Abhishek
    Abhishek added an answer Direct Technical Solution: In C++20, range view adaptors (like std::views::filter,… September 11, 2026 at 9:57 pm
  • Sneha Patel
    Anonymous added an answer Direct Technical Solution: torch.cuda.empty_cache() releases only cached (unallocated) blocks back… September 11, 2026 at 9:57 pm

Related Questions

  • pgvector: HNSW index build fails with out-of-memory or high swap: ...

    • 1 Answer
  • Why does std::views::filter on temporary containers trigger undefined behavior and ...

    • 1 Answer
  • PyTorch RuntimeError: CUDA out of memory: Why torch.cuda.empty_cache() fails & ...

    • 1 Answer
  • Next.js 15: Error: Route used "params" without awaiting it (Asynchronous ...

    • 1 Answer
  • Task Scheduler with Cooldowns: Closed-form mathematical formula vs Priority Queue ...

    • 2 Answers

Top Members

Queryiest

Queryiest

  • 201 Questions
  • 295 Points
Enlightened
Anonymous

Anonymous

  • 11 Questions
  • 42 Points
Begginer
paperubofficial

paperubofficial

  • 0 Questions
  • 22 Points
Begginer

Trending Tags

ai asp.net aws basics aws certification aws console aws free tier aws login aws scenario-based questions c++ career cyber security cyber security interview git java javascript jobs jquery net core net core interview questions sql

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • DSA Problems
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • New Questions
  • Trending Questions
  • Must read Questions
  • Hot Questions

Footer

About Us

  • Meet The Team
  • Blog
  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy
  • Disclaimer
  • Terms & Conditions

Help

  • Knowledge Base
  • Support

Follow

© 2023-25 RTSALL. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.