Given the dictionary {'a': 1, 'b': {'c': 2, 'd': {'e': 3}}, 'f': {'g': 4}}, what is the flattened output mapping keys to values: 'a':1, 'c':2, 'e':3, 'g':4?
💡 Model Answer
To flatten a nested dictionary, you can use a recursive helper that walks through each key. If the value is itself a dictionary, recurse; otherwise, add the key‑value pair to the result. For the given dictionary, the recursion visits 'a' (value 1) and records it. It then enters 'b', finds 'c' (2) and records it, then enters 'd', finds 'e' (3) and records it. Finally, it visits 'f', finds 'g' (4) and records it. The resulting flat dictionary is {'a': 1, 'c': 2, 'e': 3, 'g': 4}. This approach runs in O(n) time, where n is the total number of leaf nodes, and uses O(h) additional space for the recursion stack, with h being the maximum depth of nesting.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500