I am trying a Codility demo problem before taking a real test as part of a job application. One of the demos they have is the problem of counting the number of disk intersections for an array of disks.
Task description
Given an array A of N integers, we draw N disks in the 2D plane so that the I-th disk is centered on (0, I) and has a radius A [I]. We say that the Jth disk and the Kth disk intersect if J β K and the Jth and Kth disks have at least one common point. Write a function: class Solution {public int number_of_disc_intersections (int [] A);
You can watch the test here .
There are some obvious O (n ^ 2) solutions with time complexity, but the goal is O (n * log (n)).
I came up with this that works on any examples I have provided and on a simple test case given by codility ([1, 5, 2, 1, 4, 0]), but Codility tells me that most are different, but I canβt understand why.
This, of course, should be O (n log n), since adding each of n disks to a TreeSet is log n, and then we iterate over all disks using only the O (1) operation TreeSet.headSet ().
import java.util.*; class Circle implements Comparable<Circle> { long edge; int index; Circle (long e, int i){ edge = e; index = i; } long getRightAssumingEdgeIsLeft(){ return (long)(2*index - edge + 1); } @Override public int compareTo(Circle other){ return Long.valueOf(edge).compareTo(other.edge); } } class Solution { public int number_of_disc_intersections ( int[] A ) { int N = A.length; if (N<2) return 0; int result = 0; SortedSet<Circle> leftEdges = new TreeSet<Circle>(); for (int i=0; i<N; i++) { leftEdges.add( new Circle( (long)(iA[i]), i ) ); } int counter = 0; for (Circle c : leftEdges) { long rightEdge = c.getRightAssumingEdgeIsLeft(); Circle dummyCircle = new Circle (rightEdge, -1); SortedSet<Circle> head = leftEdges.headSet(dummyCircle); result += head.size() - counter; if (result > 10000000) return -1; counter++; } return result; } }
user1002973
source share