Run Strings Through a Two-Letter State Machine
StringsAuto-graded · 16 test casesLast updated
Simulate a partial deterministic automaton over the letters a and b, handling missing transitions, invalid symbols and empty input, and report acceptance for a batch of query strings.
You are given the description of a state machine that reads text one letter at a time. The only letters it understands are "a" and "b". Your task is to answer a batch of queries, where each query asks whether the machine accepts a particular string.
Machine description
states: the list of state names (strings).transitions: a dictionary of dictionaries.transitions[u][c]is the state the machine moves to when it is in stateuand reads letterc.start_state: the state the machine is in before reading anything.accept_states: the list of states that count as accepting.
The transition table may be incomplete:
- A state may have no entry at all in
transitions. This includes states that appear only as the destination of other transitions. - A state may have an entry that lacks one of the letters
"a"or"b".
Whenever the machine needs a transition that does not exist, it falls into a dead state. From the dead state it can never leave and it is never accepting, so the string is rejected.
Queries
You receive two parallel lists, operations and arguments. The i-th query has the operation name operations[i] and the argument list arguments[i]. Every operation is "accepts", and its argument list holds exactly one string s.
For each query, run the machine on s starting at start_state, reading characters left to right, following transitions at each step. The query result is True if and only if all of the following hold:
- Every character of
sis either"a"or"b". Any other character (uppercase letters, digits, spaces, punctuation, etc.) means rejection. - No missing transition is needed while reading
s. - After the last character, the current state is in
accept_states.
The empty string consumes no characters, so it is accepted exactly when start_state is in accept_states.
If an operation name is anything other than "accepts", raise a ValueError.
Return a list of booleans with one result per query, in the same order as the queries.
Constraints
1 <= len(states) <= 10^40 <= len(accept_states) <= len(states)0 <= len(s) <= 10^5for each query string- At most 100 queries
- Characters in
sare printable ASCII - Each query should take
O(len(s))time andO(1)extra space
Examples
Example 1
Input: run_automaton_queries(['q0', 'q1', 'q2'], {'q0': {'a': 'q1', 'b': 'q0'}, 'q1': {'a': 'q1', 'b': 'q2'}, 'q2': {'a': 'q1', 'b': 'q0'}}, 'q0', ['q2'], ['accepts', 'accepts', 'accepts', 'accepts'], [['aab'], ['ab'], ['aba'], ['']])
Output: [True, True, False, False]
Example 2
Input: run_automaton_queries(['even', 'odd'], {'even': {'a': 'odd', 'b': 'even'}, 'odd': {'a': 'even', 'b': 'odd'}}, 'even', ['even'], ['accepts', 'accepts', 'accepts', 'accepts'], [[''], ['b'], ['ba'], ['baab']])
Output: [True, True, False, True]
Hints
Hint 1
Think of the machine as a lookup table plus one variable holding the current state. Update that variable once per character.
Hint 2
Convert the accepting states to a set so the final membership test is constant time. Use `.get` on the outer dictionary so a state with no row does not raise a KeyError.
Hint 3
You can stop reading as soon as you hit a character outside `a`/`b` or a missing transition. The empty string needs no special case: the loop simply never runs and you check the start state.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The machine is a transition table plus a single "current state" variable. Build a set from accept_states once. For each query, start at start_state and process the characters of s in order:
- If the character is not
"a"or"b", the answer isFalse, so stop. - Look up the current state's row with
transitions.get(state). If the row does not exist, or it has no entry for this character, the machine has entered the dead state, so the answer isFalseand we stop. - Otherwise move to
row[ch].
If the loop finishes without rejection, the answer is whether the final state is in the accepting set.
Why it is correct
After reading a prefix of s, the variable state is exactly the state the machine would be in after that prefix, because each step applies the transition function once. The machine is deterministic, so there is only one possible run per string.
- Dead state: it loops to itself forever and is never accepting. Any string that reaches it is rejected, so stopping early gives the same answer as reading the rest.
- Invalid characters: the machine only recognizes strings over
{a, b}, so any other character means rejection regardless of the current state. - Empty string: the loop body never runs, so
statestaysstart_stateand the result is simply whether the start state is accepting. - Missing rows: using
.getavoids aKeyErrorfor states that only appear as targets.
Complexity
- Preprocessing: O(|accept_states|) time and space for the set.
- Each query: O(len(s)) time with O(1) expected dictionary lookups per character, and O(1) auxiliary space.
- Overall: O(|accept_states| + sum of len(s)) time.
Reference solution
from typing import Dict, List
def run_automaton_queries(states: List[str],
transitions: Dict[str, Dict[str, str]],
start_state: str,
accept_states: List[str],
operations: List[str],
arguments: List[List[str]]) -> List[bool]:
accepted = set(accept_states)
results = []
for operation, args in zip(operations, arguments):
if operation != "accepts":
raise ValueError("Unsupported operation")
s = args[0]
state = start_state
valid = True
for ch in s:
if ch not in ("a", "b"):
valid = False
break
row = transitions.get(state)
if row is None or ch not in row:
valid = False
break
state = row[ch]
results.append(valid and state in accepted)
return results