Lists & Stacks Hard
Persistent Functional List
FList is an immutable singly linked list: cons creates a new head that points at the prior list, while map and filter recursively build new versions. Values are consed in input order, so the visible list order is reversed.
Advanced input, scenarios & complexity
Trace input
Bounded JSONEdit the exact operation sequence, then build a deterministic trace.
Source scenarios
Complexity
BestO(N) for map, filter, and length; O(1) for head, tail, and cons
AverageO(N) time and O(N) recursion space for map/filter/length
WorstO(N) time and O(N) recursion space
SpaceO(N) new nodes for map; O(K) new nodes for filter
Data structure in memory
Follow the active references as the source executes.
Operation result
Current stepReady to explore
Source behavior & common mistakes
Build an FList by repeated cons, measure its recursive length, then map a fixed safe function or filter for even values. Iterate the result while keeping the original root available to show persistence.
- Repeated cons prepends: input [0, 1, 2] creates the list 2 → 1 → 0.
- map applies f while recursive calls return, then conses each mapped head onto the mapped tail.
- filter tests each head before recursing, then conses retained values while calls return.
- Neither map nor filter mutates its receiver; the original root still names the original list.
- head() and tail() on Nil throw IllegalArgumentException in this upstream implementation.
- The upstream iterator's next() does not check hasNext(); calling it on Nil reaches head() and throws IllegalArgumentException.
- The upstream iterator rejects remove() with UnsupportedOperationException.
- Java int increment and multiplication wrap at signed 32-bit boundaries.
Algorithm code
JavaFList.javaStep linked
The highlighted line follows the current step.
Ready to begin
Press Play to see what happens.
Detailed execution
Snapshot 1 / 1
Understand this operation
Scroll through the stored teaching scenes. The Theater keeps your place.