Tag Archives: DFS

Maximum product of two non-intersecting paths in a tree

Given an undirected connected tree with N nodes (and N-1 edges), we need to find two paths in this tree such that they are non-intersecting and the product of their length is maximum. Examples: In first tree two paths which are non-intersecting and have highest product are, 1-2 and 3-4, so answer is 1*1 =… Read More »

Maximum edge removal from tree to make even forest

Given an undirected tree which has even number of vertices, we need to remove the maximum number of edges from this tree such that each connected component of the resultant forest has an even number of vertices. Examples: In above shown tree, we can remove at max 2 edges 0-2 and 0-4 shown in red… Read More »

Number of decisions to reach destination

Given a grid which consists of 4 types of characters : ‘B’ ‘.’ ‘S’ and ‘D’. We need to reach D starting from S, at each step we can go to neighboring cells i.e. up, down, left and right. Cells having character ‘B’ are blocked i.e. at any step we can’t move to cell having… Read More »

Delete Edge to minimize subtree sum difference

Given an undirected tree whose each node is associated with a weight. We need to delete an edge in such a way that difference between sum of weight in one subtree to sum of weight in other subtree is minimized. Example: In above tree, We have 6 choices for edge deletion, edge 0-1, subtree sum… Read More »

Find length of the largest region in Boolean Matrix

Consider a matrix with rows and columns, where each cell contains either a ‘0’ or a ‘1’ and any cell containing a 1 is called a filled cell. Two cells are said to be connected if they are adjacent to each other horizontally, vertically, or diagonally .If one or more filled cells are also connected,… Read More »

Dinic’s algorithm for Maximum Flow

Problem Statement : Given a graph which represents a flow network where every edge has a capacity. Also given two vertices source ‘s’ and sink ‘t’ in the graph, find the maximum possible flow from s to t with following constraints : Flow on an edge doesn’t exceed the given capacity of the edge. Incoming… Read More »

Convert a tree to forest of even nodes

Given a tree of n even nodes. The task is to find the maximum number of edges to be removed from the given tree to obtain forest of trees having even number of nodes. This problem is always solvable as given graph has even nodes. Examples: Input : n = 10 Edge 1: 1 3… 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 »