Category Archives: Graph

Roots of a tree which give minimum height

Given an undirected graph, which has tree characteristics. It is possible to choose any node as root, the task is to find those nodes only which minimize the height of tree. Example: In below diagram all node are made as root one by one, we can see that when 3 and 4 are root, height… Read More »

Stepping Numbers

Given two integers ‘n’ and ‘m’, find all the stepping numbers in range [n, m]. A number is called stepping number if all adjacent digits have an absolute difference of 1. 321 is a Stepping Number while 421 is not. Examples: Input : n = 0, m = 21 Output : 0 1 2 3… Read More »

Clone an Undirected Graph

Cloning of a LinkedList and a Binary Tree with random pointers has already been discussed. The idea behind cloning a graph is pretty much similar. The idea is to do a BFS traversal of the graph and while visiting a node make a clone node of it (a copy of original node). If a node… Read More »

Find Shortest distance from a guard in a Bank

Given a matrix that is filled with ‘O’, ‘G’, and ‘W’ where ‘O’ represents open space, ‘G’ represents guards and ‘W’ represents walls in a Bank. Replace all of the O’s in the matrix with their shortest distance from a guard, without being able to go through any walls. Also, replace the guards with 0… Read More »

Check if two nodes are on same path in a tree

Given a tree (not necessarily a binary tree) and a number of queries such that every query takes two nodes of tree as parameters. For every query pair, find if two nodes are on the same path from root to the bottom. For example, consider the below tree, if given queries are (1, 5), (1,… Read More »