Grokking the Coding Interview: Patterns for Coding Questions
Vote

0% completed

Introduction to Hash Map Pattern

You are given a string. Find the first character that appears only once.

"swiss"    the answer is 'w'
"aabbcc"   there is no such character

The direct approach takes each character and scans the whole string to count how often it appears. That is O(N²), and it recounts the same letters again and again.

The waste is obvious once you name it. The count of s does not change depending on which position you are asking about. It is a fact about the whole string, so it should be worked out once.

So make two passes. In the first pass, count every character into a map

.....

.....

.....

Like the course? Get enrolled and start learning!