KatInterview

Validate Deep Structure Equivalence

Stacks & QueuesAuto-graded · 23 test cases
MediumAuto-gradedStacks & Queuesrecursionstackdata-structures

Last 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:

  1. Type Match: type(obj1) must equal type(obj2) exactly. (For example, 1 and True or 1 and "1" are not equal).
  2. Primitives: If the objects are primitive types, their values must be equal (obj1 == obj2).
  3. Lists: If the objects are lists, they must have identical lengths, and the elements at every corresponding index must be deeply equal.
  4. 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 to True.
  • Empty dictionaries {} vs {} evaluate to True.
  • 1 and True must evaluate to False due 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.