# Ordered Character Check

> Check if all As appear before all Bs.

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

Domain: Python · Difficulty: easy · Seniority: L6

## Problem

Given a string containing only 'A' and 'B' characters, return True if every A comes before every B (once a B appears, no A follows). Empty string returns True.

## Worked solution and explanation

### Why this problem exists in real interviews

Checking that all As precede all Bs in a string tests **state machine reasoning** and whether you can detect an order violation in a single pass. It is a clean probe of sequential validation logic.

---

### Break down the requirements

#### Step 1: Scan left to right

Once you see a 'B', every subsequent character must also be 'B'. If an 'A' appears after a 'B', the order is violated.

#### Step 2: Track whether B has been seen

Use a boolean flag. Once set, any 'A' means the string is invalid.

---

### The solution

**Single-pass state flag for order validation**

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

> **Time and Space Complexity**
>
> **Time:** O(n) where n is the string length. Single pass with early termination.
> 
> **Space:** O(1). One boolean flag.

> **Interviewers Watch For**
>
> Early termination on the first violation rather than scanning the entire string. This shows efficiency awareness even on simple problems.

> **Common Pitfall**
>
> Not handling the case where only 'A' characters exist or only 'B' characters exist. Both are valid orderings and should return True.

---

## Common follow-up questions

- What if the alphabet has three characters (A, B, C) that must be in order? _(Tests extending to track which 'phase' you are in and rejecting backward transitions.)_
- How would you return the index of the first violation? _(Tests returning the position instead of a boolean for debugging purposes.)_
- What if the check should be case-insensitive? _(Tests normalizing with `.upper()` before comparison.)_

## Related

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