linear time solution, much conciser code