Write a function that accepts two deeply nested objects or arrays obj1 and obj2 and returns a new object representing their differences.
The function should compare the properties of the two objects and identify any changes. The returned object should only contain keys where the value is different from obj1 to obj2. For each changed key, the value should be represented as an array [obj1 value, obj2 value].
Important: Keys that exist in one object but not in the other should not be included in the returned object. The end result should be a deeply nested object where each leaf value is a difference array.
When comparing two arrays, the indices of the arrays are considered to be their keys. You may assume that both objects are the output of JSON.parse.
The key insight is to recursively compare only common keys and build the result object containing differences as [old_value, new_value] arrays. Best approach uses optimized depth-first traversal with early termination. Time: O(n), Space: O(d).
Common Approaches
✓
Frequency Count
⏱️ Time: N/A
Space: N/A
Brute Force Recursive Comparison
⏱️ Time: O(n)
Space: O(d)
Traverse both objects recursively, comparing each property. For primitive values that differ, store [obj1_value, obj2_value]. For nested objects, recursively compare and only include non-empty difference objects.
Optimized Depth-First Traversal
⏱️ Time: O(n)
Space: O(d + m)
Uses depth-first traversal with optimizations: early termination for identical references, type checking before recursion, and efficient object/array handling. Minimizes object creation by only building result when differences exist.
Algorithm Steps — Algorithm Steps
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <ctype.h>
typedef enum {
JSON_NULL,
JSON_BOOL,
JSON_NUMBER,
JSON_STRING,
JSON_ARRAY,
JSON_OBJECT
} JsonType;
typedef struct JsonValue {
JsonType type;
union {
int boolean;
double number;
char* string;
struct {
struct JsonValue** items;
int count;
} array;
struct {
char** keys;
struct JsonValue** values;
int count;
} object;
};
} JsonValue;
char* skip_whitespace(char* str) {
while (*str && isspace(*str)) str++;
return str;
}
JsonValue* parse_value(char** str);
JsonValue* parse_string(char** str) {
char* s = *str;
if (*s != '"') return NULL;
s++;
char* start = s;
while (*s && *s != '"') {
if (*s == '\\') s += 2;
else s++;
}
if (*s != '"') return NULL;
JsonValue* value = malloc(sizeof(JsonValue));
value->type = JSON_STRING;
int len = s - start;
value->string = malloc(len + 1);
strncpy(value->string, start, len);
value->string[len] = '\0';
*str = s + 1;
return value;
}
JsonValue* parse_number(char** str) {
char* s = *str;
char* end;
double num = strtod(s, &end);
if (end == s) return NULL;
JsonValue* value = malloc(sizeof(JsonValue));
value->type = JSON_NUMBER;
value->number = num;
*str = end;
return value;
}
JsonValue* parse_array(char** str) {
char* s = *str;
if (*s != '[') return NULL;
s++;
JsonValue* value = malloc(sizeof(JsonValue));
value->type = JSON_ARRAY;
value->array.items = malloc(1000 * sizeof(JsonValue*));
value->array.count = 0;
s = skip_whitespace(s);
if (*s == ']') {
*str = s + 1;
return value;
}
while (true) {
s = skip_whitespace(s);
JsonValue* item = parse_value(&s);
if (!item) break;
value->array.items[value->array.count++] = item;
s = skip_whitespace(s);
if (*s == ']') {
s++;
break;
}
if (*s == ',') {
s++;
} else {
break;
}
}
*str = s;
return value;
}
JsonValue* parse_object(char** str) {
char* s = *str;
if (*s != '{') return NULL;
s++;
JsonValue* value = malloc(sizeof(JsonValue));
value->type = JSON_OBJECT;
value->object.keys = malloc(1000 * sizeof(char*));
value->object.values = malloc(1000 * sizeof(JsonValue*));
value->object.count = 0;
s = skip_whitespace(s);
if (*s == '}') {
*str = s + 1;
return value;
}
while (true) {
s = skip_whitespace(s);
if (*s != '"') break;
JsonValue* key = parse_string(&s);
if (!key) break;
s = skip_whitespace(s);
if (*s != ':') break;
s++;
s = skip_whitespace(s);
JsonValue* val = parse_value(&s);
if (!val) break;
value->object.keys[value->object.count] = key->string;
value->object.values[value->object.count] = val;
value->object.count++;
free(key);
s = skip_whitespace(s);
if (*s == '}') {
s++;
break;
}
if (*s == ',') {
s++;
} else {
break;
}
}
*str = s;
return value;
}
JsonValue* parse_value(char** str) {
*str = skip_whitespace(*str);
if (strncmp(*str, "null", 4) == 0) {
JsonValue* value = malloc(sizeof(JsonValue));
value->type = JSON_NULL;
*str += 4;
return value;
}
if (strncmp(*str, "true", 4) == 0) {
JsonValue* value = malloc(sizeof(JsonValue));
value->type = JSON_BOOL;
value->boolean = 1;
*str += 4;
return value;
}
if (strncmp(*str, "false", 5) == 0) {
JsonValue* value = malloc(sizeof(JsonValue));
value->type = JSON_BOOL;
value->boolean = 0;
*str += 5;
return value;
}
if (**str == '"') {
return parse_string(str);
}
if (**str == '[') {
return parse_array(str);
}
if (**str == '{') {
return parse_object(str);
}
if (**str == '-' || isdigit(**str)) {
return parse_number(str);
}
return NULL;
}
bool values_equal(JsonValue* v1, JsonValue* v2) {
if (v1->type != v2->type) return false;
switch (v1->type) {
case JSON_NULL:
return true;
case JSON_BOOL:
return v1->boolean == v2->boolean;
case JSON_NUMBER:
return v1->number == v2->number;
case JSON_STRING:
return strcmp(v1->string, v2->string) == 0;
case JSON_ARRAY:
if (v1->array.count != v2->array.count) return false;
for (int i = 0; i < v1->array.count; i++) {
if (!values_equal(v1->array.items[i], v2->array.items[i])) return false;
}
return true;
case JSON_OBJECT:
if (v1->object.count != v2->object.count) return false;
for (int i = 0; i < v1->object.count; i++) {
bool found = false;
for (int j = 0; j < v2->object.count; j++) {
if (strcmp(v1->object.keys[i], v2->object.keys[j]) == 0) {
if (!values_equal(v1->object.values[i], v2->object.values[j])) return false;
found = true;
break;
}
}
if (!found) return false;
}
return true;
}
return false;
}
void print_value(JsonValue* value);
void print_diff_value(JsonValue* v1, JsonValue* v2) {
printf("[");
print_value(v1);
printf(",");
print_value(v2);
printf("]");
}
void print_value(JsonValue* value) {
switch (value->type) {
case JSON_NULL:
printf("null");
break;
case JSON_BOOL:
printf(value->boolean ? "true" : "false");
break;
case JSON_NUMBER:
if (value->number == (int)value->number) {
printf("%d", (int)value->number);
} else {
printf("%g", value->number);
}
break;
case JSON_STRING:
printf("\"%s\"", value->string);
break;
case JSON_ARRAY:
printf("[");
for (int i = 0; i < value->array.count; i++) {
if (i > 0) printf(",");
print_value(value->array.items[i]);
}
printf("]");
break;
case JSON_OBJECT:
printf("{");
for (int i = 0; i < value->object.count; i++) {
if (i > 0) printf(",");
printf("\"%s\":", value->object.keys[i]);
print_value(value->object.values[i]);
}
printf("}");
break;
}
}
bool find_differences(JsonValue* obj1, JsonValue* obj2, JsonValue* result) {
if (obj1->type != obj2->type) return false;
bool has_diff = false;
if (obj1->type == JSON_OBJECT) {
result->type = JSON_OBJECT;
result->object.keys = malloc(1000 * sizeof(char*));
result->object.values = malloc(1000 * sizeof(JsonValue*));
result->object.count = 0;
for (int i = 0; i < obj1->object.count; i++) {
char* key = obj1->object.keys[i];
JsonValue* val1 = obj1->object.values[i];
JsonValue* val2 = NULL;
for (int j = 0; j < obj2->object.count; j++) {
if (strcmp(key, obj2->object.keys[j]) == 0) {
val2 = obj2->object.values[j];
break;
}
}
if (val2) {
if (val1->type == JSON_OBJECT || val1->type == JSON_ARRAY) {
JsonValue* nested_result = malloc(sizeof(JsonValue));
if (find_differences(val1, val2, nested_result)) {
result->object.keys[result->object.count] = malloc(strlen(key) + 1);
strcpy(result->object.keys[result->object.count], key);
result->object.values[result->object.count] = nested_result;
result->object.count++;
has_diff = true;
}
} else if (!values_equal(val1, val2)) {
JsonValue* diff = malloc(sizeof(JsonValue));
diff->type = JSON_ARRAY;
diff->array.items = malloc(2 * sizeof(JsonValue*));
diff->array.items[0] = val1;
diff->array.items[1] = val2;
diff->array.count = 2;
result->object.keys[result->object.count] = malloc(strlen(key) + 1);
strcpy(result->object.keys[result->object.count], key);
result->object.values[result->object.count] = diff;
result->object.count++;
has_diff = true;
}
}
}
} else if (obj1->type == JSON_ARRAY) {
result->type = JSON_OBJECT;
result->object.keys = malloc(1000 * sizeof(char*));
result->object.values = malloc(1000 * sizeof(JsonValue*));
result->object.count = 0;
int min_len = obj1->array.count < obj2->array.count ? obj1->array.count : obj2->array.count;
for (int i = 0; i < min_len; i++) {
JsonValue* val1 = obj1->array.items[i];
JsonValue* val2 = obj2->array.items[i];
if (val1->type == JSON_OBJECT || val1->type == JSON_ARRAY) {
JsonValue* nested_result = malloc(sizeof(JsonValue));
if (find_differences(val1, val2, nested_result)) {
char key[20];
sprintf(key, "%d", i);
result->object.keys[result->object.count] = malloc(strlen(key) + 1);
strcpy(result->object.keys[result->object.count], key);
result->object.values[result->object.count] = nested_result;
result->object.count++;
has_diff = true;
}
} else if (!values_equal(val1, val2)) {
JsonValue* diff = malloc(sizeof(JsonValue));
diff->type = JSON_ARRAY;
diff->array.items = malloc(2 * sizeof(JsonValue*));
diff->array.items[0] = val1;
diff->array.items[1] = val2;
diff->array.count = 2;
char key[20];
sprintf(key, "%d", i);
result->object.keys[result->object.count] = malloc(strlen(key) + 1);
strcpy(result->object.keys[result->object.count], key);
result->object.values[result->object.count] = diff;
result->object.count++;
has_diff = true;
}
}
}
return has_diff;
}
int main() {
char line1[10000], line2[10000];
fgets(line1, sizeof(line1), stdin);
fgets(line2, sizeof(line2), stdin);
// Remove newlines
line1[strcspn(line1, "\n")] = 0;
line2[strcspn(line2, "\n")] = 0;
char* p1 = line1;
char* p2 = line2;
JsonValue* obj1 = parse_value(&p1);
JsonValue* obj2 = parse_value(&p2);
if (!obj1 || !obj2) {
printf("{}");
return 0;
}
JsonValue result;
if (find_differences(obj1, obj2, &result)) {
print_value(&result);
} else {
printf("{}");
}
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
n
2n
✓ Linear Growth
Space Complexity
n
2n
✓ Linear Space
23.0K Views
MediumFrequency
~25 minAvg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.