ITPEC FE Subject B April 2024 Question 13

Source exam: ITPEC FE Subject B April 2024Topic: Stack

ITPEC FE Subject B April 2024 — Question 13 of 20

Balanced brackets check using a stack.

The program checks whether a string of brackets is balanced. It iterates through each character:
- If the character is an opening bracket ((, {, [), it is pushed onto the stack.

- If it is a closing bracket, the top of the stack is popped and its expected closing bracket is looked up via get_closing_bracket.

Blank A: `≠ c`
After popping the stack and finding the expected closing bracket, we compare it with the current character c. If they do not match (≠ c), the brackets are mismatched → return false.

Blank B: `stack.isEmpty()`
After processing all characters, we check whether the stack is empty. If it is, every opening bracket had a match → return true. If not, some brackets were never closed → return false.

Blank C: `chars[2]`
get_closing_bracket finds the bracket pair where chars[1] (the opening bracket) matches the input. It returns chars[2] — the corresponding closing bracket. (Arrays are 1-indexed in this pseudocode.)

Why not others:
- (a–d) all use = c for A, which inverts the mismatch check — would return false when brackets do match.

- (e) A is correct (≠ c), but C = chars[1] returns the opening bracket instead of the closing one.

- (f) A and C are correct, but B = not stack.isEmpty() inverts the final check — returns true when unmatched brackets remain.

- (g) A and B are correct, but C = chars[1] returns the opening bracket instead of closing.

Key rule: In balanced bracket problems, after processing all characters, stack.isEmpty() must return true for the expression to be balanced. With 1-indexed arrays, chars[2] is the closing bracket in each pair.

AI-generated — may contain errors

The original exam layout is preserved in the image so diagrams, formulas, tables, and code remain accurate.

This question comes from an official ITPEC past paper. ITPEC Practice is an independent study tool and is not affiliated with ITPEC. See the official FE past-paper collection or Report an issue.