Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on Queue
  • Practice Queue
  • MCQs on Queue
  • Queue Tutorial
  • Operations
  • Applications
  • Implementation
  • Stack vs Queue
  • Types of Queue
  • Circular Queue
  • Deque
  • Priority Queue
  • Stack using Queue
  • Advantages & Disadvantages
Open In App
Next Article:
Search in a Row-wise and Column-wise Sorted 2D Array using Divide and Conquer algorithm
Next article icon

The Skyline Problem | Set-1

Last Updated : 25 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given n rectangular buildings in a 2-dimensional city, compute 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. I

Examples:

Input: build[][] = [[1, 5, 11 ], [2, 7, 6 ], [3, 9, 13 ], [ 12, 16, 7 ], [ 14, 25, 3 ], [ 19, 22, 18 ], [ 23, 29, 13 ], [ 24, 28, 4 ]]
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. Note that no end point of the second building (2, 7, 6) is considered because it completely overlaps. Also, the points where the y coordinate changes are considered (Note that the top right of the third building (3, 9, 13) is not considered because it has same y coordinate.

sl1
The Skyline Problem

Input: build[ ][ ] = [[1, 5, 11]]
Output: [[ 1, 11 ], [ 5, 0 ]]

Common Background For Solutions

Let us understand the problem better with the first example [[1, 5, 11 ], [2, 7, 6 ], [3, 9, 13 ], [ 12, 16, 7 ], [ 14, 25, 3 ], [ 19, 22, 18 ], [ 23, 29, 13 ], [ 24, 28, 4 ]]

One thing is obvious, we build the skyline from left to right. Now we know the point [1, 11] is going to be in the output as it is the leftmost point.

If we take a look at the right point of the first building which is [5, 11], we find that this point cannot be considered because there is a higher height building (third building in our input array [3, 9, 13[). So we ignore the right point.

Now we see the second building, its both left and right are covered. Left is covered by first building and right is covered by third building because its height is smaller than both of its neighbors. So we ignore the second building completely.

We process all the remaining building same way.

Naive Sweep Line Algorithm - O(n^2) Time and O(n) Space

  • Get all corner x coordinates of all buildings in an array say points[]. We are mainly going to have 2n points in this array as we have left and right for every building.
  • Sort the points[] to simulate the sweep line from left to right.
  • Now traverse through the sorted point[] and for every x point check which building has the maximum height at this point and add the maximum height to the skyline if the maximum height is different from the previously added height to the skyline.
C++
#include <iostream> #include <vector> #include <algorithm> using namespace std;  vector<pair<int, int>> getSkyline(vector<vector<int>>& build) {     vector<int> points;      // Collect all left and right x-coordinates     // of buildings     for (auto& b : build) {         points.push_back(b[0]);         points.push_back(b[1]);     }      // Sort all critical points     sort(points.begin(), points.end());      vector<pair<int, int>> res;     int prev = 0;      // Traverse through each point to     // determine skyline height     for (int x : points) {         int maxH = 0;          // Check which buildings cover the          // current x and get the max height         for (auto& b : build) {             int l = b[0], r = b[1], h = b[2];             if (l <= x && x < r) {                 maxH = max(maxH, h);             }         }          // Add to result if height has changed         if (res.empty() || maxH != prev) {             res.push_back({x, maxH});             prev = maxH;         }     }      return res; }  int main() {     vector<vector<int>> build = {         {2, 9, 10},         {3, 6, 15},         {5, 12, 12}     };      vector<pair<int, int>> skyline = getSkyline(build);      for (auto& p : skyline) {         cout << "(" << p.first << ", " << p.second << ") ";     }      cout << endl;     return 0; } 
Java
import java.util.*;  class Solution {     public List<int[]> getSkyline(int[][] build) {         List<Integer> points = new ArrayList<>();          // Collect all left and right x-coordinates         // of buildings         for (int[] b : build) {             points.add(b[0]);             points.add(b[1]);         }          // Sort all critical points         Collections.sort(points);          List<int[]> res = new ArrayList<>();         int prev = 0;          // Traverse through each point to         // determine skyline height         for (int x : points) {             int maxH = 0;              // Check which buildings cover the              // current x and get the max height             for (int[] b : build) {                 int l = b[0], r = b[1], h = b[2];                 if (l <= x && x < r) {                     maxH = Math.max(maxH, h);                 }             }              // Add to result if height has changed             if (res.isEmpty() || maxH != prev) {                 res.add(new int[]{x, maxH});                 prev = maxH;             }         }          return res;     }      public static void main(String[] args) {         int[][] build = {             {2, 9, 10},             {3, 6, 15},             {5, 12, 12}         };          Solution sol = new Solution();         List<int[]> skyline = sol.getSkyline(build);          for (int[] p : skyline) {             System.out.print("(" + p[0] + ", " + p[1] + ") ");         }          System.out.println();     } } 
Python
def getSkyline(build):     points = []      # Collect all left and right x-coordinates     # of buildings     for b in build:         points.append(b[0])         points.append(b[1])      # Sort all critical points     points.sort()      res = []     prev = 0      # Traverse through each point to     # determine skyline height     for x in points:         maxH = 0          # Check which buildings cover the          # current x and get the max height         for b in build:             l, r, h = b             if l <= x < r:                 maxH = max(maxH, h)          # Add to result if height has changed         if not res or maxH != prev:             res.append((x, maxH))             prev = maxH      return res  if __name__ == '__main__':     build = [         [2, 9, 10],         [3, 6, 15],         [5, 12, 12]     ]      skyline = getSkyline(build)      for p in skyline:         print(f'({p[0]}, {p[1]}) ', end='')      print() 
C#
using System; using System.Collections.Generic;  class Solution {     public IList<int[]> GetSkyline(int[][] build) {         List<int> points = new List<int>();          // Collect all left and right x-coordinates         // of buildings         foreach (var b in build) {             points.Add(b[0]);             points.Add(b[1]);         }          // Sort all critical points         points.Sort();          List<int[]> res = new List<int[]>();         int prev = 0;          // Traverse through each point to         // determine skyline height         foreach (var x in points) {             int maxH = 0;              // Check which buildings cover the              // current x and get the max height             foreach (var b in build) {                 int l = b[0], r = b[1], h = b[2];                 if (l <= x && x < r) {                     maxH = Math.Max(maxH, h);                 }             }              // Add to result if height has changed             if (res.Count == 0 || maxH != prev) {                 res.Add(new int[] { x, maxH });                 prev = maxH;             }         }          return res;     }      public static void Main(string[] args) {         int[][] build = {             new int[] {2, 9, 10},             new int[] {3, 6, 15},             new int[] {5, 12, 12}         };          Solution sol = new Solution();         var skyline = sol.GetSkyline(build);          foreach (var p in skyline) {             Console.Write("(" + p[0] + ", " + p[1] + ") ");         }          Console.WriteLine();     } } 
JavaScript
function getSkyline(build) {     const points = [];      // Collect all left and right x-coordinates     // of buildings     for (const b of build) {         points.push(b[0]);         points.push(b[1]);     }      // Sort all critical points     points.sort((a, b) => a - b);      const res = [];     let prev = 0;      // Traverse through each point to     // determine skyline height     for (const x of points) {         let maxH = 0;          // Check which buildings cover the          // current x and get the max height         for (const b of build) {             const [l, r, h] = b;             if (l <= x && x < r) {                 maxH = Math.max(maxH, h);             }         }          // Add to result if height has changed         if (res.length === 0 || maxH !== prev) {             res.push([x, maxH]);             prev = maxH;         }     }      return res; }  const build = [     [2, 9, 10],     [3, 6, 15],     [5, 12, 12] ];  const skyline = getSkyline(build);  for (const p of skyline) {     process.stdout.write(`(${p[0]}, ${p[1]}) `); }  console.log(); 

Output
(2, 10) (3, 15) (6, 12) (12, 0)  

Using Sweep Line and Priority Queue - O(n Log n) Time and O(n) Space

The problem can be approached using a sweep line algorithm with a priority queue (max-heap) to maintain the heights of the buildings as the sweep line moves from left to right. The idea is to again store all points, but this time we also store building indexes. We use priority queue to have all building point in it when we reach the next points, so that we can quickly find the maximum.

Here’s a step-by-step explanation:

  1. Prepare Edges: For each building, store two edges (start and end) as a pair of coordinates: (x-coordinate, building index). This helps in processing all the building edges.
  2. Sort Edges: Sort the edges based on the x-coordinate. If two edges have the same x-coordinate, prioritize the left edges (start) over the right ones (end).
  3. Use Priority Queue: Traverse the sorted edges and maintain a priority queue that holds the current building heights (from the start edges) as well as their right endpoints.
  4. Process Each Edge: For each x-coordinate:
    • Add building heights when encountering a start edge.
    • Remove building heights when encountering an end edge (pop from the priority queue).
    • The current maximum height in the priority queue represents the height at the current x-coordinate.
  5. Add to Skyline: If the current height is different from the previous height, record the x-coordinate and height as a new point in the skyline.
  6. Return Result: The result is the list of (x-coordinate, height) pairs representing the visible parts of the skyline.
C++
#include <iostream> #include <vector> #include <queue> #include <algorithm> using namespace std;  vector<vector<int>> getSkyline(vector<vector<int>> &arr) {     vector<pair<int, int>> e;     priority_queue<pair<int, int>> pq;     vector<vector<int>> skyline;     int n = arr.size();      for (int i = 0; i < n; ++i) {         e.push_back({arr[i][0], i});  // start         e.push_back({arr[i][1], i});  // end     }      sort(e.begin(), e.end());      // Traverse sorted edges     int i = 0;      while (i < e.size()) {         int curr_height;         int curr_x = e[i].first;          // Add all buildings starting or ending         // at current x         while (i < e.size() && e[i].first == curr_x) {             int idx = e[i].second;              // Push building height and end x             if (arr[idx][0] == curr_x)                 pq.emplace(arr[idx][2], arr[idx][1]);              ++i;         }          // Remove buildings that have ended         while (!pq.empty() && pq.top().second <= curr_x)             pq.pop();          curr_height = pq.empty() ? 0 : pq.top().first;          if (skyline.empty() || skyline.back()[1] != curr_height)             skyline.push_back({curr_x, curr_height});     }      return skyline; }  int main() {     vector<vector<int>> arr = {         {1, 5, 11}, {2, 7, 6}, {3, 9, 13}, {12, 16, 7},         {14, 25, 3}, {19, 22, 18}, {23, 29, 13}, {24, 28, 4}     };      vector<vector<int>> result = getSkyline(arr);      for (const auto &p : result) {         cout << "[" << p[0] << ", " << p[1] << "] ";     }     cout << endl;      return 0; } 
Java
import java.util.*;  public class Skyline {     public static List<List<Integer>> getSkyline(int[][] arr, int n) {         int idx = 0;         List<int[]> e = new ArrayList<>();         PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> b[0] - a[0]);         List<List<Integer>> skyline = new ArrayList<>();          for (int i = 0; i < n; i++) {             e.add(new int[]{arr[i][0], i});              e.add(new int[]{arr[i][1], i});           }          Collections.sort(e, (a, b) -> Integer.compare(a[0], b[0]));          while (idx < e.size()) {             int curr_height;             int curr_x = e.get(idx)[0];              while (idx < e.size() && curr_x == e.get(idx)[0]) {                 int building_idx = e.get(idx)[1];                 if (arr[building_idx][0] == curr_x)                     pq.add(new int[]{arr[building_idx][2], arr[building_idx][1]});                 idx++;             }              while (!pq.isEmpty() && pq.peek()[1] <= curr_x)                 pq.poll();              curr_height = pq.isEmpty() ? 0 : pq.peek()[0];              if (skyline.isEmpty() || skyline.get(skyline.size() - 1).get(1) != curr_height)                 skyline.add(Arrays.asList(curr_x, curr_height));         }          return skyline;     }      public static void main(String[] args) {         int[][] arr = {             {1, 5, 11}, {2, 7, 6}, {3, 9, 13}, {12, 16, 7},             {14, 25, 3}, {19, 22, 18}, {23, 29, 13}, {24, 28, 4}         };         int n = 8;         List<List<Integer>> result = getSkyline(arr, n);          for (List<Integer> p : result) {             System.out.print("[" + p.get(0) + ", " + p.get(1) + "] ");         }         System.out.println();     } } 
Python
import heapq  def getSkyline(arr, n):     idx = 0     e = []     pq = []     skyline = []      for i in range(n):         e.append((arr[i][0], i))          e.append((arr[i][1], i))       e.sort()      while idx < len(e):         curr_x = e[idx][0]         while idx < len(e) and curr_x == e[idx][0]:             building_idx = e[idx][1]             if arr[building_idx][0] == curr_x:                 heapq.heappush(pq, (-arr[building_idx][2], arr[building_idx][1]))             idx += 1          while pq and pq[0][1] <= curr_x:             heapq.heappop(pq)          curr_height = 0 if not pq else -pq[0][0]          if not skyline or skyline[-1][1] != curr_height:             skyline.append([curr_x, curr_height])      return skyline  # Test arr = [[1, 5, 11], [2, 7, 6], [3, 9, 13], [12, 16, 7], [14, 25, 3], [19, 22, 18], [23, 29, 13], [24, 28, 4]] n = 8 result = getSkyline(arr, n) for p in result:     print(f"[{p[0]}, {p[1]}]", end=" ") print() 
C#
using System; using System.Collections.Generic;  class Skyline {     public static List<List<int>> GetSkyline(int[,] arr, int n)     {         int idx = 0;         List<int[]> e = new List<int[]>();          SortedSet<int[]> pq = new SortedSet<int[]>(Comparer<int[]>.Create((a, b) => a[0].CompareTo(b[0])));         List<List<int>> skyline = new List<List<int>>();          for (int i = 0; i < n; i++)         {             e.Add(new int[] { arr[i, 0], i });               e.Add(new int[] { arr[i, 1], i });          }          e.Sort((a, b) => a[0].CompareTo(b[0]));           while (idx < e.Count)         {             int curr_x = e[idx][0];              while (idx < e.Count && curr_x == e[idx][0])             {                 int building_idx = e[idx][1];                 if (arr[building_idx, 0] == curr_x)                     pq.Add(new int[] { arr[building_idx, 2], arr[building_idx, 1] }); // Add building height and end point                 idx++;             }              while (pq.Count > 0 && pq.Min[1] <= curr_x)                 pq.Remove(pq.Min);              int curr_height = pq.Count == 0 ? 0 : pq.Min[0];              if (skyline.Count == 0 || skyline[skyline.Count - 1][1] != curr_height)                 skyline.Add(new List<int> { curr_x, curr_height });         }          return skyline;     }      static void Main(string[] args)     {         int[,] arr = {             { 1, 5, 11 }, { 2, 7, 6 }, { 3, 9, 13 }, { 12, 16, 7 },             { 14, 25, 3 }, { 19, 22, 18 }, { 23, 29, 13 }, { 24, 28, 4 }         };          int n = 8;         var result = GetSkyline(arr, n);          foreach (var p in result)         {             Console.Write($"[{p[0]}, {p[1]}] ");         }         Console.WriteLine();     } } 
JavaScript
function getSkyline(arr, n) {     let idx = 0;     let e = [];     let pq = [];     let skyline = [];      for (let i = 0; i < n; i++) {         e.push([arr[i][0], i]);           e.push([arr[i][1], i]);      }      e.sort((a, b) => a[0] - b[0]);      while (idx < e.length) {         let curr_x = e[idx][0];          while (idx < e.length && curr_x === e[idx][0]) {             let building_idx = e[idx][1];             if (arr[building_idx][0] === curr_x) {                 pq.push([arr[building_idx][2], arr[building_idx][1]]);             }             idx++;         }          pq = pq.filter(item => item[1] > curr_x);           let curr_height = pq.length === 0 ? 0 : pq[0][0];          if (skyline.length === 0 || skyline[skyline.length - 1][1] !== curr_height) {             skyline.push([curr_x, curr_height]);         }     }      return skyline; }  let arr = [     [1, 5, 11], [2, 7, 6], [3, 9, 13], [12, 16, 7],     [14, 25, 3], [19, 22, 18], [23, 29, 13], [24, 28, 4] ]; let n = 8; let result = getSkyline(arr, n);  result.forEach(p => console.log(`[${p[0]}, ${p[1]}]`)); 

Output
[1, 11] [3, 13] [9, 0] [12, 7] [16, 3] [19, 18] [22, 3] [23, 13] [29, 0]  

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

  • The Skyline Problem | Set 2

Next Article
Search in a Row-wise and Column-wise Sorted 2D Array using Divide and Conquer algorithm

K

kartik
Improve
Article Tags :
  • Divide and Conquer
  • Heap
  • DSA
  • Arrays
  • priority-queue
Practice Tags :
  • Arrays
  • Divide and Conquer
  • Heap
  • priority-queue

Similar Reads

    Divide and Conquer Algorithm
    Divide and Conquer algorithm is a problem-solving strategy that involves. Divide : Break the given problem into smaller non-overlapping problems.Conquer : Solve Smaller ProblemsCombine : Use the Solutions of Smaller Problems to find the overall result.Examples of Divide and Conquer are Merge Sort, Q
    1 min read
    Introduction to Divide and Conquer Algorithm
    Divide and Conquer Algorithm is a problem-solving technique used to solve problems by dividing the main problem into subproblems, solving them individually and then merging them to find solution to the original problem. Divide and Conquer is mainly useful when we divide a problem into independent su
    9 min read
    Dynamic Programming vs Divide-and-Conquer
    In this article I’m trying to explain the difference/similarities between dynamic programming and divide and conquer approaches based on two examples: binary search and minimum edit distance (Levenshtein distance).The ProblemWhen I started to learn algorithms it was hard for me to understand the mai
    12 min read
    Decrease and Conquer
    As divide-and-conquer approach is already discussed, which include following steps: Divide the problem into a number of subproblems that are smaller instances of the same problem. Conquer the sub problems by solving them recursively. If the subproblem sizes are small enough, however, just solve the
    5 min read
    Advanced master theorem for divide and conquer recurrences
    The Master Theorem is a tool used to solve recurrence relations that arise in the analysis of divide-and-conquer algorithms. The Master Theorem provides a systematic way of solving recurrence relations of the form: T(n) = aT(n/b) + f(n) where a, b, and f(n) are positive functions and n is the size o
    5 min read

    Some standard Divide and Conquer Algorithms

    Write program to calculate pow(b, e)
    Given two numbers b and e, the task is to implement a function to compute b^e.Examples: Input: b = 3.00000, e = 5Output: 243.00000Input: b = 0.55000, e = 3Output: 0.16638Input: b = -0.67000, e = -7Output: -16.49971Table of Content[Naive Approach 1] Using Iteration - O(e) Time and O(1) Space[Naive Ap
    10 min read
    Karatsuba algorithm for fast multiplication using Divide and Conquer algorithm
    Given two binary strings that represent value of two integers, find the product of two strings. For example, if the first bit string is "1100" and second bit string is "1010", output should be 120.For simplicity, let the length of two strings be same and be n.A Naive Approach is to follow the proces
    15+ min read
    Strassen's Matrix Multiplication
    Given two square matrices arr[][] and brr[][] of order n * n. Your task is to multiply both the matrices and find the resultant matrix.Examples:Input: arr[][] = [ [7, 8], [2, 9] ]brr[][] = [ [14, 5], [5, 18] ]Output: [ [138, 179], [73, 172] ]Input: arr[][] = [ [17, 4], [17, 16] ]brr[][] = [ [9, 2],
    15+ min read
    Convex Hull using Divide and Conquer Algorithm
    In computational geometry, a convex hull is the smallest convex polygon that contains a given set of points. It is a fundamental concept with applications in various fields such as computer graphics, robotics, and image processing. Importance of Convex Hull:Convex hulls are important in computationa
    15 min read
    Quickhull Algorithm for Convex Hull
    Given a set of points, a Convex hull is the smallest convex polygon containing all the given points. Input : points[] = {{0, 3}, {1, 1}, {2, 2}, {4, 4}, {0, 0}, {1, 2}, {3, 1}, {3, 3}};Output : The points in convex hull are: (0, 0) (0, 3) (3, 1) (4, 4)Input : points[] = {{0, 3}, {1, 1}Output : Not P
    14 min read

    Binary Search based problems

    Peak Element in Array
    Given an array arr[] where no two adjacent elements are same, find the index of a peak element. An element is considered to be a peak element if it is strictly greater than its adjacent elements. If there are multiple peak elements, return the index of any one of them.Note: Consider the element befo
    12 min read
    Check for Majority Element in a sorted array
    Given an array arr of N elements, A majority element in an array arr of size N is an element that appears more than N/2 times in the array. The task is to write a function say isMajority() that takes an array (arr[] ), array’s size (n) and a number to be searched (x) as parameters and returns true i
    15+ min read
    K-th Element of Merged Two Sorted Arrays
    Given two sorted arrays of sizes m and n respectively, the task is to find the element that would be at the k-th position in the final sorted array formed by merging these two arrays.Examples: Input: a[] = [2, 3, 6, 7, 9], b[] = [1, 4, 8, 10], k = 5Output: 6Explanation: The final sorted array is [1,
    15+ min read
    Find the number of zeroes
    Given an array of 1s and 0s which has all 1s first followed by all 0s. Find the number of 0s. Count the number of zeroes in the given array.Examples : Input: arr[] = {1, 1, 1, 1, 0, 0} Output: 2 Input: arr[] = {1, 0, 0, 0, 0} Output: 4 Input: arr[] = {0, 0, 0} Output: 3 Input: arr[] = {1, 1, 1, 1} O
    12 min read
    Rotation Count in a Rotated Sorted array
    Given an array arr[] having distinct numbers sorted in increasing order and the array has been right rotated (i.e, the last element will be cyclically shifted to the starting position of the array) k number of times, the task is to find the value of k.Examples: Input: arr[] = {15, 18, 2, 3, 6, 12}Ou
    12 min read
    Unbounded Binary Search Example (Find the point where a monotonically increasing function becomes positive first time)
    Given a function 'int f(unsigned int x)' which takes a non-negative integer 'x' as input and returns an integer as output. The function is monotonically increasing with respect to the value of x, i.e., the value of f(x+1) is greater than f(x) for every input x. Find the value 'n' where f() becomes p
    11 min read
    Median of two Sorted Arrays of Different Sizes
    Given two sorted arrays, a[] and b[], the task is to find the median of these sorted arrays. Assume that the two sorted arrays are merged and then median is selected from the combined array.This is an extension of Median of two sorted arrays of equal size problem. Here we handle arrays of unequal si
    15+ min read
    The Painter's Partition Problem using Binary Search
    Given an array arr[] and k, where the array represents the boards and each element of the given array represents the length of each board. k numbers of painters are available to paint these boards. Consider that each unit of a board takes 1 unit of time to paint.The task is to find the minimum time
    10 min read

    Some practice problems on Divide and Conquer algorithm

    Program for Square Root of Integer
    Given a positive integer n, find its square root. If n is not a perfect square, then return floor of √n.Examples : Input: n = 4Output: 2Explanation: The square root of 4 is 2.Input: n = 11Output: 3Explanation: The square root of 11 lies in between 3 and 4 so floor of the square root is 3.Table of Co
    11 min read
    Maximum and minimum of an array using minimum number of comparisons
    Given an array of size N. The task is to find the maximum and the minimum element of the array using the minimum number of comparisons.Examples:Input: arr[] = {3, 5, 4, 1, 9}Output: Minimum element is: 1 Maximum element is: 9Input: arr[] = {22, 14, 8, 17, 35, 3}Output: Minimum element is: 3 Maximum
    15+ min read
    Find frequency of each element in a limited range array in less than O(n) time
    Given a sorted array arr[] of positive integers, the task is to find the frequency for each element in the array. Assume all elements in the array are less than some constant MNote: Do this without traversing the complete array. i.e. expected time complexity is less than O(n)Examples: Input: arr[] =
    10 min read
    Tiling Problem - L Shaped
    Given an n×n board (where n = 2k and k≥1), with one missing cell, the task is to fill the remaining cells using L-shaped tiles. An L-shaped tile covers 3 cells in a 2x2 grid, with one cell missing. You need to tile the entire board using the L-shaped tiles, ensuring that the missing cell remains unc
    15+ min read
    Count Inversions of an Array
    Given an integer array arr[] of size n, find the inversion count in the array. Two array elements arr[i] and arr[j] form an inversion if arr[i] > arr[j] and i < j.Note: Inversion Count for an array indicates that how far (or close) the array is from being sorted. If the array is already sorted
    15+ min read
    The Skyline Problem | Set-1
    Given n rectangular buildings in a 2-dimensional city, compute 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 (le
    13 min read
    Search in a Row-wise and Column-wise Sorted 2D Array using Divide and Conquer algorithm
    Given an n x n matrix, where every row and column is sorted in increasing order. Given a key, how to decide whether this key is in the matrix. Input: x = 62, mat[][] = [[3, 30, 38], [20, 52, 54], [35, 60, 69]]Output: falseExplanation: 62 is not present in the matrix.Input: x = 30, mat[][] = [[3, 30]
    7 min read
    Allocate Minimum Pages
    Given an array arr[] and an integer k, where arr[i] denotes the number of pages of a book and k denotes total number of students. All the books need to be allocated to k students in contiguous manner, with each student getting at least one book.The task is to minimize the maximum number of pages all
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences