TweakCode
Recursion lessons

Recursion

Trust the smaller call

Why it matters

Generated grammars and recursively encoded sequences can represent enormous outputs while a query asks for one position. Expanding all earlier data wastes memory and can make a single lookup impossible; row 30 here already contains more than 500 million symbols. The requested kth symbol must be found without constructing any complete row.

Example

K-th Symbol in Grammar

Row 1 is 0. Each 0 becomes 01 and each 1 becomes 10 to form the next row. Return the kth symbol (1-based) in row n. Do not build the whole row.

Input
n = 4, k = 5
Output
1

Approach 2 · Resolve the bottleneck

The idea

Keep one example in view

K-th Symbol in Grammar

n = 4, k = 5→1

The baseline, Build every row, is O(2ⁿ) · O(2ⁿ). The better model below keeps this exact input and removes that bottleneck.

For n = 4 and k = 5, brute construction writes 1 + 2 + 4 + 8 symbols to read one of them. Follow position 5's single parent in each earlier row instead, then copy or flip while returning.

For n = 4 and k = 5, position 5 came from position (5 + 1) // 2 = 3 in row 3. That position came from 2 in row 2, then from 1 in row 1, whose value is the base symbol 0.

Unwind the chain using each child's position. k = 2 is even, so row 2 flips 0 to 1. k = 3 is odd, so row 3 copies 1; k = 5 is odd, so row 4 also copies 1. Only one position from each of the four rows is examined.

Visual anchor

K-th Symbol in Grammar

row 1

0
0

row 2

01
0
1

row 3

0123
0
1
1
0

row 4

01234567
0
1
1
0
1
0
0
1
Row 1 is just "0". The base case answers directly.

Pro

The rest of this is on Pro

The idea above is free. The walkthrough, the cost, and the practice are on Pro.