Transform string to adjacency list
Last updated: July 16, 2025
Quick Overview
Given a string representation of a graph where each node is connected by edges, transform the string into an adjacency list. The input will be a string formatted as "node1->node2,node3;node2->node4", and the output should be a dictionary where each key is a node and its value is a list of adjacent nodes. Ensure that the adjacency list accurately reflects all connections specified in the input string.
65
11
3,362 solved
Given a string representation of a graph where each node is connected by edges, transform the string into an adjacency list. The input will be a string formatted as "node1->node2,node3;node2->node4", and the output should be a dictionary where each key is a node and its value is a list of adjacent nodes. Ensure that the adjacency list accurately reflects all connections specified in the input string.
This coding problem is frequently asked during Onsite at Google. The interviewer is testing your ability to translate a problem into clean, working code while discussing time and space complexity. Google expects candidates to write production-quality code, not just solve the puzzle.
What the Interviewer Expects
- Recognize the underlying problem pattern (sliding window, two pointers, BFS/DFS, etc.)
- Discuss multiple approaches and trade-offs before coding
- Implement an optimal solution with clean, production-quality code
- Handle all edge cases including boundary conditions and invalid input
- Optimize both time and space complexity with clear justification
- Test your solution systematically with well-chosen examples
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- What happens if the input contains duplicates?
- Can you solve this iteratively instead of recursively (or vice versa)?
- Can you solve this in a single pass?
- How would you modify your solution to handle streaming input?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Problem Analysis
The problem requires transforming a string representation of a graph into an adjacency list format. The input string uses a specific format: 'node1->node2,node3;node2->node4'. This indicates that 'nod...
Approach
- Initialize an empty dictionary to hold the adjacency list.
- Split the input string by semicolons to separate each node's edges.
- For each segment:
- Split again by '->' to identify the sourc...