I had the exact same online assessment question. I did it with the merge intervals approach. My solution passed all 5 example test cases but when I submitted it, it only passed 3/7 cases. Can't figure out why. Can someone help? Would really appreciate it.
public class Solution {
public static class Range{
int start;
int end;
public Range(int start, int end) {
this.start = start;
this.end = end;
}
public boolean containsBoth(int B, int E) {
if(B >= start && B <= end && E >=start && E <= end) {
return true;
}
return false;
}
public String toString() {
return "[" + String.valueOf(start) + "," + String.valueOf(end) + "]";
}
}
public boolean solution(int[] A, int[] P, int B, int E) {
// write your code in Java SE 8
List<Range> ranges = new ArrayList<>();
for(int i=0; i<A.length; i++) {
Range r = new Range(P[i]-A[i], P[i]+A[i]);
ranges.add(r);
}
Collections.sort(ranges, (r1, r2) -> Integer.compare(r1.start, r2.start));
System.out.println(ranges);
//merge overlapped ranges
List<Range> merged = new ArrayList<>();
Range cur = ranges.get(0);
for(int i=1; i<ranges.size(); i++) {
Range next = ranges.get(i);
if(cur.end >= next.start && cur.end <= next.end) {//merge
cur.end = next.end;
}
else {//break
merged.add(cur);
cur = next;
}
}
if(merged.size() == 0 || cur.end != merged.get(merged.size()-1).end) {
merged.add(cur);
}
System.out.println(merged);
for(Range r : merged) {
if(r.containsBoth(B, E)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
int[] A = new int[] {2, 1};
int[] P = new int[] {5, 1};
System.out.println(new Solution().solution(A, P, 2, 6));
A = new int[] {2,1};
P = new int[] {5,1};
System.out.println(new Solution().solution(A, P, 3, 6));
A = new int[] {5,5,1};
P = new int[] {3,3,6};
System.out.println(new Solution().solution(A, P, 4, 8));
A = new int[] {1,4,2};
P = new int[] {10,4,7};
System.out.println(new Solution().solution(A, P, 11, 1));
}
}