Validate Deep Structure Equivalence
Stacks & QueuesAuto-graded · 23 test casesLast updated
Recursively or iteratively check if two arbitrarily nested data structures are identical in type, shape, and value.
Write a function are_deeply_equal(obj1, obj2) that checks whether two arbitrarily nested structures are structurally and value-equivalent.
The inputs can consist of primitive values (integers, strings, booleans, None), lists, and dictionaries.
Two objects obj1 and obj2 are considered deeply equal if and only if all of the following conditions hold:
- Type Match:
type(obj1)must equaltype(obj2)exactly. (For example,1andTrueor1and"1"are not equal). - Primitives: If the objects are primitive types, their values must be equal (
obj1 == obj2). - Lists: If the objects are lists, they must have identical lengths, and the elements at every corresponding index must be deeply equal.
- Dictionaries: If the objects are dictionaries, they must contain the exact same set of keys, and the corresponding values for every key must be deeply equal. Key order within dictionaries does not matter.
Constraints
- The structures can be nested to arbitrary depths.
- You may assume there are no self-referential or cyclic structures.
- Dictionary key sets must match regardless of key insertion order.
Edge Cases
- Empty lists
[]vs[]evaluate toTrue. - Empty dictionaries
{}vs{}evaluate toTrue. 1andTruemust evaluate toFalsedue to exact type checking (type(1) is not type(True)).
Examples
Example 1
Input: are_deeply_equal({'a': [1, 2], 'b': {'c': 3}}, {'a': [1, 2], 'b': {'c': 3}})
Output: True
Example 2
Input: are_deeply_equal([1, {'x': 2}], [1, {'x': 3}])
Output: False
Example 3
Input: are_deeply_equal([{'a': 1, 'b': 2}], [{'b': 2, 'a': 1}])
Output: True
Hints
Hint 1
Strict type checking using `type(a) is type(b)` is essential to prevent automatic standard type coercions (like `True == 1`).
Hint 2
For dictionaries, check whether key sets match and sizes are equal before evaluating nested values.
Hint 3
Consider using an explicit stack rather than recursion to safely handle deeply nested input structures without exceeding system call stack limits.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Checking for deep equality requires traversing two nested object structures simultaneously. We compare values at leaf nodes (primitives) and expand container nodes (lists and dictionaries).
While a recursive solution is straightforward, an iterative depth-first search using a stack is preferred to prevent Python's RecursionError on deeply nested structures.
For every pair of items (left, right) popped from the stack:
- Type Verification: Check
type(left) is type(right). Usingtype(...) is not type(...)ensures strict type matching so that1(an integer) andTrue(a boolean) are correctly identified as unequal. - Dictionary Handling: Check that both dictionaries have the same count of keys and identical key sets (
left.keys() != right.keys()). If they match, push(left[k], right[k])for all keys onto the stack. - List Handling: Check that both lists have identical lengths (
len(left) == len(right)). If lengths match, iterate over pair elements position-by-position usingzipand push them onto the stack. - Primitive Comparison: For non-container values, directly compare
left != right.
If any pair fails any check during traversal, we immediately short-circuit and return False. If the stack becomes empty, all corresponding elements were successfully validated as equal, so we return True.
Complexity Analysis
- Time Complexity: $\mathcal{O}(N)$ where $N$ is the total number of nodes/values across the structures. Each nested pair is pushed and popped at most once. Dictionary key set comparisons and string value comparisons run in linear time relative to their size.
- Space Complexity: $\mathcal{O}(N)$ worst-case memory usage for maintaining the explicit traversal stack.
Reference Solution
def are_deeply_equal(obj1: object, obj2: object) -> bool:
stack = [(obj1, obj2)]
while stack:
left, right = stack.pop()
# Strict type check
if type(left) is not type(right):
return False
if isinstance(left, dict):
if len(left) != len(right) or left.keys() != right.keys():
return False
for key in left:
stack.append((left[key], right[key]))
elif isinstance(left, list):
if len(left) != len(right):
return False
for left_item, right_item in zip(left, right):
stack.append((left_item, right_item))
elif left != right:
return False
return True