Top-Level JSON Array Split
JavaScript
Hard
5 views
Problem Description
One line has a JSON array as plain text (do NOT parse). Count how many top-level elements are present, ignoring commas inside strings/brackets. Print the count.
Input Format
One line JSON array text.
Output Format
One integer count.
Sample Test Case
Input:
[1,2,[3,4],{"a":5},"x,y"]
Constraints
Input is valid JSON array text. Length up to 2e5.
Official Solution
const fs=require('fs');const s=fs.readFileSync(0,'utf8').trim();if(!s)process.exit(0);const QUOTE=34;let i=0;while(i<s.length&&/\\s/.test(s[i]))i++;if(i>=s.length||s[i]!=='['){process.stdout.write('0');process.exit(0);}i++;let depth=0,inStr=false,esc=false,count=0,hasVal=false;for(;i<s.length;i++){const ch=s[i];const cc=s.charCodeAt(i);if(inStr){if(esc){esc=false;continue;}if(ch==='\\\\'){esc=true;continue;}if(cc===QUOTE)inStr=false;continue;}if(cc===QUOTE){inStr=true;hasVal=true;continue;}if(ch==='['||ch==='{'){depth++;hasVal=true;continue;}if(ch===']'){if(depth===0)break;depth--;continue;}if(ch==='}'&&depth>0){depth--;continue;}if(depth===0){if(ch===','){if(hasVal){count++;hasVal=false;}continue;}if(!/\\s/.test(ch))hasVal=true;}}if(hasVal)count++;process.stdout.write(String(count));
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!