# Lag Column

> What came before this row?

Canonical URL: <https://datadriven.io/problems/lag_column>

Domain: Python · Difficulty: medium · Seniority: L3

## Problem

Given a list of values, return a list of the same length where each position i holds the value at position i-1 in the input. The first position (no predecessor) is None.

## Worked solution and explanation

### Why this problem exists in real interviews

Implementing a lag operation tests understanding of **window functions** in Python form. It mirrors `LAG()` in SQL and checks whether you handle the first-element boundary correctly.

---

### Break down the requirements

#### Step 1: The first element has no predecessor

Output None for position 0 since there is no prior value.

#### Step 2: Each subsequent element is the previous input value

For index i, the output is `values[i-1]`.

---

### The solution

**Offset copy with None for the first position**

```python
def lag(values):
    result = [None]
    for i in range(1, len(values)):
        result.append(values[i - 1])
    return result
```

> **Time and Space Complexity**
>
> **Time:** O(n) where n is the list length. Single pass.
> 
> **Space:** O(n) for the output list.

> **Interviewers Watch For**
>
> Recognizing this as a simple offset rather than overcomplicating with deque or sliding window logic. The direct index approach is the clearest.

> **Common Pitfall**
>
> Returning an empty list when the input has one element. A single-element input should return `[None]`.

---

## Common follow-up questions

- How would you generalize to a lag of k positions? _(Tests prepending k Nones and taking `values[:-k]` or using a loop with offset i-k.)_
- How would you implement a lead (forward-looking) function? _(Tests the mirror operation: shift values left and fill None at the end.)_
- How does this relate to SQL's LAG() window function? _(Tests mapping `LAG(col, 1) OVER (ORDER BY ...)` to this exact pattern.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/lag_column)
- [Python Interview Questions](https://datadriven.io/python-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.