Fixed issue: Memory Limit Exceeded.

O(n) runtime, O(1) space