1. Doubly Linked List with HashMap: A Perfect Duo
This question focused on implementing an LRU Cache using a combination of HashMap and doubly linked list.
• The HashMap acts as the forward attacker with O(1) lookups.
• The doubly linked list handles order maintenance, ensuring efficient updates for the most and least recently used items.
The challenge was initializing the doubly linked list. Adding a head and tail dummy node simplified operations. This allowed quick additions at the head and deletions from the tail. With modular helper functions like addToHead() and removeNode(), the implementation became clean and efficient.
2. Regex Matching: Dynamic Programming in Action
The second problem was a hard-level regex matching task involving * and . operators:
• *: Matches zero or more occurrences of the preceding character.
• .: Matches any single character.
I solved it with a 2D dynamic programming table, where:
• dp[i][j] determined if the first i characters of the string matched the first j characters of the pattern.
• Key strategies:
1. * as zero matches: Ignore the preceding character entirely (dp[i][j] = dp[i][j-2]).
2. * as one or more matches: Extend the match backward (dp[i][j] = dp[i-1][j]).
Though edge cases like empty strings or consecutive * were tricky, a methodical approach to defining base cases and transitions led to success.
3. Word Ladder: Turning Strings into a Graph
This problem asked for the shortest path between two words, where a word could transform into another if they differed by exactly one letter. For example:
• APPLE and APPLI are connected (1 letter difference).
• APPLE and APPPP are not connected (2 letters difference).
Key insights:
1.Graph Representation: I used wildcard patterns (e.g., A*PLE, AP*LE) to group similar words in a HashMap, allowing O(1) neighbor lookups.
2.Breadth-First Search (BFS): BFS was perfect for finding the shortest path, exploring neighbors layer by layer. The first match to the target word guarantees the shortest path.
Once the graph was clear, the problem transitioned from daunting to straightforward.