Given an array A[1..n], we want to compute another array B[1..n] such that B[i] stores the nearest element to the left of A[i]>
A[1..n]
B[1..n]
B[i]
A[i]>
Your stack approach is correct. It works because if you pop an element bigger than A[i], that element will never be needed for any elements following A[i], because you can just use A[i] instead.
A[i]
Each element is only accessed twice, so this is O(n).
O(n)