2.2 Next greater element
Again we are given an array of integers. We want to compute,
for each index
The array
Problem 2.2.1 Given an array of integers, compute the NGE array as just described.
Input: a single line containing
Output: a single line containing
Sample Input:
8 6 4 8 9 13 6 8 9 7 5 8 11 4 5 12
Sample Output:
4 3 3 4 5 16 7 8 12 11 11 12 15 14 15 16
Test cases
Before starting to code, you should think of a handful of test cases (unless this is during an actual competition). Write them into a file and use them to test your algorithm later on.
Exercise 2.2.2 Write test cases for this problem. In particular,
- the above example;
- an increasing array;
- a decreasing array;
-
a program that generates somehow random instances. For example, like
python generate-random-test-cases.py 10 -20 20
-9 18 19 -14 2 -10 12 -16 14 18
For each test case (except the large ones generated randomly), compute the answer by hand and write it into a file. Produce a pair file like increasing-array-length-11.in and increasing-array-length-11.out.
A quadratic algorithm
It should be simple to come up with a quadratic algorithm
for this problem. Iterate
def compute_nge(array):
n = len(array)
nge = [0] * n
for i in range(n):
j = i+1
while (j < n and array[j] <= array[i]):
j = j+1
nge[i] = j
return nge
array = list(map(int, input().split()))
nge = compute_nge(array)
for j in nge:
print(j, end=' ')
print()
A linear time algorithm
We scan the array from right to left. We keep a stack of indices
How do we process a new index? For example, when processing
The works if the
Theorem 2.2.1
If
Proof.
Let
Problem 2.2.3 Implement the above idea with a stack to achieve a linear time algorithm for the Next-Greater-Element problem.
Test your algorithm by comparing it to the solution computed by the quadratic implementation above.