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:

screen-shot-2016-11-17-at-10-44-50-pm

My solution:

screen-shot-2016-12-05-at-3-36-36-pm

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.

 

Advertisements
Nearest Larger

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s