Deep Equal (JSON)
JavaScript
Hard
3 views
Problem Description
Two JSON values are given on two lines. Check deep equality: primitives compare normally (NaN does not appear in JSON), arrays compare by order, objects compare by keys and values ignoring key order. Print YES or NO.
Input Format
Line1: JSON A. Line2: JSON B.
Sample Test Case
Input:
{"a":[1,2],"b":null}
{"b":null,"a":[1,2]}
Constraints
Total nodes up to 2e5.
Official Solution
const fs=require('fs');const txt=fs.readFileSync(0,'utf8');const lines=txt.split(/\
?\
/);const aLine=(lines[0]||'').trim();const bLine=lines.slice(1).join('\
').trim();if(!aLine||!bLine)process.exit(0);const A=JSON.parse(aLine);const B=JSON.parse(bLine);const eq=(x,y)=>{if(x===y)return true;if(x===null||y===null)return x===y;const ax=Array.isArray(x),ay=Array.isArray(y);if(ax||ay){if(!(ax&&ay))return false;if(x.length!==y.length)return false;for(let i=0;i<x.length;i++){if(!eq(x[i],y[i]))return false;}return true;}if(typeof x!=='object'||typeof y!=='object')return false;const kx=Object.keys(x);const ky=Object.keys(y);if(kx.length!==ky.length)return false;kx.sort();ky.sort();for(let i=0;i<kx.length;i++){if(kx[i]!==ky[i])return false;}for(const k of kx){if(!eq(x[k],y[k]))return false;}return true;};process.stdout.write(eq(A,B)?'YES':'NO');
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!