Example 1:
Input: 5 4 3 2 1
Output: nil
Example 2:
Input: 5 4 3 2 6 1
Output: 0, 4 (indices)
Please suggest an algorithm to find such indices i, j that i < j and A[i] < A[j] in linear time and constant extra space. I have solved it in O(n^2) using 2 for loops.
Um… I would immediately make an assumption that if such
iandjexist at all, then there also must existiandjsuch thatj == i + 1andA[i] < A[j]. If so, the algorithm turns into a trivial single pass over the array.In your second example that would be
i = 3andj = 4.Indeed, let’s say we found
iandjsuch thatA[i] < A[j]andi + 1 < j. Let’s take a look atA[i + 1]. IfA[i + 1]is greater thanA[i], then just setj = i + 1and we are done. Otherwise, ifA[i + 1]is smaller or equal toA[i], then just seti = i + 1and repeat. This will always lead us to aj == i + 1pair that satisfies theA[i] < A[j]requirement.In other words, just go over your array looking for
A[i] < A[i + 1]situation. That’s all there is to it.