Levelset interview question

Basic JavaScript algorithm with follow up for optimization