Boruvka's algorithm | Greedy Algo-9
Last Updated :
17 Mar, 2023
We have discussed the following topics on Minimum Spanning Tree.
Applications of Minimum Spanning Tree Problem
Kruskal’s Minimum Spanning Tree Algorithm
Prim’s Minimum Spanning Tree Algorithm
In this post, Boruvka's algorithm is discussed. Like Prim's and Kruskal's, Boruvka’s algorithm is also a Greedy algorithm. Below is a complete algorithm.
1) Input is a connected, weighted and un-directed graph.
2) Initialize all vertices as individual components (or sets).
3) Initialize MST as empty.
4) While there are more than one components, do following
for each component.
a) Find the closest weight edge that connects this
component to any other component.
b) Add this closest edge to MST if not already added.
5) Return MST.
Below is the idea behind the above algorithm (The idea is the same as Prim's MST algorithm).
A spanning tree means all vertices must be connected. So the two disjoint subsets (discussed above) of vertices must be connected to make a Spanning Tree. And they must be connected with the minimum weight edge to make it a Minimum Spanning Tree.
Let us understand the algorithm in the below example.

Initially, MST is empty. Every vertex is single component as highlighted in blue color in the below diagram.

For every component, find the cheapest edge that connects it to some other component.
Component Cheapest Edge that connects
it to some other component
{0} 0-1
{1} 0-1
{2} 2-8
{3} 2-3
{4} 3-4
{5} 5-6
{6} 6-7
{7} 6-7
{8} 2-8
The cheapest edges are highlighted with green color. Now MST becomes {0-1, 2-8, 2-3, 3-4, 5-6, 6-7}.

After above step, components are {{0,1}, {2,3,4,8}, {5,6,7}}. The components are encircled with blue color.

We again repeat the step, i.e., for every component, find the cheapest edge that connects it to some other component.
Component Cheapest Edge that connects
it to some other component
{0,1} 1-2 (or 0-7)
{2,3,4,8} 2-5
{5,6,7} 2-5
The cheapest edges are highlighted with green color. Now MST becomes {0-1, 2-8, 2-3, 3-4, 5-6, 6-7, 1-2, 2-5}

At this stage, there is only one component {0, 1, 2, 3, 4, 5, 6, 7, 8} which has all edges. Since there is only one component left, we stop and return MST.
Implementation: Below is the implementation of the above algorithm. The input graph is represented as a collection of edges and union-find data structure is used to keep track of components.
C++
// Boruvka's algorithm to find Minimum Spanning
// Tree of a given connected, undirected and weighted graph
#include <bits/stdc++.h>
using namespace std;
// Class to represent a graph
class Graph {
int V; // No. of vertices
vector<vector<int> >graph; // default dictionary to store graph
// A utility function to find set of an element i
// (uses path compression technique)
int find(vector<int>& parent, int i)
{
if (parent[i] == i) {
return i;
}
return find(parent, parent[i]);
}
// A function that does union of two sets of x and y
// (uses union by rank)
void unionSet(vector<int>& parent, vector<int>& rank,
int x, int y)
{
int xroot = find(parent, x);
int yroot = find(parent, y);
// Attach smaller rank tree under root of high rank
// tree (Union by Rank)
if (rank[xroot] < rank[yroot]) {
parent[xroot] = yroot;
}
else if (rank[xroot] > rank[yroot]) {
parent[yroot] = xroot;
}
// If ranks are same, then make one as root and
// increment its rank by one
else {
parent[yroot] = xroot;
rank[xroot]++;
}
}
public:
Graph(int vertices)
{
V = vertices;
graph = vector<vector<int> >();
}
// function to add an edge to graph
void addEdge(int u, int v, int w)
{
graph.push_back({ u, v, w });
}
// The main function to construct MST using Kruskal's
// algorithm
void boruvkaMST()
{
vector<int> parent(V);
// An array to store index of the cheapest edge of
// subset. It store [u,v,w] for each component
vector<int> rank(V);
vector<vector<int> > cheapest(V,
vector<int>(3, -1));
// Initially there are V different trees.
// Finally there will be one tree that will be MST
int numTrees = V;
int MSTweight = 0;
// Create V subsets with single elements
for (int node = 0; node < V; node++) {
parent[node] = node;
rank[node] = 0;
}
// Keep combining components (or sets) until all
// components are not combined into single MST
while (numTrees > 1) {
// Traverse through all edges and update
// cheapest of every component
for (int i = 0; i < graph.size(); i++) {
// Find components (or sets) of two corners
// of current edge
int u = graph[i][0], v = graph[i][1],
w = graph[i][2];
int set1 = find(parent, u),
set2 = find(parent, v);
// If two corners of current edge belong to
// same set, ignore current edge. Else check
// if current edge is closer to previous
// cheapest edges of set1 and set2
if (set1 != set2) {
if (cheapest[set1][2] == -1
|| cheapest[set1][2] > w) {
cheapest[set1] = { u, v, w };
}
if (cheapest[set2][2] == -1
|| cheapest[set2][2] > w) {
cheapest[set2] = { u, v, w };
}
}
}
// Consider the above picked cheapest edges and
// add them to MST
for (int node = 0; node < V; node++) {
// Check if cheapest for current set exists
if (cheapest[node][2] != -1) {
int u = cheapest[node][0],
v = cheapest[node][1],
w = cheapest[node][2];
int set1 = find(parent, u),
set2 = find(parent, v);
if (set1 != set2) {
MSTweight += w;
unionSet(parent, rank, set1, set2);
printf("Edge %d-%d with weight %d "
"included in MST\n",
u, v, w);
numTrees--;
}
}
}
for (int node = 0; node < V; node++) {
// reset cheapest array
cheapest[node][2] = -1;
}
}
printf("Weight of MST is %d\n", MSTweight);
}
};
int main()
{
Graph g(4);
g.addEdge(0, 1, 10);
g.addEdge(0, 2, 6);
g.addEdge(0, 3, 5);
g.addEdge(1, 3, 15);
g.addEdge(2, 3, 4);
g.boruvkaMST();
}
// This code is contributed by prajwal kandekar
Java
// Boruvka's algorithm to find Minimum Spanning
// Tree of a given connected, undirected and weighted graph
import java.util.*;
// Class to represent a graph
class Graph {
private int V; // No. of vertices
private List<List<Integer> >
graph; // default dictionary to store graph
Graph(int vertices)
{
V = vertices;
graph = new ArrayList<>();
}
// function to add an edge to graph
void addEdge(int u, int v, int w)
{
graph.add(Arrays.asList(u, v, w));
}
// A utility function to find set of an element i
// (uses path compression technique)
private int find(List<Integer> parent, int i)
{
if (parent.get(i) == i) {
return i;
}
return find(parent, parent.get(i));
}
// A function that does union of two sets of x and y
// (uses union by rank)
private void unionSet(List<Integer> parent,
List<Integer> rank, int x, int y)
{
int xroot = find(parent, x);
int yroot = find(parent, y);
// Attach smaller rank tree under root of high rank
// tree (Union by Rank)
if (rank.get(xroot) < rank.get(yroot)) {
parent.set(xroot, yroot);
}
else if (rank.get(xroot) > rank.get(yroot)) {
parent.set(yroot, xroot);
}
// If ranks are same, then make one as root and
// increment its rank by one
else {
parent.set(yroot, xroot);
rank.set(xroot, rank.get(xroot) + 1);
}
}
// The main function to construct MST using Kruskal's
// algorithm
void boruvkaMST()
{
List<Integer> parent = new ArrayList<>();
// An array to store index of the cheapest edge of
// subset. It store [u,v,w] for each component
List<Integer> rank = new ArrayList<>();
List<List<Integer> > cheapest = new ArrayList<>();
// Initially there are V different trees.
// Finally there will be one tree that will be MST
int numTrees = V;
int MSTweight = 0;
// Create V subsets with single elements
for (int node = 0; node < V; node++) {
parent.add(node);
rank.add(0);
cheapest.add(Arrays.asList(-1, -1, -1));
}
// Keep combining components (or sets) until all
// components are not combined into single MST
while (numTrees > 1) {
// Traverse through all edges and update
// cheapest of every component
for (List<Integer> edge : graph) {
// Find components (or sets) of two corners
// of current edge
int u = edge.get(0), v = edge.get(1),
w = edge.get(2);
int set1 = find(parent, u),
set2 = find(parent, v);
// If two corners of current edge belong to
// same set, ignore current edge. Else check
// if current edge is closer to previous
// cheapest edges of set1 and set2
if (set1 != set2) {
if (cheapest.get(set1).get(2) == -1
|| cheapest.get(set1).get(2) > w) {
cheapest.set(
set1, Arrays.asList(u, v, w));
}
if (cheapest.get(set2).get(2) == -1
|| cheapest.get(set2).get(2) > w) {
cheapest.set(
set2, Arrays.asList(u, v, w));
}
}
}
// Consider the above picked cheapest edges and
// add them to MST
for (int node = 0; node < V; node++) {
// Check if cheapest for current set exists
if (cheapest.get(node).get(2) != -1) {
int u = cheapest.get(node).get(0),
v = cheapest.get(node).get(1),
w = cheapest.get(node).get(2);
int set1 = find(parent, u),
set2 = find(parent, v);
if (set1 != set2) {
MSTweight += w;
unionSet(parent, rank, set1, set2);
System.out.printf(
"Edge %d-%d with weight %d included in MST\n",
u, v, w);
numTrees--;
}
}
}
for (List<Integer> list : cheapest) {
// reset cheapest array
list.set(2, -1);
}
}
System.out.printf("Weight of MST is %d\n",
MSTweight);
}
}
class GFG {
public static void main(String[] args)
{
Graph g = new Graph(4);
g.addEdge(0, 1, 10);
g.addEdge(0, 2, 6);
g.addEdge(0, 3, 5);
g.addEdge(1, 3, 15);
g.addEdge(2, 3, 4);
g.boruvkaMST();
}
}
// This code is contributed by prasad264
Python
# Boruvka's algorithm to find Minimum Spanning
# Tree of a given connected, undirected and weighted graph
from collections import defaultdict
#Class to represent a graph
class Graph:
def __init__(self,vertices):
self.V= vertices #No. of vertices
self.graph = [] # default dictionary to store graph
# function to add an edge to graph
def addEdge(self,u,v,w):
self.graph.append([u,v,w])
# A utility function to find set of an element i
# (uses path compression technique)
def find(self, parent, i):
if parent[i] == i:
return i
return self.find(parent, parent[i])
# A function that does union of two sets of x and y
# (uses union by rank)
def union(self, parent, rank, x, y):
xroot = self.find(parent, x)
yroot = self.find(parent, y)
# Attach smaller rank tree under root of high rank tree
# (Union by Rank)
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yroot] = xroot
#If ranks are same, then make one as root and increment
# its rank by one
else :
parent[yroot] = xroot
rank[xroot] += 1
# The main function to construct MST using Kruskal's algorithm
def boruvkaMST(self):
parent = []; rank = [];
# An array to store index of the cheapest edge of
# subset. It store [u,v,w] for each component
cheapest =[]
# Initially there are V different trees.
# Finally there will be one tree that will be MST
numTrees = self.V
MSTweight = 0
# Create V subsets with single elements
for node in range(self.V):
parent.append(node)
rank.append(0)
cheapest =[-1] * self.V
# Keep combining components (or sets) until all
# components are not combined into single MST
while numTrees > 1:
# Traverse through all edges and update
# cheapest of every component
for i in range(len(self.graph)):
# Find components (or sets) of two corners
# of current edge
u,v,w = self.graph[i]
set1 = self.find(parent, u)
set2 = self.find(parent ,v)
# If two corners of current edge belong to
# same set, ignore current edge. Else check if
# current edge is closer to previous
# cheapest edges of set1 and set2
if set1 != set2:
if cheapest[set1] == -1 or cheapest[set1][2] > w :
cheapest[set1] = [u,v,w]
if cheapest[set2] == -1 or cheapest[set2][2] > w :
cheapest[set2] = [u,v,w]
# Consider the above picked cheapest edges and add them
# to MST
for node in range(self.V):
#Check if cheapest for current set exists
if cheapest[node] != -1:
u,v,w = cheapest[node]
set1 = self.find(parent, u)
set2 = self.find(parent ,v)
if set1 != set2 :
MSTweight += w
self.union(parent, rank, set1, set2)
print ("Edge %d-%d with weight %d included in MST" % (u,v,w))
numTrees = numTrees - 1
#reset cheapest array
cheapest =[-1] * self.V
print ("Weight of MST is %d" % MSTweight)
g = Graph(4)
g.addEdge(0, 1, 10)
g.addEdge(0, 2, 6)
g.addEdge(0, 3, 5)
g.addEdge(1, 3, 15)
g.addEdge(2, 3, 4)
g.boruvkaMST()
#This code is contributed by Neelam Yadav
C#
// Boruvka's algorithm to find Minimum Spanning
// Tree of a given connected, undirected and weighted graph
using System;
using System.Collections.Generic;
// Class to represent a graph
class Graph {
private int V; // No. of vertices
private List<List<int> >
graph; // default dictionary to store graph
// A utility function to find set of an element i
// (uses path compression technique)
private int Find(List<int> parent, int i)
{
if (parent[i] == i) {
return i;
}
return Find(parent, parent[i]);
}
// A function that does union of two sets of x and y
// (uses union by rank)
private void UnionSet(List<int> parent, List<int> rank,
int x, int y)
{
int xroot = Find(parent, x);
int yroot = Find(parent, y);
// Attach smaller rank tree under root of high rank
// tree (Union by Rank)
if (rank[xroot] < rank[yroot]) {
parent[xroot] = yroot;
}
else if (rank[xroot] > rank[yroot]) {
parent[yroot] = xroot;
}
// If ranks are same, then make one as root and
// increment its rank by one
else {
parent[yroot] = xroot;
rank[xroot]++;
}
}
public Graph(int vertices)
{
V = vertices;
graph = new List<List<int> >();
}
// function to add an edge to graph
public void AddEdge(int u, int v, int w)
{
graph.Add(new List<int>{ u, v, w });
}
// The main function to construct MST using Kruskal's
// algorithm
public void boruvkaMST()
{
List<int> parent = new List<int>();
// An array to store index of the cheapest edge of
// subset. It store [u,v,w] for each component
List<int> rank = new List<int>();
List<List<int> > cheapest = new List<List<int> >();
// Initially there are V different trees.
// Finally there will be one tree that will be MST
int numTrees = V;
int MSTweight = 0;
// Create V subsets with single elements
for (int node = 0; node < V; node++) {
parent.Add(node);
rank.Add(0);
cheapest.Add(new List<int>{ -1, -1, -1 });
}
// Keep combining components (or sets) until all
// components are not combined into single MST
while (numTrees > 1) {
// Traverse through all edges and update
// cheapest of every component
for (int i = 0; i < graph.Count; i++) {
// Find components (or sets) of two corners
// of current edge
int u = graph[i][0], v = graph[i][1],
w = graph[i][2];
int set1 = Find(parent, u),
set2 = Find(parent, v);
// If two corners of current edge belong to
// same set, ignore current edge. Else check
// if current edge is closer to previous
// cheapest edges of set1 and set2
if (set1 != set2) {
if (cheapest[set1][2] == -1
|| cheapest[set1][2] > w) {
cheapest[set1]
= new List<int>{ u, v, w };
}
if (cheapest[set2][2] == -1
|| cheapest[set2][2] > w) {
cheapest[set2]
= new List<int>{ u, v, w };
}
}
}
// Consider the above picked cheapest edges and
// add them to MST
for (int node = 0; node < V; node++) {
// Check if cheapest for current set exists
if (cheapest[node][2] != -1) {
int u = cheapest[node][0],
v = cheapest[node][1],
w = cheapest[node][2];
int set1 = Find(parent, u),
set2 = Find(parent, v);
if (set1 != set2) {
MSTweight += w;
UnionSet(parent, rank, set1, set2);
Console.WriteLine(
"Edge {0}-{1} with weight {2} included in MST",
u, v, w);
numTrees--;
}
}
}
for (int node = 0; node < V; node++) {
// reset cheapest array
cheapest[node][2] = -1;
}
}
Console.WriteLine("Weight of MST is {0}",
MSTweight);
}
}
public class GFG {
static void Main(string[] args)
{
Graph g = new Graph(4);
g.AddEdge(0, 1, 10);
g.AddEdge(0, 2, 6);
g.AddEdge(0, 3, 5);
g.AddEdge(1, 3, 15);
g.AddEdge(2, 3, 4);
g.boruvkaMST();
}
}
// This code is contributed by prasad264
JavaScript
// Boruvka's algorithm to find Minimum Spanning
// Tree of a given connected, undirected and weighted graph
// Class to represent a graph
class Graph {
constructor(vertices) {
this.V = vertices; // No. of vertices
this.graph = []; // default dictionary to store graph
}
// function to add an edge to graph
addEdge(u, v, w) {
this.graph.push([u, v, w]);
}
// A utility function to find set of an element i
// (uses path compression technique)
find(parent, i) {
if (parent[i] === i) {
return i;
}
return this.find(parent, parent[i]);
}
// A function that does union of two sets of x and y
// (uses union by rank)
union(parent, rank, x, y) {
const xroot = this.find(parent, x);
const yroot = this.find(parent, y);
// Attach smaller rank tree under root of high rank tree
// (Union by Rank)
if (rank[xroot] < rank[yroot]) {
parent[xroot] = yroot;
} else if (rank[xroot] > rank[yroot]) {
parent[yroot] = xroot;
}
// If ranks are same, then make one as root and increment
// its rank by one
else {
parent[yroot] = xroot;
rank[xroot] += 1;
}
}
//The main function to construct MST using Kruskal's algorithm
boruvkaMST() {
const parent = [];
// An array to store index of the cheapest edge of
// subset. It store [u,v,w] for each component
const rank = [];
const cheapest = [];
// Initially there are V different trees.
// Finally there will be one tree that will be MST
let numTrees = this.V;
let MSTweight = 0;
// Create V subsets with single elements
for (let node = 0; node < this.V; node++) {
parent.push(node);
rank.push(0);
cheapest[node] = -1;
}
// Keep combining components (or sets) until all
// components are not combined into single MST
while (numTrees > 1) {
// Traverse through all edges and update
// cheapest of every component
for (let i = 0; i < this.graph.length; i++) {
// Find components (or sets) of two corners
// of current edge
const [u, v, w] = this.graph[i];
const set1 = this.find(parent, u);
const set2 = this.find(parent, v);
// If two corners of current edge belong to
// same set, ignore current edge. Else check if
// current edge is closer to previous
// cheapest edges of set1 and set2
if (set1 !== set2) {
if (cheapest[set1] === -1 || cheapest[set1][2] > w) {
cheapest[set1] = [u, v, w];
}
if (cheapest[set2] === -1 || cheapest[set2][2] > w) {
cheapest[set2] = [u, v, w];
}
}
}
// Consider the above picked cheapest edges and add them
// to MST
for (let node = 0; node < this.V; node++) {
// Check if cheapest for current set exists
if (cheapest[node] !== -1) {
const [u, v, w] = cheapest[node];
const set1 = this.find(parent, u);
const set2 = this.find(parent, v);
if (set1 !== set2) {
MSTweight += w;
this.union(parent, rank, set1, set2);
console.log(`Edge ${u}-${v} with weight ${w} included in MST`);
numTrees--;
}
}
}
for (let node = 0; node < this.V; node++) {
// reset cheapest array
cheapest[node] = -1;
}
}
console.log(`Weight of MST is ${MSTweight}`);
}
}
let g = new Graph(4);
g.addEdge(0, 1, 10);
g.addEdge(0, 2, 6);
g.addEdge(0, 3, 5);
g.addEdge(1, 3, 15);
g.addEdge(2, 3, 4);
g.boruvkaMST();
// This code is contributed by prajwal kandekar
OutputEdge 0-3 with weight 5 included in MST
Edge 0-1 with weight 10 included in MST
Edge 2-3 with weight 4 included in MST
Weight of MST is 19
Interesting Facts about Boruvka’s algorithm:
- Time Complexity of Boruvka's algorithm is O(E log V) which is the same as Kruskal's and Prim's algorithms.
- Boruvka's algorithm is used as a step in a faster randomized algorithm that works in linear time O(E).
- Boruvka’s algorithm is the oldest minimum spanning tree algorithm that was discovered by Boruvka in 1926, long before computers even existed. The algorithm was published as a method of constructing an efficient electricity network.
Space complexity: The space complexity of Boruvka’s algorithm is O(V).
Exercise:
The above code assumes that the input graph is connected and it fails if a disconnected graph is given. Extend the above algorithm so that it works for a disconnected graph also and produces a forest.
Similar Reads
Greedy Algorithms
Greedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Greedy Algorithm Tutorial
Greedy is an algorithmic paradigm that builds up a solution piece by piece, always choosing the next piece that offers the most obvious and immediate benefit. Greedy algorithms are used for optimization problems. An optimization problem can be solved using Greedy if the problem has the following pro
9 min read
Greedy Algorithms General Structure
A greedy algorithm solves problems by making the best choice at each step. Instead of looking at all possible solutions, it focuses on the option that seems best right now.Example of Greedy Algorithm - Fractional KnapsackProblem structure:Most of the problems where greedy algorithms work follow thes
5 min read
Difference between Greedy Algorithm and Divide and Conquer Algorithm
Greedy algorithm and divide and conquer algorithm are two common algorithmic paradigms used to solve problems. The main difference between them lies in their approach to solving problems. Greedy Algorithm:The greedy algorithm is an algorithmic paradigm that follows the problem-solving heuristic of m
3 min read
Greedy Approach vs Dynamic programming
Greedy approach and Dynamic programming are two different algorithmic approaches that can be used to solve optimization problems. Here are the main differences between these two approaches: Greedy Approach:The greedy approach makes the best choice at each step with the hope of finding a global optim
2 min read
Comparison among Greedy, Divide and Conquer and Dynamic Programming algorithm
Greedy algorithm, divide and conquer algorithm, and dynamic programming algorithm are three common algorithmic paradigms used to solve problems. Here's a comparison among these algorithms:Approach:Greedy algorithm: Makes locally optimal choices at each step with the hope of finding a global optimum.
4 min read
Standard Greedy algorithms
Activity Selection Problem | Greedy Algo-1
Given n activities with their start and finish times given in array start[] and finish[]. Select the maximum number of activities that can be performed by a single person, assuming that a person can only work on a single activity at a time. Note: Duration of the activity includes both starting and f
13 min read
Job Sequencing Problem
Given two arrays: deadline[] and profit[], where the index of deadline[] represents a job ID, and deadline[i] denotes the deadline for that job and profit[i] represents profit of doing ith job. Each job takes exactly one unit of time to complete, and only one job can be scheduled at a time. A job ea
13 min read
Huffman Coding | Greedy Algo-3
Huffman coding is a lossless data compression algorithm. The idea is to assign variable-length codes to input characters, lengths of the assigned codes are based on the frequencies of corresponding characters. The variable-length codes assigned to input characters are Prefix Codes, means the codes (
12 min read
Huffman Decoding
We have discussed Huffman Encoding in a previous post. In this post, decoding is discussed. Examples: Input Data: AAAAAABCCCCCCDDEEEEEFrequencies: A: 6, B: 1, C: 6, D: 2, E: 5 Encoded Data: 0000000000001100101010101011111111010101010 Huffman Tree: '#' is the special character usedfor internal nodes
15 min read
Water Connection Problem
You are given n houses in a colony, numbered from 1 to n, and p pipes connecting these houses. Each house has at most one outgoing pipe and at most one incoming pipe. Your goal is to install tanks and taps efficiently.A tank is installed at a house that has one outgoing pipe but no incoming pipe.A t
8 min read
Greedy Algorithm for Egyptian Fraction
Every positive fraction can be represented as sum of unique unit fractions. A fraction is unit fraction if numerator is 1 and denominator is a positive integer, for example 1/3 is a unit fraction. Such a representation is called Egyptian Fraction as it was used by ancient Egyptians. Following are a
11 min read
Policemen catch thieves
Given an array arr, where each element represents either a policeman (P) or a thief (T). The objective is to determine the maximum number of thieves that can be caught under the following conditions:Each policeman (P) can catch only one thief (T).A policeman can only catch a thief if the distance be
12 min read
Fitting Shelves Problem
Given length of wall w and shelves of two lengths m and n, find the number of each type of shelf to be used and the remaining empty space in the optimal solution so that the empty space is minimum. The larger of the two shelves is cheaper so it is preferred. However cost is secondary and first prior
9 min read
Assign Mice to Holes
There are N Mice and N holes are placed in a straight line. Each hole can accommodate only 1 mouse. A mouse can stay at his position, move one step right from x to x + 1, or move one step left from x to x -1. Any of these moves consumes 1 minute. Assign mice to holes so that the time when the last m
8 min read
Greedy algorithm on Array
Minimum product subset of an array
INTRODUCTION: The minimum product subset of an array refers to a subset of elements from the array such that the product of the elements in the subset is minimized. To find the minimum product subset, various algorithms can be used, such as greedy algorithms, dynamic programming, and branch and boun
13 min read
Maximize array sum after K negations using Sorting
Given an array of size n and an integer k. We must modify array k number of times. In each modification, we can replace any array element arr[i] by -arr[i]. The task is to perform this operation in such a way that after k operations, the sum of the array is maximum.Examples : Input : arr[] = [-2, 0,
10 min read
Minimum sum of product of two arrays
Find the minimum sum of Products of two arrays of the same size, given that k modifications are allowed on the first array. In each modification, one array element of the first array can either be increased or decreased by 2.Examples: Input : a[] = {1, 2, -3} b[] = {-2, 3, -5} k = 5 Output : -31 Exp
14 min read
Minimum sum of absolute difference of pairs of two arrays
Given two arrays a[] and b[] of equal length n. The task is to pair each element of array a to an element in array b, such that sum S of absolute differences of all the pairs is minimum.Suppose, two elements a[i] and a[j] (i != j) of a are paired with elements b[p] and b[q] of b respectively, then p
7 min read
Minimum increment/decrement to make array non-Increasing
Given an array a, your task is to convert it into a non-increasing form such that we can either increment or decrement the array value by 1 in the minimum changes possible. Examples : Input : a[] = {3, 1, 2, 1}Output : 1Explanation : We can convert the array into 3 1 1 1 by changing 3rd element of a
11 min read
Sorting array with reverse around middle
Consider the given array arr[], we need to find if we can sort array with the given operation. The operation is We have to select a subarray from the given array such that the middle element(or elements (in case of even number of elements)) of subarray is also the middle element(or elements (in case
6 min read
Sum of Areas of Rectangles possible for an array
Given an array, the task is to compute the sum of all possible maximum area rectangles which can be formed from the array elements. Also, you can reduce the elements of the array by at most 1. Examples: Input: a = {10, 10, 10, 10, 11, 10, 11, 10} Output: 210 Explanation: We can form two rectangles o
13 min read
Largest lexicographic array with at-most K consecutive swaps
Given an array arr[], find the lexicographically largest array that can be obtained by performing at-most k consecutive swaps. Examples : Input : arr[] = {3, 5, 4, 1, 2} k = 3 Output : 5, 4, 3, 2, 1 Explanation : Array given : 3 5 4 1 2 After swap 1 : 5 3 4 1 2 After swap 2 : 5 4 3 1 2 After swap 3
9 min read
Partition into two subsets of lengths K and (N - k) such that the difference of sums is maximum
Given an array of non-negative integers of length N and an integer K. Partition the given array into two subsets of length K and N - K so that the difference between the sum of both subsets is maximum. Examples : Input : arr[] = {8, 4, 5, 2, 10} k = 2 Output : 17 Explanation : Here, we can make firs
7 min read
Greedy algorithm on Operating System
Program for First Fit algorithm in Memory Management
Prerequisite : Partition Allocation MethodsIn the first fit, the partition is allocated which is first sufficient from the top of Main Memory.Example : Input : blockSize[] = {100, 500, 200, 300, 600}; processSize[] = {212, 417, 112, 426};Output:Process No. Process Size Block no. 1 212 2 2 417 5 3 11
8 min read
Program for Best Fit algorithm in Memory Management
Prerequisite : Partition allocation methodsBest fit allocates the process to a partition which is the smallest sufficient partition among the free available partitions. Example: Input : blockSize[] = {100, 500, 200, 300, 600}; processSize[] = {212, 417, 112, 426}; Output: Process No. Process Size Bl
8 min read
Program for Worst Fit algorithm in Memory Management
Prerequisite : Partition allocation methodsWorst Fit allocates a process to the partition which is largest sufficient among the freely available partitions available in the main memory. If a large process comes at a later stage, then memory will not have space to accommodate it. Example: Input : blo
8 min read
Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)
The shortest job first (SJF) or shortest job next, is a scheduling policy that selects the waiting process with the smallest execution time to execute next. SJN, also known as Shortest Job Next (SJN), can be preemptive or non-preemptive. Â Characteristics of SJF Scheduling: Shortest Job first has th
13 min read
Job Scheduling with two jobs allowed at a time
Given a 2d array jobs[][] of order n * 2, where each element jobs[i], contains two integers, representing the start and end time of the job. Your task is to check if it is possible to complete all the jobs, provided that two jobs can be done simultaneously at a particular moment. Note: If a job star
6 min read
Optimal Page Replacement Algorithm
In operating systems, whenever a new page is referred and not present in memory, page fault occurs, and Operating System replaces one of the existing pages with newly needed page. Different page replacement algorithms suggest different ways to decide which page to replace. The target for all algorit
3 min read
Greedy algorithm on Graph