Modified solution-> O(n) time