# The Password Builder

> Random characters, fixed rules.

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

Domain: Python · Difficulty: easy · Seniority: L3

## Problem

Given a positive integer length and a non-empty string pool, return a string of `length` characters where position i is pool[i % len(pool)].

## Worked solution and explanation

### Why this problem exists in real interviews

This tests **modular arithmetic** for cyclic indexing, a basic but essential skill. It checks whether candidates can cycle through a character pool using the modulo operator without falling back to complex conditional logic.

---

### Break down the requirements

#### Step 1: Iterate for the requested length

Loop from 0 to length-1, building one character per iteration.

#### Step 2: Index the pool with modulo

Use `pool[i % len(pool)]` to wrap around when i exceeds the pool length.

#### Step 3: Join and return the result

Collect characters in a list and join them into a string.

---

### The solution

**Cyclic pool indexing with modulo**

```python
def generate_password(length, pool):
    chars = []
    for i in range(length):
        chars.append(pool[i % len(pool)])
    result = ''.join(chars)
    return result
```

> **Time and Space Complexity**
>
> **Time:** O(length) for the loop.
> 
> **Space:** O(length) for the output string.

> **Interviewers Watch For**
>
> Do you use `%` naturally? The modulo operator for cycling is a fundamental pattern. Candidates who use if/else to manually reset an index counter are overcomplicating it.

> **Common Pitfall**
>
> Not handling `length = 0`. The loop simply does not execute, producing an empty string, which is correct.

---

## Common follow-up questions

- What if the pool were empty? _(Tests guarding against division by zero in the modulo.)_
- How would you shuffle the characters to make the password less predictable? _(Tests using random.shuffle or random.choice.)_
- What if certain characters must appear at least once? _(Tests placing required characters first, then filling the rest.)_

## Related

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