Problem
Given two values o1
and o2
, return a boolean value indicating whether two values, o1
and o2
, are deeply equal.
For two values to be deeply equal , the following conditions must be met:
-
If both values are primitive types, they are deeply equal if they pass the
===
equality check. -
If both values are arrays, they are deeply equal if they have the same elements in the same order, and each element is also deeply equal according to these conditions.
-
If both values are objects, they are deeply equal if they have the same keys, and the associated values for each key are also deeply equal according to these conditions.
You may assume both values are the output of JSON.parse
. In other words, they are valid JSON.
Please solve it without using lodash’s _.isEqual()
function
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Example 4:
|
|
Constraints:
1 <= JSON.stringify(o1).length <= 10^5
1 <= JSON.stringify(o2).length <= 10^5
maxNestingDepth <= 1000
Solution
Method 1 – Recursive Deep Comparison
Intuition
To check if two JSON values are deeply equal, we need to recursively compare their types and contents. For primitives, use strict equality. For arrays, compare lengths and each element. For objects, compare keys and recursively compare values.
Approach
- If both values are strictly equal, return true.
- If types differ, return false.
- If both are arrays:
- Check lengths. If not equal, return false.
- Recursively compare each element.
- If both are objects (not null):
- Check that both have the same set of keys.
- Recursively compare values for each key.
- Otherwise, return false.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
— n is the total number of keys and elements in the objects/arrays (in the worst case, all elements are compared). - 🧺 Space complexity:
O(h)
— h is the maximum depth of the nested structure (for recursion stack).