Please help me with the following code, one of my test case is not giving right answer so please tell me the correction i need to make to make it right

import java.util.*;
public class Main {
public static void main(String args[]) throws Exception {
Scanner sc = new Scanner(System.in);
int n= sc.nextInt();
int arr[] = new int[n];
for(int i = 0;i<n;i++){
arr[i] = sc.nextInt();
}
StackUsingArrays s = new StackUsingArrays(n,arr);
s.push(arr[0]);
int element;
int next;
for (int i = 1; i < n; i++)
{
next = arr[i];

        if (s.isEmpty() == false)
        {
            element = s.pop();
            while (element < next)
            {
                System.out.print(next + " ");
                if (s.isEmpty() == true)
                    break;
                element = s.pop();
            }
            if (element > next)
                s.push(element);
        }
        s.push(next);
    }
    while (s.isEmpty() == false)
    {
        element = s.pop();
        next = -1;
        System.out.print(next+" ");
    }
}

}
class StackUsingArrays {
protected int data[];
protected int top;
public StackUsingArrays(int capacity, int arr[]) throws Exception{
if(capacity<1){
throw new Exception(“invalid capacity entered”);
}
this.data = arr;
this.top = -1;
}
public int size(){
return this.top+1; // this will return the size of the current stack
}
public boolean isEmpty(){
return this.size() ==0;
}
public void push(int element) throws Exception{
if(this.top == this.size()){
throw new Exception(“Stack is full”);
}
this.top++;
this.data[this.top] = element;
}
public int pop() throws Exception{
if(this.size() == 0){
throw new Exception(“Stack is empty”);
}
int element = this.data[this.top];
this.data[this.top] = 0;
this.top–;
return element;
}
public int top() throws Exception{
if(this.size()==0){
throw new Exception(“Stack is Empty”);
}
int element = this.data[this.top];
return element;
}
public void display() throws Exception {
for(int i = this.top();i>=0;i–){
System.out.print(this.data[i]+", “);
}
System.out.println(” End ");
}
}

Hi @8006366388,
Your code will give Wrong Answer if all the elements in the array are same. In that case you will have to print -1 n times. But you are printing it only once.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.