Category Archives: Graph

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 »

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 »

Sum of dependencies in a graph

Given a directed and connected graph with n nodes. If there is an edge from u to v then u depends on v. Our task was to find out the sum of dependencies for every node. Example: For the graph in diagram, A depends on C and D i.e. 2 B depends on D i.e.… Read More »

Count number of edges in an undirected graph

Given an adjacency list representation undirected graph. Write a function to count the number of edges in the undirected graph. Expected time complexity : O(V) Examples: Input : Adjacency list representation of below graph. Output : 9 Idea is based on Handshaking Lemma. Handshaking lemma is about undirected graph. In every finite undirected graph number… 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 »

Max Flow Problem Introduction

Maximum flow problems involve finding a feasible flow through a single-source, single-sink flow network that is maximum. Let’s take an image to explain how above definition wants to say. Each edge is labeled with a capacity, the maximum amount of stuff that it can carry. The goal is to figure out how much stuff can… Read More »

Minimum steps to reach target by a Knight

Given a square chessboard of N x N size, the position of Knight and position of a target is given. We need to find out minimum steps a Knight will take to reach the target position. Examples: In above diagram Knight takes 3 step to reach from (4, 5) to (1, 1) (4, 5) ->… Read More »