There was this problem named "Duplicate in the array" where we need to find a number which is occurring two times in an array where number of elements are N and all elements between 1 and N-1 are present in the array. There always be an element which is occur twice.
**I used a simple approach by sorting the given array and then comparing each element with its next element, if they matches then return the element, else increment the pointer.
wrote this code in java**
import java.util.ArrayList;
import java.util.*;
public class Solution {
public static int findDuplicate(ArrayList<Integer> arr) {
// Write your code here.
Collections.sort(arr);
int i=0;
for(i=0;i<arr.size()-1;i++){
if((arr.get(i))== (arr.get(i+1)))
return arr.get(i);
}
return 0;
}
}
The error or Exception i am getting is this:
Exception in thread main java.lang.NullPointerException
at Runner.takeInput(Runner.java:24)
at Runner.main(Runner.java:55)