Nearest Larger

Write a function, ‘nearest_larger(arr, i)’ which takes an array and an index. The function should return another index, `j`: this should satisfy:

(a) `arr[i] < arr[j]`, AND
(b) there is no `j2` closer to `i` than `j` where `arr[i] < arr[j2]`.

In case of ties (see example below), choose the earliest (left-most) of the two indices. If no number in `arr` is larger than `arr[i]`, return `nil`.

Must pass these test cases:


My solution:


The important thing to remember here is that we should initialize the starting point at the given index since we’re comparing left and right simultaneously (because they are at equivalent distance to the index).  Also set the bounds for left and right respectively.


Nearest Larger

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s