O(n) solution using dictionary