# Rotate Buffer

> The buffer is full. Rotate it.

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

Domain: Python · Difficulty: medium · Seniority: L4

## Problem

Given a list and integer k (possibly >= len or negative), return the list rotated right by k positions.

## Worked solution and explanation

### Why this problem exists in real interviews

Right-rotating a list by k positions tests **modular arithmetic** and **slice concatenation**. It is a classic array manipulation that checks whether you handle k larger than the list length.

---

### Break down the requirements

#### Step 1: Normalize k with modulo

Use `k % len(lst)` to handle k values larger than the list length.

#### Step 2: Split and recombine

Take the last k elements and prepend them to the remaining elements.

---

### The solution

**Modulo-normalized slice rotation**

```python
def rotate_right(lst, k):
    if not lst:
        return []
    k = k % len(lst)
    result = lst[-k:] + lst[:-k] if k else list(lst)
    return result
```

> **Time and Space Complexity**
>
> **Time:** O(n) for the slice and concatenation.
> 
> **Space:** O(n) for the new list.

> **Interviewers Watch For**
>
> Using `k % len(lst)` to normalize. Without this, `k > len(lst)` would produce incorrect slices or empty results.

> **Common Pitfall**
>
> Not handling `k = 0` or `k = len(lst)`, both of which should return the original list unchanged.

---

## Common follow-up questions

- How would you rotate in place without extra space? _(Tests the three-reverse algorithm: reverse the whole list, then reverse the first k, then reverse the rest.)_
- How would you rotate left instead of right? _(Tests that left rotation by k is the same as right rotation by `n - k`.)_
- What if k is negative? _(Tests converting negative k to a positive equivalent using modulo.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/rotate_buffer)
- [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.