Refactored to less complexity O(n) from O(n^2)