three pointer solution
memory optimization with hashmap