Neural Mastery
← Back to Practice

Full Return-to-Go Sequence

Difficulty: Medium · Concept: RL Fundamentals — Markov Decision Processes (MDPs)

Discounted Return computed a single number, G0G_0, from the start of an episode. But every value function needs GtG_t for every timestep tt in a trajectory, not just the first — training a value estimator means comparing its prediction at each state against the actual return-to-go from that point onward.

The naive approach re-runs the whole sum from scratch at every ttO(n)O(n) work per timestep, O(n2)O(n^2) total across the trajectory. There's a much cheaper way, using the same recursive identity noted at the end of the original problem: Gt=rt+γGt+1G_t = r_t + \gamma G_{t+1}. Compute backward from the end of the episode, and each GtG_t costs O(1)O(1) given Gt+1G_{t+1} — no re-summing.

Your task: implement returns_to_go(rewards, gamma) in O(n)O(n) time, returning a list the same length as rewards, where entry tt is GtG_t.

Implement it yourself
assert returns_to_go([1, 1, 1], 1.0) == [3, 2, 1] assert returns_to_go([1, 1, 1, 1], 0.5) == [1.875, 1.75, 1.5, 1.0] assert returns_to_go([], 0.9) == [] assert returns_to_go([5], 0.9) == [5] assert all(abs(a - b) < 1e-9 for a, b in zip(returns_to_go([2, 4], 0.9), [5.6, 4.0]))

Next: Design a Min Stack

Last updated Sep 5, 2026Edit this pageReport an issue