Similar Problems

Similar Problems not available

Json Deep Equal - Leetcode Solution

Companies:

LeetCode:  Json Deep Equal Leetcode Solution

Difficulty: Unknown

Topics: unknown  

The Json Deep Equal problem on LeetCode is a problem that requires us to compare two given JSON objects and check if they are equal in terms of structure and values.

Problem Statement:

Given two JSON objects, write a function to determine if they are deeply equal (i.e., every property of the two objects is equal).

Example:

Input: a = {"x": {"y": [1,2,3], "z": {"p": 4}}} b = {"x": {"y": [1,2,3], "z": {"p": 4}}}

Output: True

Solution:

To solve this problem, we need to iterate over each property of the two JSON objects and compare them. We will use recursion to check all properties of the objects deeply.

Algorithm:

  1. Check the type of both objects, if they are not equal, return False.
  2. If they are both primitive types, compare their values.
  3. If they are both arrays, compare their length and then iterate over the elements and recursively compare them.
  4. If they are both objects, recursively compare their properties.
  5. If any of the above conditions do not hold, return False.
  6. If all properties of both objects are deeply equal, return True.

Code:

#Function to check if JSON objects are deeply equal def is_json_deep_equal(a, b): #Step 1: Check the type of both objects if type(a) != type(b): return False #Step 2: Check if both objects are primitive types if isinstance(a, (int, float, bool, str)) and isinstance(b, (int, float, bool, str)): return a == b #Step 3: Check if both objects are arrays if isinstance(a, list) and isinstance(b, list): if len(a) != len(b): return False for i in range(len(a)): if not is_json_deep_equal(a[i], b[i]): return False return True #Step 4: Check if both objects are objects if isinstance(a, dict) and isinstance(b, dict): a_keys = set(a.keys()) b_keys = set(b.keys()) if len(a_keys) != len(b_keys): return False for key in a_keys: if key not in b_keys: return False if not is_json_deep_equal(a[key], b[key]): return False return True #Step 5: If none of the above conditions hold, return False return False

#Example a = {"x": {"y": [1,2,3], "z": {"p": 4}}} b = {"x": {"y": [1,2,3], "z": {"p": 4}}} print(is_json_deep_equal(a, b)) #Output: True

Time Complexity:

The time complexity of the above algorithm is O(n) since we need to iterate over all properties of both objects.

Space Complexity:

The space complexity of the above algorithm is also O(n) since we use recursion to check all properties of both objects deeply.

Json Deep Equal Solution Code

1