solved with an O(n) time and O(n) space solution