SMALLTALK LAB
Catalan Numbers in Squeak: Count Trees and Balanced Parentheses
Count ordered tree shapes and balanced parentheses with exact integers. Build a dynamic-programming table, inspect the actual strings, then cross-check the result with a second algorithm.
Before you begin
Open a Squeak Workspace. Select one complete checkpoint, including its temporary declarations, and choose Print it. Every checkpoint is independent. Inputs are nonnegative integer sizes; use the small values shown before exploring larger ones. No packages or network access are required.
These are native Squeak 6.1 examples. Each checkpoint is independent: open the download as text, copy one complete expression into Workspace and choose Print it. Do not file in the checkpoint collection as a class definition.
Expected values are Smalltalk expressions. The printer may show explicit Symbol markers: #(A B) and #(#A #B) represent the same array of Symbols.
01 - Count the empty shape once
Let C(n) count ordered binary-tree shapes with n nodes. Each node has a left slot and a right slot, either of which may be empty. Left and right are distinguished: a child on the left is not the same shape as a child on the right. There is exactly one empty shape, so C(0) = 1. That one is essential: multiplying by the choices for an empty side must preserve the choices for the other side, not erase them. We store C(n) at array position n + 1 because Squeak arrays start at 1.
| counts |
counts := Array new: 3 withAll: 0.
counts at: 1 put: 1.
counts at: 2 put: (counts first * counts first).
counts at: 3 put:
((counts first * counts second) + (counts second * counts first)).
countsExpected: #(1 1 2)

Try it: Draw the two two-node shapes. Why does changing C(0) to zero make every later count zero?
02 - Split four nodes around their root
A nonempty tree spends one node on its root. For four nodes, the remaining three split into left/right sizes (0,3), (1,2), (2,1), or (3,0). For a fixed split the two sides are independent, so multiply their counts. Different splits are disjoint, so add their products. This gives C(n) = sum of C(i) * C(n-1-i), for i from 0 through n-1. These are shape counts, not choices of labeled nodes.
| earlier products |
earlier := #(1 1 2 5).
products := (0 to: 3) collect: [:leftSize |
(earlier at: leftSize + 1) * (earlier at: 4 - leftSize)].
{products asArray. products sum}Expected: #(#(5 2 2 5) 14)

Try it: Explain the middle product 1 * 2. Swapping left and right reverses the product list, but does not remove either split.
03 - Build the table bottom up
Compute smaller sizes first and reuse them. At size n, every referenced entry is already finished. The inner loop visits n splits, so the algorithm uses O(n squared) integer additions/multiplications and O(n) table entries. Those are operation counts, not constant-time bit costs: exact integers grow with n. The temporary total is reset for each new size. No floating-point approximation or recursive recomputation is needed.
| limit counts |
limit := 10.
counts := Array new: limit + 1 withAll: 0.
counts at: 1 put: 1.
1 to: limit do: [:size | | total |
total := 0.
0 to: size - 1 do: [:leftSize |
total := total + ((counts at: leftSize + 1)
* (counts at: size - leftSize))].
counts at: size + 1 put: total].
countsExpected: #(1 1 2 5 14 42 132 429 1430 4862 16796)

Try it: Change limit to 4 and compare the last entry with checkpoint 2. Keep the empty entry even if only nonempty results interest you.
04 - Generate the five three-pair strings
The same decomposition describes balanced parentheses: a nonempty string is uniquely (L)R, where L and R are balanced strings. The closing parenthesis matching the first opening parenthesis fixes the split uniquely. Its inside contains i pairs, and its remainder contains n-1-i pairs. Map the empty tree to the empty string and a node to (left)right; this explains the shared count. This small recursive generator is for inspection, not large inputs: output size itself grows rapidly.
| generate words |
generate := [:pairs | | result |
result := OrderedCollection new.
pairs = 0
ifTrue: [result add: '']
ifFalse: [0 to: pairs - 1 do: [:insideSize |
(generate value: insideSize) do: [:inside |
(generate value: pairs - 1 - insideSize) do: [:remainder |
result add: '(', inside, ')', remainder]]]].
result asArray].
words := generate value: 3.
{words. words asSet size}Expected: #(#('()()()' '()(())' '(())()' '(()())' '((()))') 5)

Try it: Find the first matching close in each string. That split, rather than an arbitrary position, prevents duplicate construction.
05 - Check every prefix, not just the total
Equal numbers of opening and closing parentheses are necessary but insufficient. A balanced string must never have a negative prefix balance, and must finish at zero. Our validator also rejects every character other than an opening or closing parenthesis; it deliberately does not accept spaces or source-code comments. Keep the validity flag once it becomes false. A later opening parenthesis cannot repair a premature close.
| balanced samples |
balanced := [:word | | depth valid |
depth := 0. valid := true.
word do: [:character |
character = $(
ifTrue: [depth := depth + 1]
ifFalse: [character = $)
ifTrue: [depth := depth - 1]
ifFalse: [valid := false]].
depth < 0 ifTrue: [valid := false]].
valid and: [depth = 0]].
samples := #('' '(()())' ')(' '(()' '(a)').
samples collect: [:word | balanced value: word]Expected: #(true true false false false)

Try it: Both )( and () finish at zero. Identify the prefix that rejects the first. Add a string containing a space and predict the result.
06 - Keep large counts exact
Squeak promotes integers as their values grow. Twenty nodes already produce 6,564,120,420 shapes, beyond a signed 32-bit integer. Staying entirely in integer arithmetic preserves the exact answer. Counting is still practical here, while generating billions of actual strings is not. A compact table stores counts, not the shapes they represent. This checkpoint intentionally repeats the full algorithm so it can run in a fresh Workspace selection.
| limit counts answer |
limit := 20.
counts := Array new: limit + 1 withAll: 0.
counts at: 1 put: 1.
1 to: limit do: [:size | | total |
total := 0.
0 to: size - 1 do: [:leftSize |
total := total + ((counts at: leftSize + 1)
* (counts at: size - leftSize))].
counts at: size + 1 put: total].
answer := counts last.
{answer. answer isInteger. answer > 2147483647}Expected: #(6564120420 true true)

Try it: Do not replace the arithmetic with Float values. What would storing all twenty-pair strings cost compared with storing just 21 counts?
07 - Compare with the central binomial coefficient
Choosing n opening positions among 2n slots gives binomial(2n,n), but it also includes strings that close too early. The Catalan identity is C(n) = binomial(2n,n) / (n+1). For n=4 there are 70 unrestricted choices, but only 14 balanced strings. This is not a Pascal-triangle row count: the prefix condition removes invalid choices. Compute the binomial coefficient multiplicatively, using exact division. Squeak / can produce an exact Fraction; here every division has an integer result.
| pairs central catalan |
pairs := 4.
central := 1.
1 to: pairs do: [:index |
central := central * (pairs + index) / index].
catalan := central / (pairs + 1).
{central. catalan. catalan isInteger}Expected: #(70 14 true)

Try it: Try pairs = 10 and compare with the table result 16796. Do not use rounded floating-point values as an exactness test.
08 - Cross-check with a prefix-walk counter
Use a second formulation as an independent check. A state records how many prefixes reach each nonnegative depth after a fixed number of characters. An opening moves up one; a closing moves down one, but never below zero. After 2n characters, only depth zero is counted. Ending at zero forces exactly n openings and n closings. We need not cap openings at n: prefixes that exceed that count cannot return to zero in the remaining steps. Separate current and next arrays prevent counting multiple moves in one iteration.
| pairs ways next |
pairs := 5.
ways := Array new: (2 * pairs) + 1 withAll: 0.
ways at: 1 put: 1.
1 to: 2 * pairs do: [:step |
next := Array new: ways size withAll: 0.
0 to: (2 * pairs) - 1 do: [:depth | | amount |
amount := ways at: depth + 1.
next at: depth + 2 put: (next at: depth + 2) + amount.
depth > 0 ifTrue: [
next at: depth put: (next at: depth) + amount]].
ways := next].
ways firstExpected: 42

Try it: Run pairs = 0, 1, 2, 3, 4 and compare 1, 1, 2, 5, 14. Why would updating ways in place corrupt the meaning of a single character step?
Watch the computed states

Download the visual experiment. Select the entire expression and Do it. Change stage := 0. to another supported stage, close the previous window, and run again. The GIF replays those native states. This example needs native Squeak; no new browser playground compatibility is claimed.
Reason about correctness and limits
C(0) is 1, not 0: an empty side is one valid choice.
C(n) lives at position n + 1. The right subtree of size n - 1 - i therefore lives at position n - i.
These are ordered, unlabeled shapes. Unordered trees or labeled nodes require different counting rules.
Never divide by two for symmetric splits. Left and right positions are meaningful, including equal-sized sides.
A zero final parenthesis balance does not guarantee valid prefixes.
The recursive generator is intentionally tiny. Fast counting does not make exponential-sized output cheap.
Keep exact Integer arithmetic. Rounded Float agreement is weaker than exact equality.
Three practice challenges
Explain the next split
Using C(0)..C(4) = 1, 1, 2, 5, 14, list all five products for C(5).
Show solution
The products are 1*14, 1*5, 2*2, 5*1, 14*1. Their sum is 14+5+4+5+14 = 42. Every split leaves four nodes after reserving one root.
Test both counting algorithms together
Turn the table recurrence and the prefix-walk counter into separate blocks. Compare their answers for each size from 0 through 8. What values should you see?
Show solution
Both should return #(1 1 2 5 14 42 132 429 1430). Initialize each block afresh for each call. The zero-size case must return 1 without entering either outer loop. Keep the two implementations separate so an indexing mistake is less likely to be copied.
Count invalid arrangements
For four pairs, how many strings have four opens and four closes but fail the balanced-prefix rule? Is that the number of all invalid length-eight strings?
Show solution
70 - 14 = 56 fail among the arrangements with four of each character. It is not all invalid binary parenthesis strings of length eight: there are 2 raisedTo: 8 = 256 strings in total and only 14 are balanced, leaving 242 invalid ones.
Continue learning
Pascal Triangle | Balanced Brackets | Recursive Tree | Fractions
Environment reference: official Squeak documentation. This lesson and its examples are original. Verified using native Squeak 6.1 build 23976 on Linux.