Levelset Interview Question

Basic JavaScript algorithm with follow up for optimization