Deep Merge Strict Types
JavaScript
Hard
6 views
Problem Description
Two JSON objects are given on two lines. Deep merge them: object+object merges keys, array+array concatenates, primitives override. But if types mismatch (like object vs array), stop and print TYPE_MISMATCH path.
Input Format
Line1: JSON object A. Line2: JSON object B.
Output Format
One line output.
Sample Test Case
Input:
{"a":{"x":1}}
{"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 isObj=v=>v!==null&&typeof v==='object'&&!Array.isArray(v);const merge=(x,y,path)=>{const ax=Array.isArray(x),ay=Array.isArray(y);if(ax&&ay)return x.concat(y);if(isObj(x)&&isObj(y)){const out={};for(const k of Object.keys(x))out[k]=x[k];for(const k of Object.keys(y)){out[k]=k in out?merge(out[k],y[k],path?path+'.'+k:k):y[k];}return out;}if((ax||isObj(x)) && (ay||isObj(y)) && !(ax&&ay) && !(isObj(x)&&isObj(y))){throw new Error('TYPE_MISMATCH '+(path||''));}return y;};try{process.stdout.write(JSON.stringify(merge(A,B,'')));}catch(e){process.stdout.write(e.message);}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!