LogIn
I don't have account.
Sponsored -53%
Zebronics #1 Best Seller

ZEBRONICS Blanc Slim Wireless Mouse — Rechargeable, BT + 2.4GHz (Black)

Up to 1600 DPI · Silent clicks · 63g · Multicolor LED

★★★★★ 4.0 (9,512) 5K+ bought last month
₹376 M.R.P. ₹799Save ₹423
Buy Now
Adℹ

Top View of a Binary Tree Using BFS and DFS | Complete Guide

DevSniper
12 Views

#tree

#binary-tree

#b-tree

#treemap

#depth-first-search

#breadth-first-search

Amazon Pay offer
Adℹ

If you've spent any time prepping for interviews at product-based companies, you've probably noticed that binary tree "view" problems top view, bottom view, left view, right view show up constantly. They look deceptively simple on a whiteboard, but the moment you start coding one under interview pressure, it's easy to write something that looks right, passes on the example the interviewer drew and then quietly falls apart on a slightly different tree shape. This article walks through exactly that journey for the top view problem: a first attempt that seems reasonable, why it breaks and how to arrive at a clean, optimal fix.

Problem Statement

You are given the root of a binary tree. Imagine standing far above the tree and looking straight down the top view is the set of nodes you'd actually be able to see from that angle.

More precisely: for every horizontal position in the tree, the top view keeps only the node that's closest to the root at that position. Any node hidden underneath a shallower node at the same horizontal position is left out.

Given the root of a binary tree, return its top view as a list of values, read from left to right.

For example, for a tree shaped like this:

              1
            /   \
           2     3
            \     \
             4     5
            /     /
           6     7

The top view is:

2, 1, 3, 5

Understanding the Problem First

The key concept here is horizontal distance (HD) the same idea that underlies most binary tree "view" problems, so it's worth being precise about it once and reusing it everywhere.

Draw a vertical line straight down through the root call that position 0. Every time you move to a left child, you shift one step left (-1), every move to a right child shifts one step right (+1). That running total is the node's horizontal distance.

For the tree above:

  • 1 is the root → HD 0.
  • 2 is 1's left child → HD -1.
  • 3 is 1's right child → HD +1.
  • 4 is 2's right child → HD 0 (one left, then one right, cancels out).
  • 5 is 3's right child → HD +2.
  • 6 is 4's left child → HD -1.
  • 7 is 5's left child → HD +1.

Grouping by HD:

HD Nodes at this HD Depth of each
-1 2, 6 1, 3
0 1, 4 0, 2
+1 3, 7 1, 3
+2 5 2

At HD -1, both 2 and 6 share the same vertical line, but 2 is closer to the root so it's the one that "wins" for the top view. Same story at HD 0 (1 beats 4) and HD +1 (3 beats 7).

So the problem really comes down to: for every distinct HD, find the shallowest node, then read those winners off from the smallest HD to the largest. Every approach below is a different way of deciding, at each HD, whether the node currently in hand should be allowed to claim that spot.

Setting Up the Tree

We'll use the tree from above throughout this article.

class TreeNode {
    int val;
    TreeNode left, right;

    TreeNode(int val) {
        this.val = val;
    }
}
public class SampleTree {
    public static TreeNode build() {
        TreeNode n1 = new TreeNode(1);
        TreeNode n2 = new TreeNode(2);
        TreeNode n3 = new TreeNode(3);
        TreeNode n4 = new TreeNode(4);
        TreeNode n5 = new TreeNode(5);
        TreeNode n6 = new TreeNode(6);
        TreeNode n7 = new TreeNode(7);

        n1.left = n2;
        n1.right = n3;
        n2.right = n4;
        n3.right = n5;
        n4.left = n6;
        n5.left = n7;

        return n1;
    }
}

Approach 1: The Naive Attempt (and Where It Breaks)

A natural first instinct: run a normal DFS, track each node's horizontal distance as you descend and write its value into a map keyed by HD overwriting whatever's already there. Once the traversal finishes, read the map off in order of HD.

This looks tempting because it's almost the same trick you'd reach for on the bottom view problem. The catch is that it quietly assumes the last node visited at a given HD is somehow the "right" one to keep and for top view, that assumption is backwards more often than it's right.

Tracing Through It

A preorder DFS (root, then left subtree, then right subtree) visits our tree in this order:

1 → 2 → 4 → 6 → 3 → 5 → 7

Overwriting the map at every visit:

Visit Node HD Map after this step
1 1 0 {0: 1}
2 2 -1 {0: 1, -1: 2}
3 4 0 {0: 4, -1: 2}
4 6 -1 {0: 4, -1: 6}
5 3 +1 {..., +1: 3}
6 5 +2 {..., +2: 5}
7 7 +1 {..., +1: 7}

By the end, three of the four positions are wrong. At HD 0, 4 (depth 2) has overwritten 1 (depth 0) even though 1 is the root and should obviously be visible from the top. At HD -1, 6 (depth 3) has overwritten 2 (depth 1) for the same reason. At HD +1, 7 (depth 3) has overwritten 3 (depth 1).

The naive output ends up as:

6, 4, 7, 5

nowhere close to the correct 2, 1, 3, 5. The root cause: nothing in this approach distinguishes "a node that's genuinely closer to the root" from "a node that simply got visited later in the traversal." DFS's visiting order and a node's actual depth are two very different things and this approach conflates them.

Approach 2: DFS With Depth Tracking (Correct)

The fix is straightforward once you've seen the bug: track each node's depth alongside its value and only let a new node claim an HD if it's strictly shallower than whatever's currently recorded there. A late-arriving deep node like 6 or 7 no longer gets to bulldoze a correct, shallower answer.

Tracing Through It

Same preorder traversal 1 → 2 → 4 → 6 → 3 → 5 → 7 now with depth-aware comparisons:

Visit Node (depth) HD Existing entry Overwrite? Map after this step
1 1 (0) 0 none add {0: (1, 0)}
2 2 (1) -1 none add {..., -1: (2, 1)}
3 4 (2) 0 (1, 0) 2 < 0 → no unchanged 1 survives
4 6 (3) -1 (2, 1) 3 < 1 → no unchanged 2 survives
5 3 (1) +1 none add {..., +1: (3, 1)}
6 5 (2) +2 none add {..., +2: (5, 2)}
7 7 (3) +1 (3, 1) 3 < 1 → no unchanged 3 survives

This time every deep latecomer checks the depth of the current occupant and backs off. Reading the map from the smallest HD to the largest gives us:

2, 1, 3, 5

the correct answer.


#include <bits/stdc++.h>
using namespace std;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int v) : val(v), left(nullptr), right(nullptr) {}
};

struct NodeInfo {
    int value;
    int depth;
};

void fillMap(TreeNode* node, int hd, int depth, map<int, NodeInfo>& hdMap) {
    if (node == nullptr) return;
    auto it = hdMap.find(hd);
    // Only claim this HD if we're strictly closer to the root
    // than whoever is currently recorded there
    if (it == hdMap.end() || depth < it->second.depth) {
        hdMap[hd] = {node->val, depth};
    }
    fillMap(node->left, hd - 1, depth + 1, hdMap);
    fillMap(node->right, hd + 1, depth + 1, hdMap);
}
vector<int> topView(TreeNode* root) {
    map<int, NodeInfo> hdMap;
    fillMap(root, 0, 0, hdMap);
    vector<int> result;
    for (auto& [hd, info] : hdMap) {
        result.push_back(info.value);
    }
    return result;
}
int main() {
    TreeNode* root = SampleTree::build();
    vector<int> result = topView(root);
    for (int v : result) cout << v << " ";
    cout << endl;
    // Output: 2 1 3 5
    return 0;
}

using System;
using System.Collections.Generic;

public class NodeInfo {
    public int Value;
    public int Depth;
    public NodeInfo(int value, int depth) {
        Value = value;
        Depth = depth;
    }
}
public class TopViewDFS {
    public static List<int> TopView(TreeNode root) {
        SortedDictionary<int, NodeInfo> hdMap = new SortedDictionary<int, NodeInfo>();
        FillMap(root, 0, 0, hdMap);
        List<int> result = new List<int>();
        foreach (var info in hdMap.Values) {
            result.Add(info.Value);
        }
        return result;
    }
    private static void FillMap(TreeNode node, int hd, int depth, SortedDictionary<int, NodeInfo> hdMap) {
        if (node == null) return;
        NodeInfo existing = hdMap.ContainsKey(hd) ? hdMap[hd] : null;
        // Only claim this HD if we're strictly closer to the root
        // than whoever is currently recorded there
        if (existing == null || depth < existing.Depth) {
            hdMap[hd] = new NodeInfo(node.val, depth);
        }
        FillMap(node.left, hd - 1, depth + 1, hdMap);
        FillMap(node.right, hd + 1, depth + 1, hdMap);
    }
    public static void Main(string[] args) {
        TreeNode root = SampleTree.Build();
        List<int> result = TopView(root);
        Console.WriteLine(string.Join(", ", result));
        // Output: 2, 1, 3, 5
    }
}

import java.util.*;

public class TopViewDFS {
    static class NodeInfo {
        int value;
        int depth;
        NodeInfo(int value, int depth) {
            this.value = value;
            this.depth = depth;
        }
    }
    public static List<Integer> topView(TreeNode root) {
        TreeMap<Integer, NodeInfo> hdMap = new TreeMap<>();
        fillMap(root, 0, 0, hdMap);
        List<Integer> result = new ArrayList<>();
        for (NodeInfo info : hdMap.values()) {
            result.add(info.value);
        }
        return result;
    }
    private static void fillMap(TreeNode node, int hd, int depth, TreeMap<Integer, NodeInfo> hdMap) {
        if (node == null) return;
        NodeInfo existing = hdMap.get(hd);
        // Only claim this HD if we're strictly closer to the root
        // than whoever is currently recorded there
        if (existing == null || depth < existing.depth) {
            hdMap.put(hd, new NodeInfo(node.val, depth));
        }
        fillMap(node.left, hd - 1, depth + 1, hdMap);
        fillMap(node.right, hd + 1, depth + 1, hdMap);
    }
    public static void main(String[] args) {
        TreeNode root = SampleTree.build();
        System.out.println(topView(root));
        // Output: [2, 1, 3, 5]
    }
}

class NodeInfo:
    def __init__(self, value, depth):
        self.value = value
        self.depth = depth

def top_view(root):
    hd_map = {}
    fill_map(root, 0, 0, hd_map)
    result = []
    for hd in sorted(hd_map.keys()):
        result.append(hd_map[hd].value)
    return result

def fill_map(node, hd, depth, hd_map):
    if node is None:
        return
    existing = hd_map.get(hd)
    # Only claim this HD if we're strictly closer to the root
    # than whoever is currently recorded there
    if existing is None or depth < existing.depth:
        hd_map[hd] = NodeInfo(node.val, depth)
    fill_map(node.left, hd - 1, depth + 1, hd_map)
    fill_map(node.right, hd + 1, depth + 1, hd_map)

if __name__ == "__main__":
    root = SampleTree.build()
    result = top_view(root)
    print(result)
    # Output: [2, 1, 3, 5]

Complexity

Value
Time O(n log w) each of the n nodes does a TreeMap lookup and possibly an insert, each O(log w), where w is the number of distinct horizontal distances (the tree's width)
Space O(h) for the recursion stack (h = tree height) plus O(w) for the map

This is correct, but notice we only needed the depth field to patch a problem that DFS's traversal order created in the first place. That's usually worth a second look a different traversal might make the whole comparison unnecessary.

Approach 3: BFS / Level Order Traversal (Optimal)

Here's the mirror image of what made the bottom view problem's BFS solution elegant. In that problem, we wanted the deepest node at each HD and BFS's guarantee shallower levels are always fully processed before deeper ones meant we could safely overwrite the map unconditionally, since later writes were always at least as deep.

For top view, we want the shallowest node instead. The same BFS guarantee flips the logic: since shallower levels are always visited first, the first time we see a given HD, we're already looking at the shallowest possible node for that position. So instead of overwriting, we do the opposite we add an entry only if that HD hasn't been claimed yet and simply ignore every later arrival.

Tracing Through It

Level order traversal visits our tree level by level, left to right:

1 → 2 → 3 → 4 → 5 → 6 → 7

Adding to the map only when the HD hasn't been seen before:

Visit Node HD Already claimed? Map after this step
1 1 0 no → add {0: 1}
2 2 -1 no → add {..., -1: 2}
3 3 +1 no → add {..., +1: 3}
4 4 0 yes → skip unchanged
5 5 +2 no → add {..., +2: 5}
6 6 -1 yes → skip unchanged
7 7 +1 yes → skip unchanged

No depth field, no comparisons just "have we already got an answer for this column?" Final result, read left to right by HD:

2, 1, 3, 5
 
#include <bits/stdc++.h>
using namespace std;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int v) : val(v), left(nullptr), right(nullptr) {}
};
struct QueueEntry {
    TreeNode* node;
    int hd;
};

vector<int> topView(TreeNode* root) {
    map<int, int> hdMap;
    if (root == nullptr) return {};
    queue<QueueEntry> q;
    q.push({root, 0});
    while (!q.empty()) {
        QueueEntry current = q.front();
        q.pop();
        TreeNode* node = current.node;
        int hd = current.hd;
        // Claim this HD only the first time we see it. BFS
        // guarantees that first sighting is always the shallowest
        if (hdMap.find(hd) == hdMap.end()) {
            hdMap[hd] = node->val;
        }
        if (node->left != nullptr) {
            q.push({node->left, hd - 1});
        }
        if (node->right != nullptr) {
            q.push({node->right, hd + 1});
        }
    }
    vector<int> result;
    for (auto& [hd, val] : hdMap) {
        result.push_back(val);
    }
    return result;
}

int main() {
    TreeNode* root = SampleTree::build();
    vector<int> result = topView(root);
    for (int v : result) cout << v << " ";
    cout << endl;
    // Output: 2 1 3 5
    return 0;
}
 
using System;
using System.Collections.Generic;

public class QueueEntry {
    public TreeNode Node;
    public int Hd;
    public QueueEntry(TreeNode node, int hd) {
        Node = node;
        Hd = hd;
    }
}
public class TopViewBFS {
    public static List<int> TopView(TreeNode root) {
        SortedDictionary<int, int> hdMap = new SortedDictionary<int, int>();
        if (root == null) return new List<int>();
        Queue<QueueEntry> queue = new Queue<QueueEntry>();
        queue.Enqueue(new QueueEntry(root, 0));
        while (queue.Count > 0) {
            QueueEntry current = queue.Dequeue();
            TreeNode node = current.Node;
            int hd = current.Hd;
            // Claim this HD only the first time we see it. BFS
            // guarantees that first sighting is always the shallowest
            if (!hdMap.ContainsKey(hd)) {
                hdMap[hd] = node.val;
            }
            if (node.left != null) {
                queue.Enqueue(new QueueEntry(node.left, hd - 1));
            }
            if (node.right != null) {
                queue.Enqueue(new QueueEntry(node.right, hd + 1));
            }
        }
        return new List<int>(hdMap.Values);
    }
    public static void Main(string[] args) {
        TreeNode root = SampleTree.Build();
        List<int> result = TopView(root);
        Console.WriteLine(string.Join(", ", result));
        // Output: 2, 1, 3, 5
    }
}
 
import java.util.*;
public class TopViewBFS {
    static class QueueEntry {
        TreeNode node;
        int hd;
        QueueEntry(TreeNode node, int hd) {
            this.node = node;
            this.hd = hd;
        }
    }
    public static List<Integer> topView(TreeNode root) {
        TreeMap<Integer, Integer> hdMap = new TreeMap<>();
        if (root == null) return new ArrayList<>();
        Queue<QueueEntry> queue = new LinkedList<>();
        queue.add(new QueueEntry(root, 0));
        while (!queue.isEmpty()) {
            QueueEntry current = queue.poll();
            TreeNode node = current.node;
            int hd = current.hd;
            // Claim this HD only the first time we see it BFS
            // guarantees that first sighting is always the shallowest
            if (!hdMap.containsKey(hd)) {
                hdMap.put(hd, node.val);
            }
            if (node.left != null) {
                queue.add(new QueueEntry(node.left, hd - 1));
            }
            if (node.right != null) {
                queue.add(new QueueEntry(node.right, hd + 1));
            }
        }
        return new ArrayList<>(hdMap.values());
    }
    public static void main(String[] args) {
        TreeNode root = SampleTree.build();
        System.out.println(topView(root));
        // Output: [2, 1, 3, 5]
    }
}
 
from collections import deque

class QueueEntry:
    def __init__(self, node, hd):
        self.node = node
        self.hd = hd

def top_view(root):
    hd_map = {}
    if root is None:
        return []
    queue = deque([QueueEntry(root, 0)])
    while queue:
        current = queue.popleft()
        node = current.node
        hd = current.hd
        # Claim this HD only the first time we see it. BFS
        # guarantees that first sighting is always the shallowest
        if hd not in hd_map:
            hd_map[hd] = node.val
        if node.left is not None:
            queue.append(QueueEntry(node.left, hd - 1))
        if node.right is not None:
            queue.append(QueueEntry(node.right, hd + 1))
    return [hd_map[hd] for hd in sorted(hd_map.keys())]

if __name__ == "__main__":
    root = SampleTree.build()
    result = top_view(root)
    print(result)
    # Output: [2, 1, 3, 5]

Complexity

Value
Time O(n log w) same asymptotic cost as Approach 2, since each node still does one TreeMap operation, but the per-node logic is simpler (a single existence check, no comparison)
Space O(n) for the queue in the worst case, plus O(w) for the map

Comparing All Approaches

Approach Time Complexity Space Complexity Core Idea
Naive DFS (buggy) O(n log w) O(h) + O(w) Overwrite the map on every visit breaks because a deeper node can be visited after a shallower one
DFS with Depth Tracking O(n log w) O(h) + O(w) Overwrite only when the new node is strictly closer to the root
BFS / Level Order Optimal O(n log w) O(n) + O(w) Claim an HD only the first time it's seen BFS guarantees that first sighting is always the shallowest

n = number of nodes, h = height of the tree, w = width of the tree (number of distinct horizontal distances).

If you've read a "bottom view" writeup before, you'll notice the optimal BFS logic here is the exact opposite: bottom view overwrites unconditionally to always keep the last (deepest) node seen at each HD, while top view adds only-if-absent to always keep the first (shallowest) one. Same traversal, same map, opposite decision rule.

Just like with bottom view, you can push the time complexity down to a strict O(n) by replacing the TreeMap with a plain array sized to the tree's width, indexing directly by the horizontal distance (shifted by an offset so it's never negative) instead of paying O(log w) per map operation.

Key Takeaways

  1. A node visited later isn't automatically "more important." The naive DFS attempt fails because it silently assumes recency in traversal order means something meaningful it doesn't.
  2. Top view and bottom view are mirror images of the same idea. Both hinge on horizontal distance; the only real difference is whether you're keeping the shallowest node or the deepest one at each position.
  3. BFS removes the need for bookkeeping, it doesn't just add speed. The DFS solution needs a depth field and a comparison to stay correct; BFS's traversal order makes that comparison redundant entirely.
  4. This pattern extends directly to other tree-view problems. Left view, right view and vertical order traversal are all built on the same horizontal-distance-plus-traversal-order foundation covered here.

Frequently Asked Questions

1. What is the difference between the top view and bottom view of a binary tree?

Both group nodes by horizontal distance from the root, but top view keeps the shallowest node at each horizontal distance, while bottom view keeps the deepest one. A node that appears in one view may not appear in the other if it's hidden behind a node further up or down its column.

2. What is horizontal distance in a binary tree?

It's a running offset that starts at 0 for the root, decreases by 1 for every step to a left child and increases by 1 for every step to a right child. Nodes sharing the same horizontal distance sit on the same imaginary vertical line.

3. Can the top view of a binary tree be solved using DFS?

Yes, but a plain DFS needs to track each node's depth and only update a horizontal distance's entry when a shallower node is found otherwise it can incorrectly let a deeper node overwrite the correct shallower one. BFS avoids this extra bookkeeping entirely.

4. Why is BFS considered the optimal approach for top view?

Because BFS visits nodes level by level, the first time any horizontal distance is encountered during a BFS traversal, it's guaranteed to be the shallowest node at that position no depth comparison is required.

5. What is the time complexity of finding the top view of a binary tree?

Using a TreeMap keyed by horizontal distance, it's O(n log w), where n is the number of nodes and w is the tree's width. Replacing the TreeMap with an offset-indexed array brings it down to O(n).

6. Is top view the same as vertical order traversal?

No. Vertical order traversal returns every node grouped by horizontal distance (and typically by depth within each column), while top view returns only a single winning node per horizontal distance the shallowest one.

Related Articles

Responses (0)

Write a response

CommentHide Comments

No Comments yet.

"},"4":{"id":4,"name":"ZEBRONICS Blanc mouse ad","otherData":"{}","contentFormat":2,"content":"
Sponsored -53%
Zebronics #1 Best Seller

ZEBRONICS Blanc Slim Wireless Mouse — Rechargeable, BT + 2.4GHz (Black)

Up to 1600 DPI · Silent clicks · 63g · Multicolor LED

★★★★★ 4.0 (9,512) 5K+ bought last month
₹376 M.R.P. ₹799Save ₹423
Buy Now
"},"2":{"id":2,"name":"Crousal Ads","otherData":"{}","contentFormat":2,"content":"
Sponsored -34%
iQOO Amazon's Choice

iQOO Z10 Lite 5G — Cyber Green, 4GB RAM, 128GB Storage

Dimensity 6300 · 50MP Sony AI Camera · 6000 mAh · IP64

★★★★★ 4.0 (2,052) 500+ bought last month
₹18,997 M.R.P. ₹28,999Save ₹10,002
Buy Now
"},"1":{"id":1,"name":"Banner Ads","otherData":"{}","contentFormat":2,"content":"\n
\n \n \n \"Amazon\n \n
"}}},"blogDetails":{"isWriter":false,"likes":0,"isLikedByUser":false,"tagIds":[21,27,32,43,133,177,282,316,317],"tags":[{"id":21,"name":"Tree","maskingName":"tree","isFeatured":false},{"id":27,"name":"Binary Tree","maskingName":"binary-tree","isFeatured":false},{"id":32,"name":"B-Tree","maskingName":"b-tree","isFeatured":false},{"id":43,"name":"HashMap","maskingName":"hashmap","isFeatured":true},{"id":133,"name":"Coding Problems","maskingName":"coding-problems","isFeatured":true},{"id":177,"name":"DSA","maskingName":"dsa","isFeatured":true},{"id":282,"name":"TreeMap","maskingName":"treemap","isFeatured":false},{"id":316,"name":"DFS","maskingName":"depth-first-search","isFeatured":false},{"id":317,"name":"BFS","maskingName":"breadth-first-search","isFeatured":false}],"comments":[],"bookmark":{"isBookmarked":false,"count":0},"author":{"userId":"MjlfNF84LVsyXTJuLXRDX0FOZ2VfX0l0","name":"DevSniper"},"viewCount":11,"showBannerImage":false,"seoTags":"Top View of Binary Tree, Binary Tree Top View, Top View Binary Tree BFS, Top View Binary Tree DFS, Binary Tree Problems, Tree Traversal, BFS, DFS, Data Structures and Algorithms, DSA Interview Questions, Binary Tree Interview Questions, Coding Problems, Tree View Problems","content":"

If you've spent any time prepping for interviews at product-based companies, you've probably noticed that binary tree \"view\" problems top view, bottom view, left view, right view show up constantly. They look deceptively simple on a whiteboard, but the moment you start coding one under interview pressure, it's easy to write something that looks right, passes on the example the interviewer drew and then quietly falls apart on a slightly different tree shape. This article walks through exactly that journey for the top view problem: a first attempt that seems reasonable, why it breaks and how to arrive at a clean, optimal fix.

\n

Problem Statement

\n

You are given the root of a binary tree. Imagine standing far above the tree and looking straight down the top view is the set of nodes you'd actually be able to see from that angle.

\n

More precisely: for every horizontal position in the tree, the top view keeps only the node that's closest to the root at that position. Any node hidden underneath a shallower node at the same horizontal position is left out.

\n

Given the root of a binary tree, return its top view as a list of values, read from left to right.

\n

For example, for a tree shaped like this:

\n
              1\n            /   \\\n           2     3\n            \\     \\\n             4     5\n            /     /\n           6     7\n
\n

The top view is:

\n
2, 1, 3, 5\n
\n

Understanding the Problem First

\n

The key concept here is horizontal distance (HD) the same idea that underlies most binary tree \"view\" problems, so it's worth being precise about it once and reusing it everywhere.

\n

Draw a vertical line straight down through the root call that position 0. Every time you move to a left child, you shift one step left (-1), every move to a right child shifts one step right (+1). That running total is the node's horizontal distance.

\n

For the tree above:

\n\n

Grouping by HD:

\n
\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
HDNodes at this HDDepth of each
-12, 61, 3
01, 40, 2
+13, 71, 3
+252
\n
\n

At HD -1, both 2 and 6 share the same vertical line, but 2 is closer to the root so it's the one that \"wins\" for the top view. Same story at HD 0 (1 beats 4) and HD +1 (3 beats 7).

\n

So the problem really comes down to: for every distinct HD, find the shallowest node, then read those winners off from the smallest HD to the largest. Every approach below is a different way of deciding, at each HD, whether the node currently in hand should be allowed to claim that spot.

\n

Setting Up the Tree

\n

We'll use the tree from above throughout this article.

\n
class TreeNode {\n    int val;\n    TreeNode left, right;\n\n    TreeNode(int val) {\n        this.val = val;\n    }\n}\n
\n
public class SampleTree {\n    public static TreeNode build() {\n        TreeNode n1 = new TreeNode(1);\n        TreeNode n2 = new TreeNode(2);\n        TreeNode n3 = new TreeNode(3);\n        TreeNode n4 = new TreeNode(4);\n        TreeNode n5 = new TreeNode(5);\n        TreeNode n6 = new TreeNode(6);\n        TreeNode n7 = new TreeNode(7);\n\n        n1.left = n2;\n        n1.right = n3;\n        n2.right = n4;\n        n3.right = n5;\n        n4.left = n6;\n        n5.left = n7;\n\n        return n1;\n    }\n}\n
\n

Approach 1: The Naive Attempt (and Where It Breaks)

\n

A natural first instinct: run a normal DFS, track each node's horizontal distance as you descend and write its value into a map keyed by HD overwriting whatever's already there. Once the traversal finishes, read the map off in order of HD.

\n

This looks tempting because it's almost the same trick you'd reach for on the bottom view problem. The catch is that it quietly assumes the last node visited at a given HD is somehow the \"right\" one to keep and for top view, that assumption is backwards more often than it's right.

\n

Tracing Through It

\n

A preorder DFS (root, then left subtree, then right subtree) visits our tree in this order:

\n
1 → 2 → 4 → 6 → 3 → 5 → 7\n
\n

Overwriting the map at every visit:

\n
\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
VisitNodeHDMap after this step
110{0: 1}
22-1{0: 1, -1: 2}
340{0: 4, -1: 2}
46-1{0: 4, -1: 6}
53+1{..., +1: 3}
65+2{..., +2: 5}
77+1{..., +1: 7}
\n
\n

By the end, three of the four positions are wrong. At HD 0, 4 (depth 2) has overwritten 1 (depth 0) even though 1 is the root and should obviously be visible from the top. At HD -1, 6 (depth 3) has overwritten 2 (depth 1) for the same reason. At HD +1, 7 (depth 3) has overwritten 3 (depth 1).

\n

The naive output ends up as:

\n
6, 4, 7, 5\n
\n

nowhere close to the correct 2, 1, 3, 5. The root cause: nothing in this approach distinguishes \"a node that's genuinely closer to the root\" from \"a node that simply got visited later in the traversal.\" DFS's visiting order and a node's actual depth are two very different things and this approach conflates them.

\n

Approach 2: DFS With Depth Tracking (Correct)

\n

The fix is straightforward once you've seen the bug: track each node's depth alongside its value and only let a new node claim an HD if it's strictly shallower than whatever's currently recorded there. A late-arriving deep node like 6 or 7 no longer gets to bulldoze a correct, shallower answer.

\n

Tracing Through It

\n

Same preorder traversal 1 → 2 → 4 → 6 → 3 → 5 → 7 now with depth-aware comparisons:

\n
\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
VisitNode (depth)HDExisting entryOverwrite?Map after this step
11 (0)0noneadd{0: (1, 0)}
22 (1)-1noneadd{..., -1: (2, 1)}
34 (2)0(1, 0)2 < 0 → nounchanged 1 survives
46 (3)-1(2, 1)3 < 1 → nounchanged 2 survives
53 (1)+1noneadd{..., +1: (3, 1)}
65 (2)+2noneadd{..., +2: (5, 2)}
77 (3)+1(3, 1)3 < 1 → nounchanged 3 survives
\n
\n

This time every deep latecomer checks the depth of the current occupant and backs off. Reading the map from the smallest HD to the largest gives us:

\n
2, 1, 3, 5\n
\n

the correct answer.

\n
\n#include <bits/stdc++.h>\nusing namespace std;\n\nstruct TreeNode {\n    int val;\n    TreeNode* left;\n    TreeNode* right;\n    TreeNode(int v) : val(v), left(nullptr), right(nullptr) {}\n};\n\nstruct NodeInfo {\n    int value;\n    int depth;\n};\n\nvoid fillMap(TreeNode* node, int hd, int depth, map<int, NodeInfo>& hdMap) {\n    if (node == nullptr) return;\n    auto it = hdMap.find(hd);\n    // Only claim this HD if we're strictly closer to the root\n    // than whoever is currently recorded there\n    if (it == hdMap.end() || depth < it->second.depth) {\n        hdMap[hd] = {node->val, depth};\n    }\n    fillMap(node->left, hd - 1, depth + 1, hdMap);\n    fillMap(node->right, hd + 1, depth + 1, hdMap);\n}\nvector<int> topView(TreeNode* root) {\n    map<int, NodeInfo> hdMap;\n    fillMap(root, 0, 0, hdMap);\n    vector<int> result;\n    for (auto& [hd, info] : hdMap) {\n        result.push_back(info.value);\n    }\n    return result;\n}\nint main() {\n    TreeNode* root = SampleTree::build();\n    vector<int> result = topView(root);\n    for (int v : result) cout << v << \" \";\n    cout << endl;\n    // Output: 2 1 3 5\n    return 0;\n}\n
\nusing System;\nusing System.Collections.Generic;\n\npublic class NodeInfo {\n    public int Value;\n    public int Depth;\n    public NodeInfo(int value, int depth) {\n        Value = value;\n        Depth = depth;\n    }\n}\npublic class TopViewDFS {\n    public static List<int> TopView(TreeNode root) {\n        SortedDictionary<int, NodeInfo> hdMap = new SortedDictionary<int, NodeInfo>();\n        FillMap(root, 0, 0, hdMap);\n        List<int> result = new List<int>();\n        foreach (var info in hdMap.Values) {\n            result.Add(info.Value);\n        }\n        return result;\n    }\n    private static void FillMap(TreeNode node, int hd, int depth, SortedDictionary<int, NodeInfo> hdMap) {\n        if (node == null) return;\n        NodeInfo existing = hdMap.ContainsKey(hd) ? hdMap[hd] : null;\n        // Only claim this HD if we're strictly closer to the root\n        // than whoever is currently recorded there\n        if (existing == null || depth < existing.Depth) {\n            hdMap[hd] = new NodeInfo(node.val, depth);\n        }\n        FillMap(node.left, hd - 1, depth + 1, hdMap);\n        FillMap(node.right, hd + 1, depth + 1, hdMap);\n    }\n    public static void Main(string[] args) {\n        TreeNode root = SampleTree.Build();\n        List<int> result = TopView(root);\n        Console.WriteLine(string.Join(\", \", result));\n        // Output: 2, 1, 3, 5\n    }\n}\n
\nimport java.util.*;\n\npublic class TopViewDFS {\n    static class NodeInfo {\n        int value;\n        int depth;\n        NodeInfo(int value, int depth) {\n            this.value = value;\n            this.depth = depth;\n        }\n    }\n    public static List<Integer> topView(TreeNode root) {\n        TreeMap<Integer, NodeInfo> hdMap = new TreeMap<>();\n        fillMap(root, 0, 0, hdMap);\n        List<Integer> result = new ArrayList<>();\n        for (NodeInfo info : hdMap.values()) {\n            result.add(info.value);\n        }\n        return result;\n    }\n    private static void fillMap(TreeNode node, int hd, int depth, TreeMap<Integer, NodeInfo> hdMap) {\n        if (node == null) return;\n        NodeInfo existing = hdMap.get(hd);\n        // Only claim this HD if we're strictly closer to the root\n        // than whoever is currently recorded there\n        if (existing == null || depth < existing.depth) {\n            hdMap.put(hd, new NodeInfo(node.val, depth));\n        }\n        fillMap(node.left, hd - 1, depth + 1, hdMap);\n        fillMap(node.right, hd + 1, depth + 1, hdMap);\n    }\n    public static void main(String[] args) {\n        TreeNode root = SampleTree.build();\n        System.out.println(topView(root));\n        // Output: [2, 1, 3, 5]\n    }\n}\n
\nclass NodeInfo:\n    def __init__(self, value, depth):\n        self.value = value\n        self.depth = depth\n\ndef top_view(root):\n    hd_map = {}\n    fill_map(root, 0, 0, hd_map)\n    result = []\n    for hd in sorted(hd_map.keys()):\n        result.append(hd_map[hd].value)\n    return result\n\ndef fill_map(node, hd, depth, hd_map):\n    if node is None:\n        return\n    existing = hd_map.get(hd)\n    # Only claim this HD if we're strictly closer to the root\n    # than whoever is currently recorded there\n    if existing is None or depth < existing.depth:\n        hd_map[hd] = NodeInfo(node.val, depth)\n    fill_map(node.left, hd - 1, depth + 1, hd_map)\n    fill_map(node.right, hd + 1, depth + 1, hd_map)\n\nif __name__ == \"__main__\":\n    root = SampleTree.build()\n    result = top_view(root)\n    print(result)\n    # Output: [2, 1, 3, 5]\n
\n

Complexity

\n
\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
Value
TimeO(n log w) each of the n nodes does a TreeMap lookup and possibly an insert, each O(log w), where w is the number of distinct horizontal distances (the tree's width)
SpaceO(h) for the recursion stack (h = tree height) plus O(w) for the map
\n
\n

This is correct, but notice we only needed the depth field to patch a problem that DFS's traversal order created in the first place. That's usually worth a second look a different traversal might make the whole comparison unnecessary.

\n

Approach 3: BFS / Level Order Traversal (Optimal)

\n

Here's the mirror image of what made the bottom view problem's BFS solution elegant. In that problem, we wanted the deepest node at each HD and BFS's guarantee shallower levels are always fully processed before deeper ones meant we could safely overwrite the map unconditionally, since later writes were always at least as deep.

\n

For top view, we want the shallowest node instead. The same BFS guarantee flips the logic: since shallower levels are always visited first, the first time we see a given HD, we're already looking at the shallowest possible node for that position. So instead of overwriting, we do the opposite we add an entry only if that HD hasn't been claimed yet and simply ignore every later arrival.

\n

Tracing Through It

\n

Level order traversal visits our tree level by level, left to right:

\n
1 → 2 → 3 → 4 → 5 → 6 → 7\n
\n

Adding to the map only when the HD hasn't been seen before:

\n
\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
VisitNodeHDAlready claimed?Map after this step
110no → add{0: 1}
22-1no → add{..., -1: 2}
33+1no → add{..., +1: 3}
440yes → skipunchanged
55+2no → add{..., +2: 5}
66-1yes → skipunchanged
77+1yes → skipunchanged
\n
\n

No depth field, no comparisons just \"have we already got an answer for this column?\" Final result, read left to right by HD:

\n
2, 1, 3, 5\n
\n
 \n#include <bits/stdc++.h>\nusing namespace std;\n\nstruct TreeNode {\n    int val;\n    TreeNode* left;\n    TreeNode* right;\n    TreeNode(int v) : val(v), left(nullptr), right(nullptr) {}\n};\nstruct QueueEntry {\n    TreeNode* node;\n    int hd;\n};\n\nvector<int> topView(TreeNode* root) {\n    map<int, int> hdMap;\n    if (root == nullptr) return {};\n    queue<QueueEntry> q;\n    q.push({root, 0});\n    while (!q.empty()) {\n        QueueEntry current = q.front();\n        q.pop();\n        TreeNode* node = current.node;\n        int hd = current.hd;\n        // Claim this HD only the first time we see it. BFS\n        // guarantees that first sighting is always the shallowest\n        if (hdMap.find(hd) == hdMap.end()) {\n            hdMap[hd] = node->val;\n        }\n        if (node->left != nullptr) {\n            q.push({node->left, hd - 1});\n        }\n        if (node->right != nullptr) {\n            q.push({node->right, hd + 1});\n        }\n    }\n    vector<int> result;\n    for (auto& [hd, val] : hdMap) {\n        result.push_back(val);\n    }\n    return result;\n}\n\nint main() {\n    TreeNode* root = SampleTree::build();\n    vector<int> result = topView(root);\n    for (int v : result) cout << v << \" \";\n    cout << endl;\n    // Output: 2 1 3 5\n    return 0;\n}\n
 \nusing System;\nusing System.Collections.Generic;\n\npublic class QueueEntry {\n    public TreeNode Node;\n    public int Hd;\n    public QueueEntry(TreeNode node, int hd) {\n        Node = node;\n        Hd = hd;\n    }\n}\npublic class TopViewBFS {\n    public static List<int> TopView(TreeNode root) {\n        SortedDictionary<int, int> hdMap = new SortedDictionary<int, int>();\n        if (root == null) return new List<int>();\n        Queue<QueueEntry> queue = new Queue<QueueEntry>();\n        queue.Enqueue(new QueueEntry(root, 0));\n        while (queue.Count > 0) {\n            QueueEntry current = queue.Dequeue();\n            TreeNode node = current.Node;\n            int hd = current.Hd;\n            // Claim this HD only the first time we see it. BFS\n            // guarantees that first sighting is always the shallowest\n            if (!hdMap.ContainsKey(hd)) {\n                hdMap[hd] = node.val;\n            }\n            if (node.left != null) {\n                queue.Enqueue(new QueueEntry(node.left, hd - 1));\n            }\n            if (node.right != null) {\n                queue.Enqueue(new QueueEntry(node.right, hd + 1));\n            }\n        }\n        return new List<int>(hdMap.Values);\n    }\n    public static void Main(string[] args) {\n        TreeNode root = SampleTree.Build();\n        List<int> result = TopView(root);\n        Console.WriteLine(string.Join(\", \", result));\n        // Output: 2, 1, 3, 5\n    }\n}\n
 \nimport java.util.*;\npublic class TopViewBFS {\n    static class QueueEntry {\n        TreeNode node;\n        int hd;\n        QueueEntry(TreeNode node, int hd) {\n            this.node = node;\n            this.hd = hd;\n        }\n    }\n    public static List<Integer> topView(TreeNode root) {\n        TreeMap<Integer, Integer> hdMap = new TreeMap<>();\n        if (root == null) return new ArrayList<>();\n        Queue<QueueEntry> queue = new LinkedList<>();\n        queue.add(new QueueEntry(root, 0));\n        while (!queue.isEmpty()) {\n            QueueEntry current = queue.poll();\n            TreeNode node = current.node;\n            int hd = current.hd;\n            // Claim this HD only the first time we see it BFS\n            // guarantees that first sighting is always the shallowest\n            if (!hdMap.containsKey(hd)) {\n                hdMap.put(hd, node.val);\n            }\n            if (node.left != null) {\n                queue.add(new QueueEntry(node.left, hd - 1));\n            }\n            if (node.right != null) {\n                queue.add(new QueueEntry(node.right, hd + 1));\n            }\n        }\n        return new ArrayList<>(hdMap.values());\n    }\n    public static void main(String[] args) {\n        TreeNode root = SampleTree.build();\n        System.out.println(topView(root));\n        // Output: [2, 1, 3, 5]\n    }\n}\n
 \nfrom collections import deque\n\nclass QueueEntry:\n    def __init__(self, node, hd):\n        self.node = node\n        self.hd = hd\n\ndef top_view(root):\n    hd_map = {}\n    if root is None:\n        return []\n    queue = deque([QueueEntry(root, 0)])\n    while queue:\n        current = queue.popleft()\n        node = current.node\n        hd = current.hd\n        # Claim this HD only the first time we see it. BFS\n        # guarantees that first sighting is always the shallowest\n        if hd not in hd_map:\n            hd_map[hd] = node.val\n        if node.left is not None:\n            queue.append(QueueEntry(node.left, hd - 1))\n        if node.right is not None:\n            queue.append(QueueEntry(node.right, hd + 1))\n    return [hd_map[hd] for hd in sorted(hd_map.keys())]\n\nif __name__ == \"__main__\":\n    root = SampleTree.build()\n    result = top_view(root)\n    print(result)\n    # Output: [2, 1, 3, 5]\n
\n

Complexity

\n
\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
Value
TimeO(n log w) same asymptotic cost as Approach 2, since each node still does one TreeMap operation, but the per-node logic is simpler (a single existence check, no comparison)
SpaceO(n) for the queue in the worst case, plus O(w) for the map
\n
\n

Comparing All Approaches

\n
\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
ApproachTime ComplexitySpace ComplexityCore Idea
Naive DFS (buggy)O(n log w)O(h) + O(w)Overwrite the map on every visit breaks because a deeper node can be visited after a shallower one
DFS with Depth TrackingO(n log w)O(h) + O(w)Overwrite only when the new node is strictly closer to the root
BFS / Level Order OptimalO(n log w)O(n) + O(w)Claim an HD only the first time it's seen BFS guarantees that first sighting is always the shallowest
\n
\n

n = number of nodes, h = height of the tree, w = width of the tree (number of distinct horizontal distances).

\n

If you've read a \"bottom view\" writeup before, you'll notice the optimal BFS logic here is the exact opposite: bottom view overwrites unconditionally to always keep the last (deepest) node seen at each HD, while top view adds only-if-absent to always keep the first (shallowest) one. Same traversal, same map, opposite decision rule.

\n

Just like with bottom view, you can push the time complexity down to a strict O(n) by replacing the TreeMap with a plain array sized to the tree's width, indexing directly by the horizontal distance (shifted by an offset so it's never negative) instead of paying O(log w) per map operation.

\n

Key Takeaways

\n
    \n
  1. A node visited later isn't automatically \"more important.\" The naive DFS attempt fails because it silently assumes recency in traversal order means something meaningful it doesn't.
  2. \n
  3. Top view and bottom view are mirror images of the same idea. Both hinge on horizontal distance; the only real difference is whether you're keeping the shallowest node or the deepest one at each position.
  4. \n
  5. BFS removes the need for bookkeeping, it doesn't just add speed. The DFS solution needs a depth field and a comparison to stay correct; BFS's traversal order makes that comparison redundant entirely.
  6. \n
  7. This pattern extends directly to other tree-view problems. Left view, right view and vertical order traversal are all built on the same horizontal-distance-plus-traversal-order foundation covered here.
  8. \n
\n

Frequently Asked Questions

\n
\n

1. What is the difference between the top view and bottom view of a binary tree?

\n

Both group nodes by horizontal distance from the root, but top view keeps the shallowest node at each horizontal distance, while bottom view keeps the deepest one. A node that appears in one view may not appear in the other if it's hidden behind a node further up or down its column.

\n

2. What is horizontal distance in a binary tree?

\n

It's a running offset that starts at 0 for the root, decreases by 1 for every step to a left child and increases by 1 for every step to a right child. Nodes sharing the same horizontal distance sit on the same imaginary vertical line.

\n

3. Can the top view of a binary tree be solved using DFS?

\n

Yes, but a plain DFS needs to track each node's depth and only update a horizontal distance's entry when a shallower node is found otherwise it can incorrectly let a deeper node overwrite the correct shallower one. BFS avoids this extra bookkeeping entirely.

\n

4. Why is BFS considered the optimal approach for top view?

\n

Because BFS visits nodes level by level, the first time any horizontal distance is encountered during a BFS traversal, it's guaranteed to be the shallowest node at that position no depth comparison is required.

\n

5. What is the time complexity of finding the top view of a binary tree?

\n

Using a TreeMap keyed by horizontal distance, it's O(n log w), where n is the number of nodes and w is the tree's width. Replacing the TreeMap with an offset-indexed array brings it down to O(n).

\n

6. Is top view the same as vertical order traversal?

\n

No. Vertical order traversal returns every node grouped by horizontal distance (and typically by depth within each column), while top view returns only a single winning node per horizontal distance the shallowest one.

\n
\n

Related Articles

\n
\n

Bottom View of a Binary Tree

\n

Left View of a Binary Tree

\n

Right View of a Binary Tree

\n
","categoryId":177,"subCategoryId":177,"contentFormat":5,"blogId":205,"userId":"MjlfNF84LVsyXTJuLXRDX0FOZ2VfX0l0","title":"Top View of a Binary Tree Using BFS and DFS | Complete Guide","url":"top-view-of-a-binary-tree","bannerImage":"","seoDescription":"Learn how to find the top view of a binary tree using DFS and BFS with step-by-step explanations, examples, code, complexity analysis and interview insights.","generatedOn":"2026-08-28T10:00:29","updatedOn":"2026-08-28T10:00:29"},"popularContents":[{"id":197,"title":"My Adobe SDE Interview Experience (Aug 2026) 5 Rounds, Selected","url":"my-adobe-sde-interview-experience-aug-2026-5-rounds-selected","description":null,"seoDescription":"Real Adobe SDE interview: 5 rounds, 4 DSA problems (Rotate Array, BSTs, Kth Smallest Matrix), code review & behavioral round. Full solutions + tips.","contentType":5,"generatedOn":"2026-10-14T22:53:55.4906309Z","viewCount":0},{"id":168,"title":"Amazon SDE-2 Interview Experience (3 Years Experience)","url":"amazon-sde-2-interview-experience-3-years-experience","description":null,"seoDescription":" Read a real Amazon SDE-2 interview experience covering the online assessment, coding rounds, object-oriented design, leadership principles and system design.","contentType":5,"generatedOn":"2026-10-14T22:53:55.4906274Z","viewCount":0},{"id":167,"title":"Meesho SDE-1 Online Assessment Interview Experience (Remote) - Rejected","url":"meesho-sde-1-online-assessment-interview-experience-remote-rejected","description":null,"seoDescription":"Read a real Meesho SDE-1 online assessment experience with coding questions, DSA topics, solutions, difficulty level, preparation tips and interview insights.","contentType":5,"generatedOn":"2026-10-14T22:53:55.4906256Z","viewCount":0},{"id":135,"title":"Spinny SDE-1 Interview Experience (Selected)","url":"spinny-sde-1-interview-experience-selected","description":null,"seoDescription":"Spinny SDE-1 Interview Experience (Selected) | 4 Rounds Breakdown: Coding, LLD, Java, SQL + Real Interview Questions","contentType":5,"generatedOn":"2026-10-14T22:53:55.4906151Z","viewCount":0},{"id":166,"title":"System Design Interview – BIGGEST Mistakes to Avoid","url":"system-design-interview-biggest-mistakes-to-avoid","description":null,"seoDescription":"Learn the biggest mistakes to avoid in a system design interview, from unclear requirements to poor trade-off analysis. Includes real-world cases, advanced insights and examples to help you ace your next system design interview.","contentType":2,"generatedOn":"2026-10-14T22:53:55.4900595Z","viewCount":0},{"id":35,"title":"Cursor vs Copilot : Which AI Coding Assistant Wins in 2025?","url":"cursor-vs-copilot-which-ai-coding-assistant-truly-wins-in-2025","description":null,"seoDescription":"Compare Cursor vs GitHub Copilot on speed, context awareness, multi-file support, pricing and code quality to choose the best AI coding assistant for developers","contentType":5,"generatedOn":"2026-10-14T22:53:55.4906085Z","viewCount":0},{"id":139,"title":"Blinkit (Eternal) SDE-1 Interview Experience (June 2026) – Offer Received","url":"blinkit-eternal-sde-1-interview-experience-june-2026-offer-received","description":null,"seoDescription":"Blinkit SDE-1 interview experience with a 30 LPA offer. Covers House Robber DP, ticket booking system design, culture fit round and tips.","contentType":5,"generatedOn":"2026-10-14T22:53:55.4906231Z","viewCount":0},{"id":122,"title":"Zepto SDE-1 Interview Experience (Backend Developer) : Real DSA, LLD, Chess Game Design","url":"zepto-sde-1-interview-experience-backend-developer-real-dsa-lld-chess-game-design","description":null,"seoDescription":" Zepto SDE-1 Backend Interview Experience covering DSA, Dynamic Programming, LLD, API Design, DB Schema, OOP & Product Company Rounds.","contentType":5,"generatedOn":"2026-10-14T22:53:55.490613Z","viewCount":0},{"id":138,"title":"DSA Patterns for Coding Interviews: Complete LeetCode Roadmap (Beginner to Advanced)","url":"dsa-patterns-for-coding-interviews-complete-leetcode-roadmap-beginner-to-advanced","description":null,"seoDescription":"Master every LeetCode pattern for coding interviews. Learn Arrays, Sliding Window, Graphs, Dynamic Programming, Trees, Heaps and more with 250+ curated problem","contentType":5,"generatedOn":"2026-10-14T22:53:55.4906168Z","viewCount":0},{"id":172,"title":"Google L4 Software Engineer III interview experience | Selected","url":"google-l4-software-engineer-iii-interview-experience-selected","description":null,"seoDescription":"Google L4 Software Engineer III interview experience with API design, Googlyness, route matching, graph coding rounds, follow-up questions and tips.","contentType":5,"generatedOn":"2026-10-14T22:53:55.4906292Z","viewCount":0}],"latestContents":[{"id":219,"title":"6 Tools That Made My Life Easier as a Software Engineer","url":"6-tools-that-made-my-life-easier-as-a-software-engineer","description":null,"seoDescription":"The 6 developer tools I use daily as a software engineer: Git, VS Code, Docker, Postman, Chrome DevTools, and AI assistants, with real tips, mistakes, and trade","contentType":5,"generatedOn":"2026-10-14T22:53:55.4892907Z","viewCount":0},{"id":218,"title":"When Should a Business Use Multiple AI Agents Instead of One?","url":"when-should-a-business-use-multiple-ai-agents-instead-of-one","description":null,"seoDescription":"Single agent or multi-agent AI? Learn the 4 signals that justify splitting agents by knowledge, permissions, and risk, plus routing and handoff tips.","contentType":5,"generatedOn":"2026-10-14T22:53:55.4892957Z","viewCount":0},{"id":216,"title":"AI in Clinical Trials Market Estimated to Experience a Hike in Growth by 2035","url":"ai-in-clinical-trials-market-estimated-to-experience-a-hike-in-growth-by-2035","description":null,"seoDescription":"The exclusive information about market dynamics serves as a valuable guide to predict economic scenarios and initiatives taken to enhance future growth. Our mar","contentType":5,"generatedOn":"2026-10-14T22:53:55.4892976Z","viewCount":0},{"id":217,"title":"AI in Clinical Trials Market Estimated to Experience a Hike in Growth by 2035","url":"ai-in-clinical-trials-market-estimated-to-experience-a-hike-in-growth-by-2035","description":null,"seoDescription":"The exclusive information about market dynamics serves as a valuable guide to predict economic scenarios and initiatives taken to enhance future growth. Our mar","contentType":5,"generatedOn":"2026-10-14T22:53:55.4892991Z","viewCount":0},{"id":215,"title":"What Happens When an AI Agent Doesn't Know the Answer?","url":"what-happens-when-an-ai-agent-doesnt-know-the-answer","description":null,"seoDescription":"Most AI agents fail quietly. They guess instead of saying \"I don't know.\" Here's how to design better fallback and human-handoff behavior.","contentType":5,"generatedOn":"2026-10-14T22:53:55.4893002Z","viewCount":0},{"id":214,"title":"Greedy Algorithms Explained: How They Work, When They Fail and How to Use Them","url":"greedy-algorithms-explained-how-they-work-when-they-fail-and-how-to-use-them","description":null,"seoDescription":"Learn greedy algorithms step by step with C# code Dijkstra, Huffman coding, knapsack and MSTs plus when greedy fails and how to prove it's correct","contentType":5,"generatedOn":"2026-10-14T22:53:55.4893049Z","viewCount":0},{"id":213,"title":"Amazon SDE II Interview Experience (Bangalore, Selected) ~ Aug 2026","url":"amazon-sde-ii-interview-experience-bangalore-selected-aug-2026","description":null,"seoDescription":"Amazon SDE II interview experience from Bangalore covering 4 rounds, DSA, LLD, system design, Leadership Principles, coding questions and selection.","contentType":5,"generatedOn":"2026-10-14T22:53:55.4893058Z","viewCount":0},{"id":212,"title":"How to Get 10x Better AI Answers Without Writing Better Prompts : 10 Proven Techniques","url":"how-to-get-10x-better-ai-answers-without-writing-better-prompts-10-proven-techniques","description":null,"seoDescription":"Get better AI answers without complex prompts. Learn 10 practical techniques using context, examples, tools, feedback, and verification.","contentType":5,"generatedOn":"2026-10-14T22:53:55.4893066Z","viewCount":0},{"id":211,"title":"I Interviewed for a Microsoft SDE I Role. Here's Everything That Happened.","url":"i-interviewed-for-a-microsoft-sde-i-role-heres-everything-that-happened","description":null,"seoDescription":"My real Microsoft SDE I interview experience, all 4 rounds, the exact DSA problems with fully tested solutions, the WhatsApp system design round","contentType":5,"generatedOn":"2026-10-14T22:53:55.4893074Z","viewCount":0},{"id":140,"title":"PolicyBazaar Software Development Engineer (SDE) Interview Experience | DSA, Core CS & System Design","url":"policybazaar-software-development-engineer-sde-interview-experience-dsa-core-cs-system-design","description":null,"seoDescription":"Detailed PolicyBazaar SDE interview experience covering 3 rounds: DSA coding, core CS assessment and system design with key learnings and insights.","contentType":5,"generatedOn":"2026-10-14T22:53:55.4893083Z","viewCount":0}],"relatedContents":[{"id":207,"title":"How to Find the Right View of a Binary Tree","url":"right-view-of-a-binary-tree","description":null,"seoDescription":"Learn how to find the right view of a binary tree using DFS and BFS, with examples, code, complexity analysis and coding interview tips.","contentType":5,"generatedOn":"2026-10-14T22:53:55.4951712Z","viewCount":0},{"id":206,"title":"Left View of a Binary Tree: DFS and BFS Approaches Explained","url":"left-view-of-a-binary-tree","description":null,"seoDescription":"Learn how to find the left view of a binary tree using DFS and BFS, with examples, code, complexity analysis, common mistakes and interview tips.","contentType":5,"generatedOn":"2026-10-14T22:53:55.4951754Z","viewCount":0},{"id":201,"title":"Bottom View of a Binary Tree: DFS vs BFS Approach","url":"bottom-view-of-a-binary-tree-dfs-vs-bfs-approach","description":null,"seoDescription":"Learn to find the bottom view of a binary tree using horizontal distance. Compares a buggy DFS attempt, a fixed DFS and the optimal BFS solution in Java.","contentType":5,"generatedOn":"2026-10-14T22:53:55.4951785Z","viewCount":0},{"id":200,"title":" Longest Playlist With No Repeated Songs : Brute Force to Optimal","url":"longest-playlist-with-no-repeated-songs-brute-force-to-optimal","description":null,"seoDescription":"Find the longest playlist with no repeated songs using brute force, HashSet, and HashMap sliding window techniques, with Java code and dry runs.","contentType":5,"generatedOn":"2026-10-14T22:53:55.4951797Z","viewCount":0},{"id":90,"title":"Contain Virus : Deep, Intuitive & Fully Explained Guide","url":"contain-virus-deep-intuitive-fully-explained-guide","description":null,"seoDescription":"Contain Virus problem explained with DFS + greedy approach, step-by-step simulation, examples and optimized solutions for coding interviews.","contentType":5,"generatedOn":"2026-10-14T22:53:55.4951814Z","viewCount":0},{"id":37,"title":"Find the repeating and missing numbers","url":"find-the-repeating-and-missing-numbers","description":null,"seoDescription":"Find the repeating and missing numbers in an array from 1..n using brute force, hashmap, math and XOR, step-by-step explained with real-world use cases.","contentType":5,"generatedOn":"2026-10-14T22:53:55.4951827Z","viewCount":0},{"id":27,"title":"4 Sum | Find Quads that add up to a target value","url":"4-sum-find-quads-that-add-up-to-a-target-value","description":null,"seoDescription":"","contentType":5,"generatedOn":"2026-10-14T22:53:55.4951838Z","viewCount":0},{"id":26,"title":"Top 50 Most Frequently Asked String Coding Problems (Interview Preparation )","url":"top-50-most-frequently-asked-string-coding-problems-interview-preparation","description":null,"seoDescription":"","contentType":5,"generatedOn":"2026-10-14T22:53:55.495185Z","viewCount":0},{"id":25,"title":"Intersection of Two Sorted Arrays","url":"intersection-of-two-sorted-arrays","description":null,"seoDescription":"","contentType":5,"generatedOn":"2026-10-14T22:53:55.4951863Z","viewCount":0}]}}},"source":{"isMobile":false}}; window.__CLIENT_RENDER__ = false;