Im trying to solve a problem which is stated as -> Given an array A, find the next greater element G[i] for every element A[i] in the array. The Next greater Element for an element A[i] is the first greater element on the right side of A[i] in array, A. Elements for which no greater element exists, consider the next greater element as -1.
public class Solution {
public ArrayList<Integer> nextGreater(ArrayList<Integer> A) {
Stack<Integer> stk = new Stack<>();
if (A.size() == 1)
{
ArrayList<Integer> ans= new ArrayList<>();
ans.add(0,-1);
return ans;
}
ArrayList<Integer> ans= new ArrayList<>(A.size());
ans.add(A.size()-1,-1); //error ->Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 8, Size: 0
stk.push(0);
for(int i=1;i<A.size()-1;i++){
while(!stk.isEmpty()&&A.get(i)>A.get(stk.peek())){
ans.add(stk.pop(),A.get(i));
// stk.pop();
}
stk.push(i);
}
return ans;
}
}
But while solving this Im not understanding why Im getting error while adding -1 in the arraylist at position A.size()-1 where A : [ 34, 35, 27, 42, 5, 28, 39, 20, 28 ]
A.size()
is 0
, since there is no element in the list yet. Arrays should be initialized with a starting value, Lists (ArrayLists) are not.
You should initialize your ArrayList without capacity:
ArrayList<Integer> ans= new ArrayList<>();
Then you can simply
ans.add(-1);
or better, you can add -1
simply at the very end of your method.