code optimization to gain O(N) time complexity