IMMEDIATE SMALLER ELEMENT in java

IMMEDIATE SMALLER ELEMENT in java

Given an integer array arr of size n. For each element in the array, check whether the right adjacent element (on the next immediate position) of the array is smaller. If next element is smaller, update the current index to that element. If not, then -1.

Input

line 1: contains an integer n denoting size of array.

line 2: contains n spaced integers denoting elements of array.

Output

Print an array of integers denoting the immediate smaller element after the current element.

Constraints

1<=n<=10^6

1<=arr[i]<=10^6

Expected Time Complexity: O(N)

Expected Space Complexity: O(N)

Sample Input

5
4 2 1 5 3

Sample Output

2 1 -1 3 -1

Solution of IMMEDIATE SMALLER ELEMENT in java:–

import java.io.*;
import java.util.*;
public class Main {
    public static void main(String args[]) {
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        int a[] = new int[n];
        for(int i = 0; i < n; i++){
            a[i] = input.nextInt();
        }
        for(int i = 0; i < n; i++){
            if(i + 1 < n && a[i + 1] < a[i])
                System.out.print(a[i + 1] + " ");
            else{
                System.out.print(-1 + " ");
            }
        }
    }
}

Add a Comment

Your email address will not be published. Required fields are marked *