# The Order Enforcer

> Some rules say every A must come before every B.

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

Domain: Python · Difficulty: easy · Seniority: L3

## Problem

Given a string of lowercase letters, return True if no 'a' appears after any 'b' (once a 'b' is seen, all subsequent chars are not 'a'). Empty strings return True.

## Worked solution and explanation

### Why this problem exists in real interviews

This is a variant of the ordering constraint problem. It tests whether candidates can express a **state machine** with two states (before and after seeing the first B) in a clean single-pass scan.

---

### Break down the requirements

#### Step 1: Track whether a B has been seen

Use a boolean flag that flips to True when the first B character appears.

#### Step 2: After B appears, reject any A

Once the flag is True, encountering an A means the sequence is invalid.

#### Step 3: Return the validation result

If the scan completes without finding an A after a B, the sequence is valid.

---

### The solution

**State flag scan for ordering violation**

```python
def is_valid_order(s):
    seen_b = False
    for ch in s:
        if ch == 'B':
            seen_b = True
        elif ch == 'A' and seen_b:
            return False
    return True
```

> **Time and Space Complexity**
>
> **Time:** O(n) with a single pass.
> 
> **Space:** O(1). One boolean flag.

> **Interviewers Watch For**
>
> Is your solution concise and does it short-circuit on the first violation? Returning False immediately upon finding the first invalid character is both efficient and clean.

> **Common Pitfall**
>
> Checking all characters are A or B. The problem may contain other characters that are neither A nor B and should be ignored.

---

## Common follow-up questions

- What if there were three types (A, B, C) that must appear in order? _(Tests extending to a multi-state machine.)_
- What if you needed to return the index of the first violation? _(Tests tracking position alongside the boolean flag.)_
- What if the ordering rule were configurable? _(Tests parameterizing the character pair.)_

## Related

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