Nearest Greater Element to the Left of Every Element - Java Solution

1. Introduction

In this blog post, we explore a problem that is commonly encountered in array processing and data structures: finding the nearest greater element to the left of every element in an array. This problem is a variation of the Next Greater Element problem and can be efficiently solved using a stack.

Problem

Given an array of integers, the task is to find the nearest greater element on the left side for every element in the array. If no such element exists, print -1.

2. Solution Steps

1. Create a stack to keep track of elements for which the nearest greater element on the left is not yet found.

2. Iterate through the array from left to right.

3. For each element:

a. Pop elements from the stack until the stack is empty or the top element of the stack is greater than the current element.

b. If the stack is empty, there is no greater element on the left. Print -1.

c. If the stack has elements, the top element is the nearest greater element on the left.

4. Push the current element onto the stack.

5. Repeat the process for each element in the array.

3. Code Program

import java.util.Stack;

public class Solution {

    // Main method for testing
    public static void main(String[] args) {
        int[] arr = {4, 5, 2, 10, 8};
        printNearestGreaterToLeft(arr);
    }

    // Method to print nearest greater elements to the left
    public static void printNearestGreaterToLeft(int[] arr) {
        Stack<Integer> stack = new Stack<>();
        StringBuilder result = new StringBuilder();

        for (int j : arr) {
            while (!stack.isEmpty() && stack.peek() <= j) {
                stack.pop();
            }
            result.append(stack.isEmpty() ? "-1 " : stack.peek() + " ");
            stack.push(j);
        }

        System.out.println(result.toString().trim());
    }
}

Output:

-1 5 5 10 10

Explanation:

The printNearestGreaterToLeft method utilizes a stack to find the nearest greater element to the left for each element in the array. The stack keeps elements in a way such that the top element is always the nearest greater element for the next array element. 

For example, in the array [4, 5, 2, 10, 8], the nearest greater element to the left of 2 is 5, and for 10 and 8, it's 10. The method efficiently traverses the array and prints the correct nearest greater element for each element.

Comments