I have an array arr of size n containing the integers 1 through n in a random order; for example, it might be arr = [4 5 3 6 2 1].
For each element e in arr, I need to find the closest element k that is less than e. ("Closest" in terms of position, not value; so in the above example, 5 is closer to 3 than to 6.) If there are equally-close lesser elements in both directions — as with 6 in the example above, whose immediate neighbors are both less than it — then it doesn't matter which of those elements is chosen.
So with the example above, arr = [4 5 3 6 2 1], one valid result is [3 3 2 2 1 NIL].
I know of a O(n) algorithm to solve this; it works by maintaining a stack to find the nearest smaller element in left and right of every element.
But surprisingly, a simple linear bidirectional search performed better than that algorithm, even though it seems to me to be O(n2) in the worst case:
for i = 1 to N
right = i + 1
left = i - 1
while (left > 0 && right <= n)
// ...find the closest element that is smaller than arr[i] and break while loop
What is the worst-case complexity of the above? Am I right that it's O(n2)?
i. if the top of the stack is greater than arr[i]...then we keep popping from the array till we get stack[top] < arr[i]...that would be the closest smaller element of i on the left. Reverse the array and rerun to get the smaller on right. Further, we can keep track of indices of these elements to find the closest by comparing rite/left