The Wayback Machine - https://web.archive.org/web/20240930054736/https://www.geeksforgeeks.org/the-skyline-problem-using-divide-and-conquer-algorithm/
Open In App

The Skyline Problem | Set-1

Last Updated : 23 Nov, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given n rectangular buildings in a 2-dimensional city, computes the skyline of these buildings, eliminating hidden lines. The main task is to view buildings from a side and remove all sections that are not visible.  All buildings share a common bottom and every building is represented by a triplet (left, ht, right)

  • ‘left’: is the x coordinate of the left side (or wall).
  • ‘right’: is x coordinate of right side
  • ‘ht’: is the height of the building.

A skyline is a collection of rectangular strips. A rectangular strip is represented as a pair (left, ht) where left is x coordinate of the left side of the strip and ht is the height of the strip.

Examples:

Input: buildings[][] = { {1, 11, 5}, {2, 6, 7}, {3, 13, 9}, {12, 7, 16}, {14, 3, 25}, {19, 18, 22}, {23, 13, 29}, {24, 4, 28} }

Output: { {1, 11}, {3, 13}, {9, 0}, {12, 7}, {16, 3}, {19, 18}, {22, 3}, {23, 13}, {29, 0} }

Explanation:

The skyline is formed based on the key-points (representing by “green” dots)
eliminating hidden walls of the buildings.

sl1
The Skyline Problem

Input: buildings[ ][ ] = { {1, 11, 5} }

Output: { {1, 11}, {5, 0} }

Skyline Problem Using Divide and Conquer

We can find Skyline using Divide and Conquer. The idea is similar to Merge Sort, divide the given set of buildings in two subsets. Recursively construct skyline for two halves and finally merge the two skylines. Start from first strips of two skylines, compare x coordinates. Pick the strip with smaller x coordinate and add it to result. The height of added strip is considered as maximum of current heights from skyline1 and skyline2.

Below is implementation of above idea. 

C++

// A divide and conquer based C++
// program to find skyline of given buildings
#include <iostream>
using namespace std;

// A structure for building
struct Building {
    // x coordinate of left side
    int left;

    // height
    int ht;

    // x coordinate of right side
    int right;
};

// A strip in skyline
class Strip {
    // x coordinate of left side
    int left;

    // height
    int ht;

public:
    Strip(int l = 0, int h = 0)
    {
        left = l;
        ht = h;
    }
    friend class SkyLine;
};

// Skyline: To represent Output(An array of strips)
class SkyLine {
    // Array of strips
    Strip* arr;

    // Capacity of strip array
    int capacity;

    // Actual number of strips in array
    int n;

public:
    ~SkyLine() { delete[] arr; }
    int count() { return n; }

    // A function to merge another skyline
    // to this skyline
    SkyLine* Merge(SkyLine* other);

    // Constructor
    SkyLine(int cap)
    {
        capacity = cap;
        arr = new Strip[cap];
        n = 0;
    }

    // Function to add a strip 'st' to array
    void append(Strip* st)
    {
        // Check for redundant strip, a strip is
        // redundant if it has same height or left as
        // previous
        if (n > 0 && arr[n - 1].ht == st->ht)
            return;
        if (n > 0 && arr[n - 1].left == st->left) {
            arr[n - 1].ht = max(arr[n - 1].ht, st->ht);
            return;
        }

        arr[n] = *st;
        n++;
    }

    // A utility function to print all strips of
    // skyline
    void print()
    {
        for (int i = 0; i < n; i++) {
            cout << " (" << arr[i].left << ", " << arr[i].ht
                 << "), ";
        }
    }
};

// This function returns skyline for a
// given array of buildings arr[l..h].
// This function is similar to mergeSort().
SkyLine* findSkyline(Building arr[], int l, int h)
{
    if (l == h) {
        SkyLine* res = new SkyLine(2);
        res->append(new Strip(arr[l].left, arr[l].ht));
        res->append(new Strip(arr[l].right, 0));
        return res;
    }

    int mid = (l + h) / 2;

    // Recur for left and right halves
    // and merge the two results
    SkyLine* sl = findSkyline(arr, l, mid);
    SkyLine* sr = findSkyline(arr, mid + 1, h);
    SkyLine* res = sl->Merge(sr);

    // To avoid memory leak
    delete sl;
    delete sr;

    // Return merged skyline
    return res;
}

// Similar to merge() in MergeSort
// This function merges another skyline
// 'other' to the skyline for which it is called.
// The function returns pointer to the
// resultant skyline
SkyLine* SkyLine::Merge(SkyLine* other)
{
    // Create a resultant skyline with
    // capacity as sum of two skylines
    SkyLine* res = new SkyLine(this->n + other->n);

    // To store current heights of two skylines
    int h1 = 0, h2 = 0;

    // Indexes of strips in two skylines
    int i = 0, j = 0;
    while (i < this->n && j < other->n) {
        // Compare x coordinates of left sides of two
        // skylines and put the smaller one in result
        if (this->arr[i].left < other->arr[j].left) {
            int x1 = this->arr[i].left;
            h1 = this->arr[i].ht;

            // Choose height as max of two heights
            int maxh = max(h1, h2);

            res->append(new Strip(x1, maxh));
            i++;
        }
        else {
            int x2 = other->arr[j].left;
            h2 = other->arr[j].ht;
            int maxh = max(h1, h2);
            res->append(new Strip(x2, maxh));
            j++;
        }
    }

    // If there are strips left in this
    // skyline or other skyline
    while (i < this->n) {
        res->append(&arr[i]);
        i++;
    }
    while (j < other->n) {
        res->append(&other->arr[j]);
        j++;
    }
    return res;
}

// Driver Function
int main()
{
    Building arr[]
        = { { 1, 11, 5 },   { 2, 6, 7 },   { 3, 13, 9 },
            { 12, 7, 16 },  { 14, 3, 25 }, { 19, 18, 22 },
            { 23, 13, 29 }, { 24, 4, 28 } };
    int n = sizeof(arr) / sizeof(arr[0]);

    // Find skyline for given buildings
    // and print the skyline
    SkyLine* ptr = findSkyline(arr, 0, n - 1);
    cout << " Skyline for given buildings is \n";
    ptr->print();
    return 0;
}

Java

// A divide and conquer based Java
// program to find skyline of given buildings
import java.util.*;
// A class for building
class Building {
    int left, ht, right;

    public Building(int left, int ht, int right) {
        this.left = left;
        this.ht = ht;
        this.right = right;
    }
}
// A strip in skyline
class Strip {
    int left, ht;

    public Strip(int left, int ht) {
        this.left = left;
        this.ht = ht;
    }
}
// Skyline: To represent Output(An array of strips)
class SkyLine {
    List<Strip> arr;
    int capacity, n;

    public SkyLine(int cap) {
        this.arr = new ArrayList<>();
        this.capacity = cap;
        this.n = 0;
    }

    public int count() {
        return this.n;
    }

// A function to merge another skyline
    // to this skyline

    public SkyLine merge(SkyLine other) {
        SkyLine res = new SkyLine(this.n + other.n);
        int h1 = 0, h2 = 0, i = 0, j = 0;
        while (i < this.n && j < other.n) {
            if (this.arr.get(i).left < other.arr.get(j).left) {
                int x1 = this.arr.get(i).left;
                h1 = this.arr.get(i).ht;
                int maxh = Math.max(h1, h2);
                res.append(new Strip(x1, maxh));
                i++;
            } else {
                int x2 = other.arr.get(j).left;
                h2 = other.arr.get(j).ht;
                int maxh = Math.max(h1, h2);
                res.append(new Strip(x2, maxh));
                j++;
            }
        }
        while (i < this.n) {
            res.append(this.arr.get(i));
            i++;
        }
        while (j < other.n) {
            res.append(other.arr.get(j));
            j++;
        }
        return res;
    }

// Function to add a strip 'st' to array
    public void append(Strip st) {
        if (this.n > 0 && this.arr.get(this.n-1).ht == st.ht) {
            return;
        }
        if (this.n > 0 && this.arr.get(this.n-1).left == st.left) {
            this.arr.get(this.n-1).ht = Math.max(this.arr.get(this.n-1).ht, st.ht);
            return;
        }
        this.arr.add(st);
        this.n++;
    }

// A utility function to print all strips of
    // skyline
    public void printSkyline() {
        System.out.println("Skyline for given buildings is:");
        for (int i = 0; i < this.n; i++) {
            System.out.print("(" + this.arr.get(i).left + ", " + this.arr.get(i).ht + "), ");
        }
        System.out.println();
    }
}

// This function returns skyline for a
// given array of buildings arr[l..h].
// This function is similar to mergeSort().
class SkylineProblem {
    public static SkyLine findSkyline(Building[] arr, int l, int h) {
        if (l == h) {
            SkyLine res = new SkyLine(2);
            res.append(new Strip(arr[l].left, arr[l].ht));
            res.append(new Strip(arr[l].right, 0));
            return res;
        }
        int mid = (l + h) / 2;
        
        
    // Recur for left and right halves
    // and merge the two results
        SkyLine sl = findSkyline(arr, l, mid);
        SkyLine sr = findSkyline(arr, mid+1, h);
        SkyLine res = sl.merge(sr);
        return res;
    }
    
// Driver Code
public static void main(String[] args) {
    
Building[] arr = {new Building(1, 11, 5), new Building(2, 6, 7), new Building(3, 13, 9),
new Building(12, 7, 16), new Building(14, 3, 25), new Building(19, 18, 22),
new Building(23, 13, 29), new Building(24, 4, 28)};

// Find skyline for given buildings
    // and print the skyline
SkyLine res = findSkyline(arr, 0, arr.length-1);
res.printSkyline();
}
}

/* Output:
Skyline for given buildings is:
(1, 11), (3, 13), (9, 0), (12, 18), (22, 3), (25, 0), (28, 4), (29, 0),
*/

Python3

class Building:
    def __init__(self, left, ht, right):
        self.left = left
        self.ht = ht
        self.right = right

class Strip:
    def __init__(self, left=0, ht=0):
        self.left = left
        self.ht = ht

class SkyLine:
    def __init__(self, cap):
        self.arr = []
        self.capacity = cap
        self.n = 0

    def count(self):
        return self.n

    def merge(self, other):
        res = SkyLine(self.n + other.n)
        h1, h2, i, j = 0, 0, 0, 0
        while i < self.n and j < other.n:
            if self.arr[i].left < other.arr[j].left:
                x1, h1 = self.arr[i].left, self.arr[i].ht
                maxh = max(h1, h2)
                res.append(Strip(x1, maxh))
                i += 1
            else:
                x2, h2 = other.arr[j].left, other.arr[j].ht
                maxh = max(h1, h2)
                res.append(Strip(x2, maxh))
                j += 1
        while i < self.n:
            res.append(self.arr[i])
            i += 1
        while j < other.n:
            res.append(other.arr[j])
            j += 1
        return res

    def append(self, st):
        if self.n > 0 and self.arr[self.n-1].ht == st.ht:
            return
        if self.n > 0 and self.arr[self.n-1].left == st.left:
            self.arr[self.n-1].ht = max(self.arr[self.n-1].ht, st.ht)
            return
        self.arr.append(st)
        self.n += 1

    def print_skyline(self):
        print("Skyline for given buildings is")
        for i in range(self.n):
            print(" ({}, {}),".format(self.arr[i].left, self.arr[i].ht), end="")
        print()

def find_skyline(arr, l, h):
    if l == h:
        res = SkyLine(2)
        res.append(Strip(arr[l].left, arr[l].ht))
        res.append(Strip(arr[l].right, 0))
        return res
    mid = (l + h) // 2
    sl = find_skyline(arr, l, mid)
    sr = find_skyline(arr, mid+1, h)
    res = sl.merge(sr)
    return res

arr = [Building(1, 11, 5), Building(2, 6, 7), Building(3, 13, 9), Building(12, 7, 16), Building(14, 3, 25), Building(19, 18, 22), Building(23, 13, 29), Building(24, 4, 28)]
n = len(arr)
skyline = find_skyline(arr, 0, n-1)
skyline.print_skyline()

C#

// A divide and conquer based Java
// program to find skyline of given buildings
using System;
using System.Collections.Generic;

// A class for building
public class Building {
    public int left, ht, right;

    public Building(int left, int ht, int right) {
        this.left = left;
        this.ht = ht;
        this.right = right;
    }
}

// A strip in skyline
public class Strip {
    public int left, ht;

    public Strip(int left, int ht) {
        this.left = left;
        this.ht = ht;
    }
}

// Skyline: To represent Output(An array of strips)
public class SkyLine {
    public List<Strip> arr;
    public int capacity, n;

    public SkyLine(int cap) {
        this.arr = new List<Strip>();
        this.capacity = cap;
        this.n = 0;
    }

    public int count() {
        return this.n;
    }

// A function to merge another skyline
    // to this skyline
    public SkyLine merge(SkyLine other) {
        SkyLine res = new SkyLine(this.n + other.n);
        int h1 = 0, h2 = 0, i = 0, j = 0;
        while (i < this.n && j < other.n) {
            if (this.arr[i].left < other.arr[j].left) {
                int x1 = this.arr[i].left;
                h1 = this.arr[i].ht;
                int maxh = Math.Max(h1, h2);
                res.append(new Strip(x1, maxh));
                i++;
            } else {
                int x2 = other.arr[j].left;
                h2 = other.arr[j].ht;
                int maxh = Math.Max(h1, h2);
                res.append(new Strip(x2, maxh));
                j++;
            }
        }
        while (i < this.n) {
            res.append(this.arr[i]);
            i++;
        }
        while (j < other.n) {
            res.append(other.arr[j]);
            j++;
        }
        return res;
    }

// Function to add a strip 'st' to array
    public void append(Strip st) {
        if (this.n > 0 && this.arr[this.n-1].ht == st.ht) {
            return;
        }
        if (this.n > 0 && this.arr[this.n-1].left == st.left) {
            this.arr[this.n-1].ht = Math.Max(this.arr[this.n-1].ht, st.ht);
            return;
        }
        this.arr.Add(st);
        this.n++;
    }

// A utility function to print all strips of
    // skyline
    public void printSkyline() {
        Console.WriteLine("Skyline for given buildings is:");
        for (int i = 0; i < this.n; i++) {
            Console.Write("(" + this.arr[i].left + ", " + this.arr[i].ht + "), ");
        }
        Console.WriteLine();
    }
}

// This function returns skyline for a
// given array of buildings arr[l..h].
// This function is similar to mergeSort().
public class SkylineProblem {
    public static SkyLine findSkyline(Building[] arr, int l, int h) {
        if (l == h) {
            SkyLine res2 = new SkyLine(2);
            res2.append(new Strip(arr[l].left, arr[l].ht));
            res2.append(new Strip(arr[l].right, 0));
            return res2;
        }
        int mid = (l + h) / 2;
        
    // Recur for left and right halves
    // and merge the two results
        SkyLine sl = findSkyline(arr, l, mid);
        SkyLine sr = findSkyline(arr, mid+1, h);
        SkyLine res3 = sl.merge(sr);
        return res3;
    }
    
// Driver Code
    public static void Main(string[] args) {
    Building[] arr = {new Building(1, 11, 5), new Building(2, 6, 7), new Building(3, 13, 9),
    new Building(12, 7, 16), new Building(14, 3, 25), new Building(19, 18, 22),
    new Building(23, 13, 29), new Building(24, 4, 28)};

    // Find skyline for given buildings and print the skyline
    SkyLine res1 = findSkyline(arr, 0, arr.Length-1);
    res1.printSkyline();
}
}

JavaScript

// Js program to find skyline of given buildings

// A structure for building
const Building = {
    left: Number,
    ht: Number,
    right: Number,
};

class Strip {
    constructor(l = 0, h = 0) {
        this.left = l;
        this.ht = h;
    }
}

class SkyLine {
    constructor(cap) {
        this.capacity = cap;
        this.arr = new Array(cap);
        this.n = 0;
    }
    count() {
        return this.n;
    }
    Merge(other) {
        let res = new SkyLine(this.n + other.n);
        let h1 = 0, h2 = 0;
        let i = 0, j = 0;
        // Merge two skylines by comparing the left coordinates of the strips
        while (i < this.n && j < other.n) {
            if (this.arr[i].left < other.arr[j].left) {
                let x1 = this.arr[i].left;
                h1 = this.arr[i].ht;
                let maxh = Math.max(h1, h2);
                res.append(new Strip(x1, maxh));
                i++;
            } else {
                let x2 = other.arr[j].left;
                h2 = other.arr[j].ht;
                let maxh = Math.max(h1, h2);
                res.append(new Strip(x2, maxh));
                j++;
            }
        }
        // Append remaining strips from skyline 1 and 2
        while (i < this.n) {
            res.append(this.arr[i]);
            i++;
        }
        while (j < other.n) {
            res.append(other.arr[j]);
            j++;
        }
        return res;
    }
    // Append a strip to skyline if it is not redundant
    append(st) {
        if (this.n > 0 && this.arr[this.n - 1].ht == st.ht) {
            return;
        }
        if (this.n > 0 && this.arr[this.n - 1].left == st.left) {
            this.arr[this.n - 1].ht = Math.max(this.arr[this.n - 1].ht, st.ht);
            return;
        }
        this.arr[this.n] = st;
        this.n++;
    }
    // Print the skyline strips
    print() {
        let str = '';
        for (let i = 0; i < this.n; i++) {
            str += `(${this.arr[i].left}, ${this.arr[i].ht}), `;
        }
        console.log(`Skyline for given buildings is \n${str}`);
    }
}

function findSkyline(arr, l, h) {
    if (l == h) {
        // Base case: when a single building is left
        let res = new SkyLine(2);
        res.append(new Strip(arr[l].left, arr[l].ht));
        res.append(new Strip(arr[l].right, 0));
        return res;
    }
    // Divide and Conquer approach
    let mid = Math.floor((l + h) / 2);
    let sl = findSkyline(arr, l, mid);
    let sr = findSkyline(arr, mid + 1, h);
    let res = sl.Merge(sr);
    delete sl;
    delete sr;
    return res;
}

const main = () => {
const arr = [
{ left: 1, ht: 11, right: 5 },
{ left: 2, ht: 6, right: 7 },
{ left: 3, ht: 13, right: 9 },
{ left: 12, ht: 7, right: 16 },
{ left: 14, ht: 3, right: 25 },
{ left: 19, ht: 18, right: 22 },
{ left: 23, ht: 13, right: 29 },
{ left: 24, ht: 4, right: 28 },
];
const n = arr.length;
const ptr = findSkyline(arr, 0, n - 1);
console.log("Skyline for given buildings is");
ptr.print();
};

main();

Output

 Skyline for given buildings is 
 (1, 11),  (3, 13),  (9, 0),  (12, 7),  (16, 3),  (19, 18),  (22, 3),  (23, 13),  (29, 0), 

Time Complexity: O(n logn)
Auxilary Space:O(n)

Refer to the below article for solving the above problem using multiset



Previous Article
Next Article

Similar Reads

The Skyline Problem | Set 2
Given n rectangular buildings in a 2-dimensional city, computes the skyline of these buildings, eliminating hidden lines. The main task is to view buildings from aside and remove all sections that are not visible. All buildings share a common bottom and every building is represented by a triplet (left, ht, right) left: is x coordinated on the left
8 min read
Transportation Problem | Set 7 ( Degeneracy in Transportation Problem )
Please go through this article first. This article will discuss degeneracy in transportation problem through an explained example. Solution: This problem is balanced transportation problem as total supply is equal to total demand. Initial basic feasible solution: Least Cost Cell Method will be used here to find the initial basic feasible solution.
3 min read
Secretary Problem (A Optimal Stopping Problem)
The Secretary Problem also known as marriage problem, the sultan's dowry problem, and the best choice problem is an example of Optimal Stopping Problem. This problem can be stated in the following form: Imagine an administrator who wants to hire the best secretary out of n rankable applicants for a position. The applicants are interviewed one by on
12 min read
Nuts & Bolts Problem (Lock & Key problem) using Quick Sort
Given a set of n nuts of different sizes and n bolts of different sizes. There is a one-one mapping between nuts and bolts. Match nuts and bolts efficiently. Constraint: Comparison of a nut to another nut or a bolt to another bolt is not allowed. It means a nut can only be compared with a bolt and a bolt can only be compared with a nut to see which
12 min read
Nuts & Bolts Problem (Lock & Key problem) using Hashmap
Given a set of n nuts of different sizes and n bolts of different sizes. There is a one-one mapping between nuts and bolts. Match nuts and bolts efficiently. Constraint: Comparison of a nut to another nut or a bolt to another bolt is not allowed. It means nut can only be compared with bolt and bolt can only be compared with a nut to see which one i
5 min read
Difference between 0/1 Knapsack problem and Fractional Knapsack problem
What is Knapsack Problem?Suppose you have been given a knapsack or bag with a limited weight capacity, and each item has some weight and value. The problem here is that "Which item is to be placed in the knapsack such that the weight limit does not exceed and the total value of the items is as large as possible?". Consider the real-life example. Su
13 min read
Shortest Superstring Problem | Set 2 (Using Set Cover)
Given a set of n strings S, find the smallest string that contains each string in the given set as substring. We may assume that no string in arr[] is substring of another string. Examples: Input: S = {"001", "01101", "010"} Output: 0011010 Input: S = {"geeks", "quiz", "for"} Output: geeksquizfor Input: S = {"catg", "ctaagt", "gcta", "ttca", "atgca
3 min read
Word Break Problem | DP-32 | Set - 2
Given a non-empty sequence S and a dictionary dict[] containing a list of non-empty words, print all possible ways to break the sentence in individual dictionary words.Examples: Input: S = "catsanddog" dict[] = {"cat", "cats", "and", "sand", "dog"} Output: "cats and dog" "cat sand dog"Input: S = "pineapplepenapple" dict[] = {"apple", "pen", "applep
15 min read
Job Selection Problem - Loss Minimization Strategy | Set 2
We have discussed one loss minimization strategy before: Job Sequencing Problem – Loss Minimization. In this article, we will look at another strategy that applies to a slightly different problem.We are given a sequence of N goods of production numbered from 1 to N. Each good has a volume denoted by (Vi). The constraint is that once a good has been
9 min read
Problem on permutations and combinations | Set 2
Prerequisite : Permutation and Combination Given a polygon of m sides, count number of triangles that can be formed using vertices of polygon. Answer : [m (m - 1)(m - 2) / 6] Explanation : There are m vertices in a polygon with m sides. We need to count different combinations of three points chosen from m. So answer is mC3 = m * (m - 1) * (m - 2) /
4 min read
Print equal sum sets of array (Partition problem) | Set 1
Given an array arr[]. Determine whether it is possible to split the array into two sets such that the sum of elements in both the sets is equal. If it is possible, then print both the sets. If it is not possible then output -1. Examples : Input : arr = {5, 5, 1, 11} Output : Set 1 = {5, 5, 1}, Set 2 = {11} Sum of both the sets is 11 and equal. Inpu
14 min read
Mobile Numeric Keypad Problem | Set 2
Given the mobile numeric keypad. You can only press buttons that are up, left, right or down to the current button or can choose to press the same button again. Round corner buttons (i.e. * and # ) are invalid moves. Given a number N, You have to find the distinct numbers of length N you can dial by starting from any number from 0-9, under the cons
12 min read
Transportation Problem Set 8 | Transshipment Model-1
Transshipment Model is a model which comes under the transportation problem. There are two types of transshipment problem: With sources and destination acting as transient (i.e. intermediary) nodesWith some transient nodes between sources and destination Look at the given transportation problem diagram. In a transportation problem, the shipment mov
3 min read
Proof that Clique Decision problem is NP-Complete | Set 2
Prerequisite: NP-Completeness, Clique problem. A clique in a graph is a set of vertices where each vertex shares an edge with every other vertex. Thus, a clique in a graph is a subgraph which is a complete graph. Problem: Given a graph G(V, E) and an integer K, the problem is to determine if the graph contains a clique of size K. Explanation: An in
5 min read
Hungarian Algorithm for Assignment Problem | Set 2 (Implementation)
Given a 2D array, arr of size N*N where arr[i][j] denotes the cost to complete the jth job by the ith worker. Any worker can be assigned to perform any job. The task is to assign the jobs such that exactly one worker can perform exactly one job in such a way that the total cost of the assignment is minimized. Example Input: arr[][] = {{3, 5}, {10,
7 min read
The Celebrity Problem | Set-2
In a party of N people, only one person is known to everyone. Such a person may be present at the party, if yes, (s)he doesn’t know anyone in the party. We can only ask questions like “does A know B? “. Find the stranger (celebrity) in the minimum number of questions.We can describe the problem input as an array of numbers/characters representing p
5 min read
The Celebrity Problem | Set-3
In a party of N people, only one person is known to everyone. Such a person may be present at the party, if yes, (s)he doesn’t know anyone in the party. We can only ask questions like “does A know B? “. Find the stranger (celebrity) in the minimum number of questions.We can describe the problem input as an array of numbers/characters representing p
4 min read
Prove that a problem consisting of Clique and Independent Set is NP Complete
Prerequisite: NP-Completeness, NP Class, Clique, Independent Set Problem: Given an undirected graph G = (V, E) and an integer K, determine if a clique of size K as well as an independent set (IS) of size K, exists. Demonstrate that it is an NP Complete. Explanation: A Clique is a subgraph of a graph in which all of the vertices are connected, formi
6 min read
Transportation Problem | Set 3 (Least Cost Cell Method)
The North-West Corner method has been discussed in the previous article. In this article, the Least Cost Cell method will be discussed. Solution: According to the Least Cost Cell method, the least cost among all the cells in the table has to be found which is 1 (i.e. cell (O1, D2)). Now check the supply from the row O1 and demand for column D2 and
2 min read
Transportation Problem | Set 5 ( Unbalanced )
An introduction to the transportation problem has been discussed in this article. In this article, the method to solve the unbalanced transportation problem will be discussed. Below transportation problem is an unbalanced transportation problem. The problem is unbalanced because the sum of all the supplies i.e. O1 , O2 , O3 and O4 is not equal to t
1 min read
Transportation Problem | Set 6 (MODI Method - UV Method)
There are two phases to solve the transportation problem. In the first phase, the initial basic feasible solution has to be found and the second phase involves optimization of the initial basic feasible solution that was obtained in the first phase. There are three methods for finding an initial basic feasible solution, NorthWest Corner MethodLeast
7 min read
Hitting Set problem is NP Complete
Prerequisite: NP CompleteProblem: Given a ground set X of elements and also a grouping collection C of subsets available in X and an integer k, the task is to find the smallest subset of X, such that the smallest subset, H hits every set comprised in C. This implies that the intersection of H and S is null for every set S belonging to C, with size
3 min read
Transportation Problem | Set 2 (NorthWest Corner Method)
An introduction to Transportation problem has been discussed in the previous article, in this article, finding the initial basic feasible solution using the NorthWest Corner Cell Method will be discussed. Explanation: Given three sources O1, O2 and O3 and four destinations D1, D2, D3 and D4. For the sources O1, O2 and O3, the supply is 300, 400 and
7 min read
Largest Independent Set Problem using Dynamic Programming
Given a Binary Tree, find size of the Largest Independent Set(LIS) in it. A subset of all tree nodes is an independent set if there is no edge between any two nodes of the subset. For example, consider the following binary tree. The largest independent set(LIS) is {10, 40, 60, 70, 80} and size of the LIS is 5. Recommended PracticeLargest Independen
15+ min read
Greedy Approximate Algorithm for Set Cover Problem
Given a universe U of n elements, a collection of subsets of U say S = {S1, S2...,Sm} where every subset Si has an associated cost. Find a minimum cost subcollection of S that covers all elements of U. Example: U = {1,2,3,4,5} S = {S1,S2,S3} S1 = {4,1,3}, Cost(S1) = 5 S2 = {2,5}, Cost(S2) = 10 S3 = {1,4,3,2}, Cost(S3) = 3 Output: Minimum cost of se
6 min read
Chocolate Distribution Problem | Set 2
Given an array A[] consisting of N integers, where each value represents the marks of the ith student, the task is to find the minimum number of chocolates required to be distributed such that: Each student should be awarded with at least one chocolateA student with higher marks should be awarded more chocolates than his adjacent students. Examples
15+ min read
Transportation Problem | Set 1 (Introduction)
Transportation problem is a special kind of Linear Programming Problem (LPP) in which goods are transported from a set of sources to a set of destinations subject to the supply and demand of the sources and destination respectively such that the total cost of transportation is minimized. It is also sometimes called as Hitchcock problem. Types of Tr
2 min read
CSES Problem Set Solutions
In this article, we have compiled comprehensive, high-quality tutorials on the CSES Problem Set Solutions to assist you in understanding the problem set for learning algorithmic programming. What is CSES Problem Set?CSES Problem Set is a collection of competitive programming tasks hosted on the CSES website. These problems cover a wide range of top
8 min read
Transportation Problem | Set 4 (Vogel's Approximation Method)
The North-West Corner method and the Least Cost Cell method has been discussed in the previous articles. In this article, the Vogel's Approximation method will be discussed. Solution: For each row find the least value and then the second least value and take the absolute difference of these two least values and write it in the corresponding row dif
14 min read
Set Mismatch Problem
Given an integer array arr[], which originally contains all the numbers from 1 to n. Due to some error, one of the numbers in arr[] got duplicated to another number in arr[], which results in repetition of one number and loss of another number. Find the number that occurs twice and the number that is missing and return them as an array. Examples: I
7 min read
Article Tags :
Practice Tags :