Grokking Data Structures & Algorithms for Coding Interviews
Ask Author
Back to course home

0% completed

Vote For New Content
Java solution iterating from beginning of list to end of list.

Ejike Nwude

Nov 12, 2025

public class Solution {     public List<Integer> nextLargerElement(List<Integer> arr) {         int size = arr.size();         List<Integer> res = new ArrayList<>(Collections.nCopies(size, -1));         Stack<Integer> stack = new Stack<>();         for (int i = 0; i < size; i++) {             while (!stack.isEmpty() && arr.get(i) > arr.get(stack.peek())) {                 int index = stack.pop();                 res.set(index, arr.get(i));             }             stack.push(i);         }         return res;     } }

0

0

Comments
Comments