4

Given an array find the last smaller element's index in array for each element.

For example, suppose the given array is {4,2,1,5,3}. Then last smaller element for each element will be as follows.

4->3
2->1
1->Null
5->3
3->Null

Notice for 1st pair 4->3, 3 is the last element in array smaller than 4.

The resultant/output array would have indexes not the elements themselves. Result would be {4,2,-1,4,-1}

I was asked this question in an interview, but i couldn't think of a solution better than the trivial O(n^2) solution.

Any help would be highly appreciated.

0

2 Answers 2

3

We need to compute max(index) over all elements with smaller values.

Let's sort pairs (element, index) in lexicographical order and iterate over them keeping track of the largest index seen so far. That's exactly the position of the rightmost smaller element. Here's how one could implement it:

def get_right_smaller(xs):
    res = [-1] * len(xs)
    right_index = -1
    for val, idx in sorted((val, idx) for idx, val in enumerate(xs)):
        res[idx] = right_index if right_index > idx else -1
        right_index = max(right_index, idx)
    return res

This solution works properly even if the input array contains equal numbers because the element with smaller index goes earlier if the the values of two elements are the same.

The time complexity of this solution is O(N log N + N) = O(N log N) (it does sorting and one linear pass).

If all elements of the array are O(N), you can make this solution linear using count sort.

Sign up to request clarification or add additional context in comments.

1 Comment

Great solution!
1
Make a list, add last element index. 
Walk through array right to left.     
For every element:
   if list tail value is smaller then current element
       find the most first smaller list element (binary search, list is sorted)
   otherwise 
       add element index to the list tail, output -1

for {4,2,1,5,3,6,2} example list will contain index 6 (value 2); index 2 (value 1)

3 Comments

Taking an example array - {4,2,1,5,3,6,2}. When I process from right. After adding 3,6,2 - 3(root) 2(Left) 6(right) Now after adding 3,6,2 , for element 5, we will look at tree (before inserting 5). 2 Lesser values exist - 3 and 2. The correct value to select is 2, but if I use a floor function then it will give me 3. So how are we selecting the lesser value?
Seems I understood condition last smaller element wrong.
New approach added.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.