I was asked this question in an interview(not Amazon). Initially I thought that I won't be able to solve it, but was able to with some hints from the interviewer. My solution was in C# and was similar to yours.
awesome. It always felt great to be able to find the solution in the end. Did you end up getting that job?
We're a place where coders share, stay up-to-date and grow their careers.
We strive for transparency and don't collect excess data.