refactored: O(n + 1) -> O(n)