The Line Cutter

An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

Domain
Python
Difficulty
easy
Seniority
L3
Asked in
phData

Problem

Given a string s and two distinct characters a and b, return True if every occurrence of a precedes every occurrence of b (i.e., the last index of a is before the first index of b). If either character is absent, return True.

Did everyone with an A-pass get through before the B-crowd arrived?

Example 1

Input:

s = "aaabbb", a = "a", b = "b"

Output:

true

Example 2

Input:

s = "aabba", a = "a", b = "b"

Output:

false

Worked solution and explanation

Why this problem exists in real interviews

This tests string scanning and ordering constraints. It reveals whether a candidate can express a simple ordering invariant (all a before all b) without overcomplicating the logic with nested loops or sorting.


Break down the requirements

Step 1: Find the last occurrence of character a

Scan the string to find the rightmost index where a appears. If a is absent, the constraint is trivially satisfied.

Step 2: Find the first occurrence of character b

Scan to find the leftmost index where b appears. If b is absent, the constraint is trivially satisfied.

Step 3: Compare the two positions

If the last a comes before the first b, every a precedes every b. Otherwise, at least one a appears after a b.


The solution

Last-a vs first-b index comparison
def check_order(s, a, b):
    last_a = -1
    first_b = len(s)
    for i in range(len(s)):
        if s[i] == a:
            last_a = i
        if s[i] == b and i < first_b:
            first_b = i
    return last_a < first_b

Common follow-up questions