Refined solution working in linear time