Problem 1483

Abstract / Summary

Given a tree and a node, find the kth ancestor of that node.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1483.py

class TreeAncestor:
    def __init__(self, n: int, parent: List[int]):
        # powers of ten
        steps = [ 1, 10, 100, 1_000, 10_000 ]
        self.parents = { 1: parent, 10: [], 100: [], 1_000: [], 10_000: [] }

        # 10th/100th parent
        for s in steps[1:]:
            for i in range(n):
                x = i
                # based on the previous step size
                for i in range(10):
                    if x != -1:
                        x = self.parents[s // 10][x]

                self.parents[s].append(x)

    def getKthAncestor(self, node: int, k: int) -> int:
        x = node

        for s in reversed(self.parents):
            while k >= s:
                x = self.parents[s][x]
                if x == -1:
                    return -1
                k -= s

        return x

# Your TreeAncestor object will be instantiated and called as such:
# obj = TreeAncestor(n, parent)
# param_1 = obj.getKthAncestor(node,k)
32 lines | 994 bytes | submitted November 13, 2023 | GitHub   30% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 36% (100k+ submissions).

Typical patterns to solve this problem:
  • Binary Search
  • Breadth First Search
  • Depth First Search
  • Design
  • Dynamic Programming
  • Tree
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The TreeAncestor class builds a lookup structure that enables fast retrieval of the k-th ancestor of any node in a rooted tree. The constructor receives the total number of nodes n and an array parent where parent[i] is the immediate parent of node i (or -1 for the root). The implementation pre-computes ancestors at step sizes that are powers of ten (1, 10, 100, 1 000, 10 000) and stores them in a dictionary keyed by the step size. The getKthAncestor method then walks the pre-computed tables from the largest step down to the smallest, subtracting the step size from k each time it jumps upward. If a jump reaches -1, the method returns -1 immediately, indicating that the requested ancestor does not exist.

Initialization

The constructor begins by defining the step sizes that will be used for the jump table.

steps = [ 1, 10, 100, 1_000, 10_000 ]
self.parents = { 1: parent, 10: [], 100: [], 1_000: [], 10_000: [] }

self.parents[1] holds the original parent array, while the other entries are initially empty lists that will be filled with ancestors at larger intervals.

Building the Jump Table

For each step size beyond the base step (1), the code iterates over every node and climbs the tree ten times using the previously built table. The inner loop performs ten successive jumps of the smaller step size, effectively creating a jump of size s.

for s in steps[1:]:
    for i in range(n):
        x = i
        for i in range(10):
            if x != -1:
                x = self.parents[s // 10][x]
        self.parents[s].append(x)

The outer loop selects the current step s. The inner loop processes each node i. The innermost loop repeats ten times, each time moving up by the previously computed step s // 10. The result x after ten repetitions is the ancestor that is s steps above the original node, or -1 if the root is reached earlier. The final value is appended to the list for step s.

Edge Cases Handled in Table Construction

  • When a node’s ancestor chain ends before completing ten jumps, the condition if x != -1 prevents further lookups and preserves the sentinel -1.
  • The root node, whose parent is -1, propagates the sentinel through all larger steps, ensuring that any query that climbs beyond the root will encounter -1 early.

Query Processing

The getKthAncestor method receives a target node and a distance k. It starts from the node and iterates over the step sizes in descending order, using a while loop to consume as many whole steps of the current size as possible.

x = node
for s in reversed(self.parents):
    while k >= s:
        x = self.parents[s][x]
        if x == -1:
            return -1
        k -= s
return x

The reversed(self.parents) expression yields the step sizes from the largest (10 000) down to the smallest (1). For each step size s, the inner while loop repeatedly jumps upward by s as long as the remaining distance k is at least s. After each jump, the method checks whether the sentinel -1 has been reached; if so, it returns -1 immediately, avoiding unnecessary further computation. When all possible large jumps have been exhausted, any leftover distance is covered by smaller steps, ultimately arriving at the exact k-th ancestor or confirming its absence.

Edge Cases Handled in Queries

  • If k is larger than the depth of the node, the algorithm will eventually attempt to jump from a node whose entry in the current table is -1. The early return ensures the correct result of -1.
  • When k is zero, the outer loop never enters the inner while because k >= s is false for all positive s. The method returns the original node unchanged, which matches the definition of a zero-step ancestor.
  • Queries for the root node (node with parent -1) are handled gracefully: any positive k will cause the first lookup in the smallest step table to yield -1, leading to an immediate return.

Performance Optimizations

The design leverages a multi-level jump table where each level represents a fixed stride of ten times the previous level. By pre-computing ancestors at these strides, the query method can skip large portions of the ancestor chain in a single array access. This reduces the number of iterations needed for large values of k compared to a naïve linear walk.

The use of a dictionary keyed by step size allows constant-time retrieval of the appropriate table during both construction and queries. The inner construction loop reuses the previously built table (self.parents[s // 10]) to compute the next level, avoiding redundant traversal of the tree.

The early exit condition if x == -1: return -1 inside the query loop prevents unnecessary work once the root has been passed, which is especially beneficial for queries where k exceeds the depth of the node.

Overall, the combination of pre-computed stride tables, descending step iteration, and sentinel checks yields a solution that processes ancestor queries with far fewer operations than a straightforward step-by-step climb.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a giant family tree where every person is holding hands with their parent. This code is like building a fast map to help you find your great-great-great grandparents without having to walk up the line one person at a time.

The first part creates a shortcut ladder for everybody. Instead of just knowing who your mom or dad is, the code remembers who is ten steps up, one hundred steps up, and all the way up to ten thousand steps up. It does this by asking your parent who their parent is, and then asking that person too, until it marks down exactly who is at those big jumps.

When someone wants to find a specific ancestor, the computer looks at the big jump numbers first. If you need to go up fifteen steps, the computer takes the biggest jump it can, like a ten-step leap, and then it only has to take five small steps to finish the trip. This makes finding family members go super fast, almost like jumping through the air instead of climbing the ladder one little rung at a time. If the computer ever reaches the top of the tree and finds nobody is there, it simply says that the ancestor does not exist for that number.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 3 | μ = 4.44 | σ = 2.11

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ C# Python Java Go TS
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
FelixFan1122 C#
fsq C++
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, Python, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
FelixFan1122 C#
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
wisdompeak C++
26 links | 14 authors | 7 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

10 solutions   November 13, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality