LeetCode 2628: JSON Deep Equal Solution
Master LeetCode problem 2628 (JSON Deep Equal), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2628. JSON Deep Equal
Problem Explanation
Explanation:
To solve this problem, we need to compare two JSON objects deeply. We can start by checking if the two JSON objects are equal at the top level. If they are not equal, then they are not deeply equal. If they are equal at the top level, we need to recursively check each key-value pair to see if they are equal.
Here is the algorithm:
- Check if both JSON objects are equal at the top level.
- If they are equal, recursively check each key-value pair to see if they are equal.
- If any key-value pair is not equal, return false.
- If all key-value pairs are equal, return true.
Time complexity: O(n), where n is the total number of key-value pairs in the JSON objects. Space complexity: O(h), where h is the maximum height of the JSON object tree.
: :
Solution Code
import org.json.simple.JSONObject;
public class Solution {
public boolean isDeepEqual(JSONObject obj1, JSONObject obj2) {
if (!obj1.equals(obj2)) {
return false;
}
for (Object key : obj1.keySet()) {
Object val1 = obj1.get(key);
Object val2 = obj2.get(key);
if ((val1 instanceof JSONObject) && (val2 instanceof JSONObject)) {
if (!isDeepEqual((JSONObject)val1, (JSONObject)val2)) {
return false;
}
} else {
if (!val1.equals(val2)) {
return false;
}
}
}
return true;
}
}Try It Yourself
Loading code editor...
Frequently Asked Questions
How to solve LeetCode 2628 (JSON Deep Equal)?
This page provides optimized solutions for LeetCode problem 2628 (JSON Deep Equal) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2628 (JSON Deep Equal)?
The time complexity for LeetCode 2628 (JSON Deep Equal) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2628 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2628 in Java, C++, or Python.