# The Tail Trimmer

> Remove the k-th item from the back without counting forward first.

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

Domain: Python · Difficulty: easy · Seniority: L3

## Problem

Given a list and positive integer k, return a new list with the k-th element from the end removed (k=1 removes the last element). If k exceeds the length, return the original list unchanged.

## Worked solution and explanation

### Why this problem exists in real interviews

This tests **index arithmetic from the end of a list** and boundary checking. Removing the k-th element from the end probes whether a candidate can translate a reverse-position specification into a forward index cleanly.

---

### Break down the requirements

#### Step 1: Validate that k is within range

If k is larger than the list length or non-positive, return the list unchanged.

#### Step 2: Convert k-from-end to a forward index

The k-th element from the end has index `len(lst) - k`.

#### Step 3: Remove the element at that index

Build a new list excluding the element at the computed position.

---

### The solution

**Reverse-index conversion with slice concatenation**

```python
def remove_kth_from_end(lst: list, k: int) -> list:
    if k <= 0 or k > len(lst):
        return lst
    idx = len(lst) - k
    result = lst[:idx] + lst[idx + 1:]
    return result
```

> **Time and Space Complexity**
>
> **Time:** O(n) for creating the new list via slicing.
> 
> **Space:** O(n) for the new list.

> **Interviewers Watch For**
>
> Clean handling of out-of-range k. Returning the original list unchanged is more graceful than raising an exception for this use case.

> **Common Pitfall**
>
> Off-by-one when converting from 1-indexed k to 0-indexed position. `k=1` means the last element, which is at index `len(lst) - 1`, not `len(lst)`.

---

## Common follow-up questions

- How would you do this in-place? _(Tests using `lst.pop(len(lst) - k)` for O(n) in-place removal.)_
- What if you could not compute the length in advance? _(Tests the two-pointer technique: advance one pointer k steps ahead, then move both until the leader reaches the end.)_
- What if k could be negative, meaning from the start? _(Tests extending the function to handle bidirectional indexing.)_

## Related

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