Wednesday, July 26, 2017

Left Greater Number

Given an array of N positive integers, for each number print the first number to it’s left which is greater than the current number. Print -1 if there is no greater number on it's left.

Input Format:

The first line contains N.
The second line contains N space separated positive integers.

Output Format:

N integers which represent the left greater numbers separated by a space.

Boundary Conditions: 2 <= N <= 10^6

Example Input/Output 1:

Input:
6
5 3 2 4 8 6

Output:
-1 5 3 5 -1 8

Example Input/Output 2:

Input:
11
3 8 5 11 10 10 3 16 11 12 15

Output:
-1 -1 8 -1 11 11 10 -1 16 16 16
 

Solution:

n,a,s=int(input()),[int(x) for x in input().split()],[]
for i in a:
    while s and s[-1] <= i:
        s.pop()
    if not s:
        print('-1',end=' ')
    else:
        print(s[-1],end=' ')
    s.append(i)
Share: