July 2, 2018
Hey Developer,
I am bringing you another high quality Java solution. This time, I am solving the Number Of Disc Intersections problem which can be found here.
I originally saw this brilliant solution on a Quora post, and it was written in Python by Hazel Prasetya, the link is here. Even after reading the solution, it was a bit hard to understand so I decided to convert it to Java, and make a video explaining it.
As always, the Java solution is below.
import java.util.Arrays; class Solution { public int solution(int[] A) { // variable holding max intersections given in problem description (10,000,000) final int MAX_INTERSECTIONS = 10000000; // variable to keep the length of A int N = A.length; //initialize arrays to store our discs' end points // left end points int [] discStartPoint = new int [N]; // right end points int [] discEndPoint = new int [N]; //populate the arrays for (int i = 0; i < N; i++) { discStartPoint[i] = i - A[i]; // if we can overflow, Example: i = 5; A[i] = Integer.MAX_VALUE; discEndPoint[i] = 5 + Integer.MAX_VALUE, causes overflow if (Integer.MAX_VALUE - A[i] < i) { discEndPoint[i] = Integer.MAX_VALUE; } else { discEndPoint[i] = i + A[i]; } } // sort the arrays Arrays.sort(discStartPoint); Arrays.sort(discEndPoint); //variable for traversing "discStartPoint" array int startPointIndex= 0; //variable for traversing "discEndPoint" array int endPointIndex = 0; // How many discs are currently open int openDiscs = 0; // number of intersections int intersections = 0; //While we have not went through all of the discs available //loop ends when all discs are opened while(startPointIndex < N) { // if we open a disc // every time we open a disc, the disc will intersect with all previously opened discs // and this new disc will be used for calculating future intersections if (discStartPoint[startPointIndex] <= discEndPoint[endPointIndex]) { intersections = intersections + openDiscs; // if our intersections are greater than max_intersections (see problem description) if (intersections > MAX_INTERSECTIONS) { return -1; } openDiscs++; startPointIndex++; } // else, we close a disc // this means that we have one less disc to intersect with else { openDiscs--; endPointIndex++; } } return intersections; } }
Comments
what’s the complexity of this code
There are two loops that iterate through the number of discs, which are O(N).
The code that I used for sorting is Arrays.sort(), the documentation gives us the complexity as O(N log(N)) using Quick Sort. Thus, the solution is O(N Log(N)).
Hope this helps.