Mutable State and Undo

Intermediate Algorithms and Data Structures English
Also available: Deutsch
Created by Best · 16.08.2026 at 09:13 UTC

Often, a shared board array is mutated: set field, recursive call, reset field. An alternative is immutable copies (more expensive).

Source of errors: forgetting the undo, then the next branch is contaminated.

Where used

In-place backtracking saves allocations; undo must be exact. The same pattern is found in editors (command stack) and in transactions with rollback.

Depth

Mutable state avoids copying large sub-candidates. A recursion level makes a small change, calls the next step, and then undoes exactly that change. This pattern is efficient but requires strict symmetric treatment of forward and backward operations.

The undo operation must also occur when the recursive call does not find a solution or collects multiple solutions. An alternative strategy produces a new immutable structure for each branch. This is often easier to check but requires more allocations and copying work.

Difficulty levels

  1. Specify the appropriate inverse operation for each mutation.
  2. Consistently update and reset multiple coupled structures.
  3. Weigh between copying and undo based on size and risk of error.

Pitfalls

An early return can skip the undo. Flat copies of nested lists are equally problematic because inner objects are still shared, and changes may seep into other branches.

University approvals: 0
Tasks
Question 1

Why is Undo important for mutable Boards?

Question 2

Why is a return statement within a mutating backtracking branch particularly important to check?

Question 3

Implement Board with place and undo. cols[row] stores the column of the queen, a free field has the value -1.

Hint

An array field is modified with cols[row] = value. The same int value as used in the constructor can be used for the free marking.

Starter code is prefilled; replace TODO blocks with your solution.
1 test case will be used for grading
Run checks runtime behavior only. Final correctness is evaluated when you submit.
Card Info
  • Topic: Algorithms and Data Structures
  • Difficulty: Intermediate
  • Completed: 0 users
Creator
Best
Best
BestBuddy