Category Archives: Graph

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 »

A matrix probability question

Given a rectangular matrix, we can move from current cell in 4 directions with equal probability. The 4 directions are right, left, top or bottom. Calculate the Probability that after N moves from a given position (i, j) in the matrix, we will not cross boundaries of the matrix at any point. We strongly recommend… Read More »