Deep Required Paths Checker
JavaScript
Hard
5 views
Problem Description
Line1 is JSON object. Line2 has integer q. Next q lines are paths like a.b[0].c. If any path missing, collect them and print MISSING count and list. Else print OK.
Input Format
Line1: JSON object. Line2: q. Next q lines: path.
Output Format
One line output.
Sample Test Case
Input:
{\"a\":{\"b\":[{\"c\":5}]}}
3
a.b[0].c
a.x
z
Constraints
Total nodes+path length up to 2e5.
Official Solution
const fs=require('fs');const txt=fs.readFileSync(0,'utf8');const lines=txt.split(/\
?\
/);let at=0;const oLine=(lines[at++]||'').trim();const q=Number((lines[at++]||'').trim());if(!oLine||!q)process.exit(0);const obj=JSON.parse(oLine);const parsePath=p=>{let t=[];let i=0;while(i<p.length){if(p[i]==='.')i++;else if(p[i]==='['){i++;let j=i;while(j<p.length&&p[j]!==']')j++;t.push({k:null,i:Number(p.slice(i,j))});i=j+1;}else{let j=i;while(j<p.length&&p[j]!=='.'&&p[j]!=='[')j++;t.push({k:p.slice(i,j),i:null});i=j;}}return t;};const get=(o,toks)=>{let cur=o;for(const tok of toks){if(cur===null||cur===undefined)return undefined;if(tok.k!==null){if(typeof cur!=='object')return undefined;cur=cur[tok.k];}else{if(!Array.isArray(cur))return undefined;cur=cur[tok.i];}}return cur;};let miss=[];for(let i=0;i<q;i++){const p=(lines[at++]||'').trim();if(!p)continue;const v=get(obj,parsePath(p));if(v===undefined)miss.push(p);}if(miss.length)process.stdout.write('MISSING '+miss.length+' '+miss.join(' '));else process.stdout.write('OK');
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!