Data Structures19 sections · 729 units
Open in Course

A Harder Problem

Beyond matching

Parentheses matching was easy. Now consider this: for each element in an array, find the next element to the right that is greater.

Array: [2,1,2,4,3][2, 1, 2, 4, 3] Answers: [4,2,4,1,1][4, 2, 4, -1, -1] For element 22 at index 00, the next greater is 44 at index 33.

For element 44, there's nothing greater to its right, so the answer is 1-1. Brute force is O(n2)O(n^2). There's an O(n)O(n) solution using a special type of stack.