Shadowing Counter
JavaScript
Medium
3 views
Problem Description
You are given variable declarations line by line in a tiny language: 'let x', 'block', 'end'. Count how many times a 'let x' shadows an existing x in an outer scope.
Input Format
n then n commands, one per line.
Output Format
One integer count.
Sample Test Case
Input:
7
let a
block
let a
let b
block
let b
end
Official Solution
const fs=require('fs');const lines=fs.readFileSync(0,'utf8').trim().split(/\
?\
/);if(!lines[0])process.exit(0);const n=Number(lines[0]);const stack=[new Map()];let count=0;for(let i=1;i<=n;i++){const line=lines[i].trim();if(line==='block'){stack.push(new Map());continue;}if(line==='end'){stack.pop();continue;}const parts=line.split(/\\s+/);if(parts[0]==='let'){const name=parts[1];let exists=false;for(let j=stack.length-2;j>=0;j--){if(stack[j].has(name)){exists=true;break;}}if(exists)count++;stack[stack.length-1].set(name,true);}}process.stdout.write(String(count));
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!