JCSU Unit 2 Problem Set 1 (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
- Established a set (2-3) of test cases to verify their own solution later.
- Established a set (1-2) of edge cases to verify their solution handles complexities.
- Have fully understood the problem and have no clarifying questions.
- Have you verified any Time/Space Constraints for this problem?
HAPPY CASE Input: nested_dict = { "a": {"name": "Alice", "age": 25}, "b": {"name": "Bob", "age": 30}, "c": {"name": "Charlie", "age": 35} } key = "name" Output: "Alice" Explanation: The key "name" is found in the nested dictionary "a", and its value is "Alice".
EDGE CASE Input: nested_dict = {"a": {}, "b": {}} key = "age" Output: None Explanation: The key "age" is not found in any nested dictionary.
Match what this problem looks like to known categories of problems, e.g. Linked List or Dynamic Programming, and strategies or patterns in those categories.
For nested dictionary search problems, we want to consider the following approaches:
Plan the solution with appropriate visualizations and pseudocode.
General Idea:
Iterate through the outer dictionary and check if the key exists in each nested dictionary. If the key is found, return its value. If the loop completes without finding the key, return None
.
items()
to access both keys and values.None
.Implement the code to solve the algorithm.
def find_key(nested_dict, key):
for outer_key, inner_dict in nested_dict.items(): # Iterate through the outer dictionary
if isinstance(inner_dict, dict): # Check if the value is a nested dictionary
if key in inner_dict: # Check if the key exists in the nested dictionary
return inner_dict[key] # Return the value associated with the key
return None # Return None if the key is not found in any nested dictionary
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
Example 1:
Example 2:
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
Assume n is the total number of outer keys, and m is the average number of keys in each nested dictionary.