Mini Scope Shadow Counter
Python
Hard
3 views
Problem Description
Read a tiny language with commands: 'let x', 'block', 'end'. Each block makes a new scope. Count how many times a let shadows a variable from an outer scope.
Input Format
First line n. Next n lines commands.
Output Format
One integer shadowCount.
Sample Test Case
Input:
7
let a
block
let a
let b
block
let b
end
Official Solution
import sys
lines=sys.stdin.read().splitlines()
if not lines or not lines[0].strip():
sys.exit(0)
n=int(lines[0].strip())
stack=[set()]
shadow=0
for i in range(1,1+n):
line=(lines[i] if i<len(lines) else '').strip()
if not line: continue
if line=='block':
stack.append(set())
continue
if line=='end':
stack.pop()
continue
parts=line.split()
if parts[0]=='let':
name=parts[1]
exists=False
for j in range(len(stack)-2,-1,-1):
if name in stack[j]:
exists=True
break
if exists:
shadow+=1
stack[-1].add(name)
sys.stdout.write(str(shadow))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!