×

Skyline Problem in Java

The skyline of a city is the outer edge of the pattern created by all of its structures when viewed from a distance. Return the skyline that these buildings together create based on their positions and heights.

Assuming n rectangular buildings in a two-dimensional cityscape, evaluates their skylines while ignoring hidden lines. The main goal is to look at structures from different angles and eliminate any elements that are not visible.

Each structure has a common bottom and is represented by a triplet (left, height, right)

  • left: on the left side is x coordinated (or wall).
  • right: is the right side's x coordinate.
  • height: is the building's height.

The skyline is made up of rectangular strips. A rectangular strip is represented as a pair (left, height), where left seems to be the x coordinate of the strip's left side and ht is the strip's height.

All structures are assumed to be perfect rectangles grounded on a completely uniform surface at height 0.

The skyline should be represented as a list of "key points" ordered by x-coordinate in the format [[x1,y1],[x2,y2],...]. Except for the last point in the list, which always has a y-coordinate of 0 and is used to denote the skyline's conclusion where the rightmost building finishes, each key point is the left endpoints of some horizontal segment in the skyline. Any land between the left and rightmost buildings should be included in the outline of the skyline.

Skyline Problem in Java

Example1:

Input: buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]
Output: [[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]]

Explanation:

Figure A displays the input's buildings.

Figure B depicts the skyline generated by these structures. The red dots in picture B reflect the output list's main points.

Example2:

Input: buildings = [[0,2,3],[2,5,3]]
Output: [[0,3],[5,0]]

Approach:

  1. Retrieve the left wall position, height, and right wall location values for each structure from the triplets that have been provided.
  2. Keep the pair of the right wall's real height and the left wall's negative height value in a vector called walls. The left and right walls of the same structure are divided in this way.
  3. Sort the walls from highest to lowest.
  4. If a left wall is located while traversing the vector walls, record its height in the multiset. If a right wall is found in any other case, take the multiset's equivalent height accordingly.
  5. Verify whether or not the top value has changed. If it has changed, update the top value and save the abscissa(x-coordinate) value of the current wall together with the revised top value in a vector designated as the skyline.
  6. The value pairs kept in the skyline vector should be printed.

Filename: Skyline.java

class Skyline {
  public List<List<Integer>> getSkyline(int[][] buildings) {
    final int a = buildings.length;
    if (a == 0)
      return new ArrayList<>();
    if (a == 1) {
      final int left = buildings[0][0];
      final int right = buildings[0][1];
      final int height = buildings[0][2];
      List<List<Integer>> ans = new ArrayList<>();
      ans.add(new ArrayList<>(Arrays.asList(left, height)));
      ans.add(new ArrayList<>(Arrays.asList(right, 0)));
      return ans;
    }
    List<List<Integer>> leftSkyline = getSkyline(Arrays.copyOfRange(buildings, 0, a / 2));
    List<List<Integer>> rightSkyline = getSkyline(Arrays.copyOfRange(buildings, a / 2, a));
    return merge(leftSkyline, rightSkyline);
  }
  private List<List<Integer>> merge(List<List<Integer>> left, List<List<Integer>> right) {
    List<List<Integer>> ans = new ArrayList<>();
    int u = 0; // left's index
    int v = 0; // right's index
    int leftY = 0;
    int rightY = 0;
    while (u < left.size() && v < right.size())
      // Choose the point with smaller x
      if (left.get(u).get(0) < right.get(v).get(0)) {
        leftY = left.get(u).get(1); // Update the ongoing leftY
        addPoint(ans, left.get(u).get(0), Math.max(left.get(u++).get(1), rightY));
      } else {
        rightY = right.get(v).get(1); // Update the ongoing rightY
        addPoint(ans, right.get(v).get(0), Math.max(right.get(v++).get(1), leftY));
      }
    while (u < left.size())
      addPoint(ans, left.get(u).get(0), left.get(u++).get(1));
    while (v < right.size())
      addPoint(ans, right.get(v).get(0), right.get(v++).get(1));
    return ans;
  }
  private void addPoint(List<List<Integer>> ans, int p, int q) {
    if (!ans.isEmpty() && ans.get(ans.size() - 1).get(0) == p) {
      ans.get(ans.size() - 1).set(1, q);
      return;
    }
    if (!ans.isEmpty() && ans.get(ans.size() - 1).get(1) == q)
      return;
    ans.add(new ArrayList<>(Arrays.asList(p, q)));
  }
}

Output:

buildings =
[[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]
 [[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]]

Filename: Skyline.java

class Skyline {
    public List<List<Integer>> getSkyline(int[][] buildings) {
        List<List<Integer>> heightList = new LinkedList<List<Integer>>();
        TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
        List<List<Integer>> alpha = new LinkedList<List<Integer>>();
        int PreviousHeight = 0;        
        for(int[] A : buildings) {
            heightList.add(Arrays.asList(A[0], -A[2]));
            heightList.add(Arrays.asList(A[1], A[2]));
        }
        Collections.sort(heightList, (x, y)->(x.get(0).intValue() != y.get(0).intValue() ? x.get(0) - y.get(0) : x.get(1) - y.get(1)));
        map.put(0, 1);
        for(List<Integer> A : heightList) {
            int Height = A.get(1);
            if(Height < 0)map.put(-Height, map.getOrDefault(-Height, 0) + 1);
            else if(map.getOrDefault(Height, 0) > 1)map.put(Height, map.get(Height) - 1);
            else map.remove(Height);
            if(map.lastKey() != PreviousHeight) {
                PreviousHeight = map.lastKey();
                alpha.add(Arrays.asList(A.get(0), PreviousHeight));
            }
        }
        return alpha;
    }
}

Output:

buildings =
[[0,2,3],[2,5,3]]
 [[0,3],[5,0]]

Related Topics

How to Compare Two Strings in Java

How to Compare Two Strings in Java On the basis of reference or content, one can compare two strings in Java. String comparison is used in reference matching (== operator), sorting...

4 minutes read.

How to Convert int to double in Java

How to Convert int to double in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

2 minutes read.

Non-primitive data types in Java

The kind of data stored in the variable is determined by its type. The type describes the data category (different sizes and values). These are not already built into the devices....

4 minutes read.

Permutation Coefficient in Java

In this tutorial, we will get familiar with the permutation coefficient in Java.  We will understand it through examples and see different approaches to solving the problem. A permutation is a...

5 minutes read.

Applet Program in Java

Applet Program in Java An applet is a program that can be embedded in a web page. Applets programs are run by a web browser. It mainly works on the client-side....

3 minutes read.

Quick Sort in Java

Quick Sort in Java Like merge sort, quick sort also uses the divide and conquer approach to sort the given array or list. In quick sort, the sorting of an array...

6 minutes read.

Contextual keywords in Java

Contextual keywords were earlier known as restricted identifiers and restricted keywords. Context keywords are chosen based on their expected placement in the syntactic grammar. These are the keywords in the code...

3 minutes read.

Annotations in Java

Annotations in Java Java Annotations are metadata about the source code. They do not have any direct effect on the execution of the java program. Annotations in Java were introduced in...

4 minutes read.

India Map Pattern in Java

India Map Pattern is the pattern we'll code now using Java, as demonstrated. We will use a star in Java to print our India map.The specialty is that we will only...

4 minutes read.

Java Architecture

Java architecture is a combination of three parts they are JVM, JRE and JDK. These components will help in the functioning of the java programs. The process of code interpretation...

6 minutes read.

Best Practices to use String Class in Java

Use String Builder or String Buffer for String concatenation in place of + operator.Compare two strings by equals( ) method instead == operator.Call .equals( ) method on a known String...

3 minutes read.

Java Math copySign() Method

The copySign() method of Math class returns the first floating-point argument with the sign of the second argument. Syntax: public static float copySign(float magnitude, float sign)public static double copySign(double magnitude, double sign) Parameters: The...

1 minute read.

Insertion Sort in Java

Insertion Sort in Java Insertion sort in Java is a simple sorting algorithm that works in the same way as we hold cards in hand. Insertion sort does the sorting element-by-element,...

3 minutes read.

How to use scanner in Java

Scanner class in Java is the part of java.util package. Java programming language has various ways to read input from the user, Scanner class is one of the classes to...

5 minutes read.

Zigzag Traversal of Binary Tree in Java

In this article, you will be acknowledged about the zigzag traversal of binary tree in java and the approaches or ways in which the zigzag traversal can be done. Zigzag Traversal A...

10 minutes read.

Java Buffered Writer

BufferWriter Class: It is used to write the data more efficiently. This class is present in the java.io package, it inherits the data from the Writer class. Writer class is...

4 minutes read.

Prime Points in Java

The points that divide an integer into two halves containing a prime number are known as prime points. Printing every prime point of a specific number is the task. Let's...

6 minutes read.

The Maximum Rectangular Area in a Histogram in Java

Continuous bars should be used to form the largest possible rectangle. We'll assume in the interest of convenience that each bar's width is 1. Naive Approach In this method, each bar will be...

6 minutes read.

Swastika Pattern in Java

This part teaches us how to create the Swastika Pattern in Java utilizing user-defined columns and rows as well as stars or other special characters.A Java pattern application that is...

2 minutes read.

How to check version of java in Linux

Java is one of the most famous and thoroughly utilized programming tongues from one side of the world to the other. On the off chance that you are a Java...

2 minutes read.