I'm working on some ruby problems geared towards new developers, but I would like the opinions of experienced developers on this. Sorry for the long post, and I really appreciate your time and opinions.
Problem Question
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 toi
thanj
wherearr[i] < arr[j]
.In case of ties (see example below), choose the earliest (left-most) of the two indices. If no number in
arr
is larger thanarr[i]
, returnnil
.Difficulty: 2/5
Rspec Test
describe "#nearest_larger" do
it "handles a simple case to the right" do
nearest_larger([2,3,4,8], 2).should == 3
end
it "handles a simple case to the left" do
nearest_larger([2,8,4,3], 2).should == 1
end
it "treats any two larger numbers like a tie" do
nearest_larger([2,6,4,8], 2).should == 1
end
it "should choose the left case in a tie" do
nearest_larger([2,6,4,6], 2).should == 1
end
it "handles a case with an answer > 1 distance to the left" do
nearest_larger([8,2,4,3], 2).should == 0
end
it "handles a case with an answer > 1 distance to the right" do
nearest_larger([2,4,3,8], 1).should == 3
end
it "should return nil if no larger number is found" do
nearest_larger( [2, 6, 4, 8], 3).should == nil
end
end
Solution
def nearest_larger arr, idx
diff = 1
loop do
l = idx - diff
r = idx + diff
return l if (l >= 0) && (arr[l] > arr[idx])
return r if (r < arr.length) && (arr[r] > arr[idx])
return nil if (l < 0) && (r >= arr.length)
diff += 1
end
end
Feedback
- How would you go about working towards a solution for this problem? (what's your process?)
- In your opinion do find the Problem Question clear and easy to understand?
- How long should it take you to solve this problem? (10min, 20min, ...?)
- Do agree with the level of difficulty? (Keep in mind this is geared towards new developers)
- If willing: please post your own solution, showcasing your style of solving this problem.
I decided to post this question because I know how easy it can be for new developer to get stuck on a problem and not know what to write first. I'm hoping your responses will give an insight on how you would work through a problem that you perceive as a challenge.