Validate Matching Block Keywords in a MATLAB Script
Last updated: November 29, 2026
Quick Overview
Given MATLAB source text, check that block keywords such as if, for, while, switch, try and function are closed by end, that elseif, else, case and catch appear only inside the right block, and report the line of the first problem.
MathWorks
November 29, 20260
0
0 solved
Given MATLAB source text, check that block keywords such as if, for, while, switch, try and function are closed by end, that elseif, else, case and catch appear only inside the right block, and report the line of the first problem.
The MATLAB Code Analyzer flags unbalanced blocks as you type, and this is a natural stack exercise for a MathWorks online assessment. Graders check stack usage, comment and string handling, and awareness that end also means 'last index' inside parentheses.
What the Interviewer Expects
- Uses a stack of (keyword, line) for open blocks
- Validates middle keywords against the block on top of the stack
- Strips comments and blanks out string literals before scanning
- Ignores end used as an index inside () or {}
- Reports the first error with a line number
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would you support block comments %{ ... %} and line continuation with ...?
- MATLAB uses ' both for strings and for transpose (A'). How would you tell them apart?
- How would you also verify that a switch block contains at least one case?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Input: a source string. Output: None if balanced, else (line_number, message) for the first problem: an end with nothing open, a middle keyword in the wrong block, or a block never closed (repor...
High-Level Design
Process line by line. Remove everything after % and replace quoted strings with empty quotes so disp('end') is not a keyword. Scan tokens: identifiers plus bracket characters. Track bracket depth;...