{
  "id": "finite-state-machine",
  "title": "Finite-State Machine",
  "lang": "en",
  "source_lang": "en",
  "summary": "A finite-state machine models computation or control using finitely many states and rules for changing state in response to inputs.",
  "category": "computer-science",
  "subcategory": "algorithms-theory",
  "type": "concept",
  "aliases": [
    "FSM",
    "finite-state automaton",
    "finite automaton",
    "finite-state model"
  ],
  "generated_at": "2026-11-03",
  "model": "pro/gpt-6.1-sol",
  "url": "https://aiwiki.page/en/finite-state-machine/",
  "translations": {
    "zh-Hans": {
      "url": "https://aiwiki.page/zh/finite-state-machine/",
      "json": "https://aiwiki.page/zh/finite-state-machine.json"
    }
  },
  "sections": [
    {
      "heading": "",
      "text": "A finite-state machine (FSM) is a mathematical model of a system whose behavior is determined by a current state, an input, and rules specifying how the state changes. Its defining restriction is that the set of possible states is finite. A state records precisely the information about the past that the model needs to determine its subsequent behavior; the complete history of previous inputs need not be retained.\n\nFinite-state machines are fundamental to computer science, digital electronics, and control-oriented software engineering. They describe devices such as traffic-light controllers, recognize patterns in text, specify communication protocols, and provide models for checking whether systems satisfy formal requirements. In theoretical work, a finite automaton commonly accepts or rejects input strings. In engineering, an FSM often runs continuously and produces outputs or actions instead of a final acceptance decision.\n\nThe model's simplicity supports efficient execution and rigorous mathematical analysis, but also establishes its limits: a fixed finite-state machine cannot remember arbitrarily much information. Understanding finite-state machines therefore involves both their practical construction and their relationship to more powerful computational models."
    },
    {
      "heading": "States, transitions, and mathematical definition",
      "text": "A deterministic finite automaton, or DFA, is conventionally defined as a five-tuple\n\n\\[M=(Q,\\Sigma,\\delta,q_0,F),\\]\n\nwhere \\(Q\\) is a finite, nonempty set of states; \\(\\Sigma\\) is a finite input alphabet; \\(\\delta:Q\\times\\Sigma\\to Q\\) is the transition function; \\(q_0\\in Q\\) is the initial state; and \\(F\\subseteq Q\\) is the set of accepting states. An input is a finite string over \\(\\Sigma\\). Starting in \\(q_0\\), the automaton processes the string one symbol at a time, updating its state according to \\(\\delta\\). It accepts exactly when the state reached after the entire string has been read belongs to \\(F\\).\n\nThe transition function extends from individual symbols to complete strings. Writing \\(\\varepsilon\\) for the empty string, the extended function satisfies\n\n\\[\\delta^*(q,\\varepsilon)=q,\\qquad \\delta^*(q,wa)=\\delta(\\delta^*(q,w),a).\\]\n\nThe language recognized by the automaton is\n\n\\[L(M)=\\{w\\in\\Sigma^*:\\delta^*(q_0,w)\\in F\\}.\\]\n\nHere a formal language is simply a set of strings. Acceptance concerns membership in that set, not whether a physical device stops operating. A practical controller may have no meaningful accepting states at all.\n\nA two-state example recognizes binary strings containing an even number of \\(1\\) symbols. Its states are \\(E\\) and \\(O\\), representing even and odd parity. Reading \\(0\\) leaves the state unchanged; reading \\(1\\) switches states. The initial and accepting state is \\(E\\), so the empty string is accepted. After any prefix, the current state records its parity without recording its length or individual symbols. Strings such as \\(11\\) and \\(101\\) leave the machine in the same state because their differences are irrelevant to future parity decisions.\n\nThis illustrates the essential interpretation of state as sufficient memory. Two input histories may share a state when the machine need not distinguish them in any future computation. A machine with \\(n\\) states requires at least \\(\\lceil\\log_2 n\\rceil\\) binary storage positions to encode its state, although an implementation may use more.\n\nIn the standard definition, \\(\\delta\\) is total: every state–symbol pair has a successor. Diagrams sometimes omit invalid or uninteresting transitions. Such a partial description can be completed by adding a nonaccepting sink state that loops on every symbol. Whether a missing transition means rejection, an error, or unspecified behavior must be established explicitly."
    },
    {
      "heading": "Representations, outputs, and execution semantics",
      "text": "A finite-state machine can be represented as a table, a mathematical function, or a directed graph. In a state diagram, vertices represent states and labeled directed edges represent transitions. An incoming arrow without a source commonly marks the initial state, while a double circle marks an accepting state. A transition table expresses the same information by listing the next state for every current-state and input combination. Diagrams emphasize structure; tables are often easier to inspect for completeness and translate into executable code.\n\nMany applications require outputs rather than string acceptance. A Mealy machine associates each output with the current state and input:\n\n\\[\\lambda:Q\\times\\Sigma\\to\\Gamma,\\]\n\nwhere \\(\\Gamma\\) is an output alphabet. A Moore machine associates each output with a state:\n\n\\[\\lambda:Q\\to\\Gamma.\\]\n\nFor example, a vending controller may use its state to represent accumulated credit. A Mealy-style output can issue a dispense command on the transition caused by the final coin, whereas a Moore-style design can enter a dispensing state whose output activates the mechanism.\n\nThe distinction affects timing and representation rather than the basic availability of finite-state control. Under suitable conventions, either kind can be transformed into the other, although a conversion can require additional states. Care is necessary when comparing output sequences: a Moore machine has an output associated with its initial state, and different conventions align this initial output differently with the first input. Consequently, an equivalence claim must specify whether outputs are observed before or after each transition.\n\nExecution semantics are equally important. In a synchronous hardware model, inputs are sampled and state registers update at specified clock edges. In event-driven software, a transition may occur when an event is removed from a queue. A label such as “timeout” may therefore represent an external timer event rather than time passing inside the abstract machine. Entry actions, exit actions, transition actions, and the order in which they execute are extensions that require precise definitions.\n\nA practical example is a door controller with states closed, opening, open, and closing. An obstruction event while closing may cause a transition to opening. The model must specify what happens if an obstruction and a close request occur together, whether events are processed sequentially, and whether an opening action can be interrupted. The diagram alone does not settle these questions.\n\nThus, a useful FSM specification includes not only named states and arrows but also input conventions, initialization, output timing, and the treatment of exceptional events. Different tools can assign different semantics to superficially similar diagrams."
    },
    {
      "heading": "Nondeterminism and regular-language recognition",
      "text": "A nondeterministic finite automaton (NFA) allows several possible successor states for a state–symbol pair. Its transition function has the form\n\n\\[\\delta:Q\\times\\Sigma\\to\\mathcal P(Q),\\]\n\nwhere \\(\\mathcal P(Q)\\) is the set of subsets of \\(Q\\). A string is accepted if at least one complete path labeled by that string ends in an accepting state. Nondeterminism is not randomness: no probability is assigned to a branch, and acceptance does not depend on selecting a lucky path during one execution.\n\nAn epsilon-NFA additionally permits transitions labeled \\(\\varepsilon\\), which change state without consuming an input symbol. These transitions make it convenient to combine smaller machines. For example, a machine recognizing the union of two languages can begin with epsilon-transitions into their respective start states. The epsilon-closure of a set of states consists of every state reachable from it using zero or more epsilon-transitions.\n\nEvery NFA has an equivalent DFA. The subset construction makes each DFA state represent a set of NFA states that could be active after the input read so far. On an input symbol, it combines all corresponding NFA successors; for epsilon-NFAs, it also takes epsilon-closures. A subset is accepting if it contains at least one accepting NFA state. An NFA with \\(n\\) states yields at most \\(2^n\\) subsets, although many may be unreachable. Some language families genuinely require exponentially more states in deterministic form, so the potential increase is not merely an artifact of an inefficient construction.\n\nThe languages recognized by finite automata are precisely the regular languages. They are also precisely the languages described by formal regular expressions built using union, concatenation, and repetition. This equivalence provides a bridge between declarative pattern notation and executable machines. Thompson's construction turns a regular expression into an epsilon-NFA with size linear in the expression's length; subset construction can then produce a DFA.\n\nFor a fixed DFA, membership testing takes time linear in the input length and uses constant auxiliary storage for the current state. Direct NFA simulation instead tracks a set of active states, avoiding the need to construct every DFA subset in advance. These alternatives trade compilation effort and storage against execution cost.\n\nRegular-expression software does not always implement only regular-language operations. Backreferences, available in some engines, can require later text to match an arbitrarily long captured substring and therefore exceed finite-automaton expressiveness. Conversely, a backtracking implementation can take exponential time on certain patterns even when the pattern itself describes a regular language. Language expressiveness and matching algorithm are separate issues."
    },
    {
      "heading": "State equivalence, minimization, and decision procedures",
      "text": "Two states of a deterministic acceptor are equivalent when no future input string can distinguish them by acceptance. Formally, states \\(p\\) and \\(q\\) are equivalent if\n\n\\[\\forall w\\in\\Sigma^*,\\quad \\delta^*(p,w)\\in F \\iff \\delta^*(q,w)\\in F.\\]\n\nEquivalent states may be merged without changing the recognized language. States unreachable from the initial state can also be removed. A minimal complete DFA is unique up to renaming its states, giving regular languages a canonical finite-state representation under this convention.\n\nThe Myhill–Nerode theorem characterizes the same idea directly in terms of input histories. Define\n\n\\[x\\equiv_L y \\quad\\Longleftrightarrow\\quad \\forall z\\in\\Sigma^*,\\; xz\\in L\\iff yz\\in L.\\]\n\nThe strings \\(x\\) and \\(y\\) are equivalent when every possible continuation treats them identically. A language is regular exactly when this relation has finitely many equivalence classes. Those classes correspond to the states of its minimal DFA. This gives a precise interpretation of a state's memory: it identifies the future-relevant equivalence class of the input already consumed.\n\nMinimization algorithms discover such equivalences through partition refinement. Initially, accepting and nonaccepting states are separated. A block is split whenever some input symbol sends its members into different existing blocks. Refinement continues until all states in each block have matching transition behavior with respect to the partition. John Hopcroft's 1971 algorithm performs this process efficiently; a standard bound is \\(O(kn\\log n)\\) for \\(n\\) states and an alphabet of size \\(k\\), given suitable representations. Simpler table-filling methods are useful for small examples and instruction.\n\nFinite automata also support effective decision procedures. Emptiness reduces to asking whether an accepting state is reachable. Equivalence of two DFAs can be checked using a product machine whose states are pairs of component states and whose accepting pairs are those where exactly one component accepts. The original machines are equivalent precisely when this product recognizes the empty language. Complementation swaps accepting and nonaccepting states in a complete DFA; intersection uses a product construction with both components required to accept.\n\nMinimization must preserve the behavior that actually matters. Two controller states with identical accepted input suffixes may still differ in their outputs, timing obligations, or permitted actions. Transducer minimization therefore uses an equivalence that accounts for output behavior. Likewise, minimizing an incompletely specified controller is not the same problem as minimizing a complete language acceptor: unspecified behavior may allow implementation choices rather than mandate rejection."
    },
    {
      "heading": "Expressive limits and extended models",
      "text": "A fixed finite-state machine cannot distinguish indefinitely many quantities or histories. It can remember a count modulo a fixed integer, but it cannot store an arbitrary exact count. For example, it can recognize binary strings with the number of \\(1\\) symbols divisible by three using three states. It cannot recognize\n\n\\[L=\\{0^n1^n:n\\geq 0\\},\\]\n\nbecause doing so requires matching an unbounded number of initial zeroes with an equal number of subsequent ones.\n\nOne proof uses distinguishable prefixes. If \\(i<j\\), the prefixes \\(0^i\\) and \\(0^j\\) must lead to different states: appending \\(1^i\\) produces a member of \\(L\\) from the former but not the latter. Infinitely many distinguishable prefixes would require infinitely many states. The pumping lemma provides another standard necessary condition for regularity, based on the repeated state that must occur along a sufficiently long accepting path. Satisfying that condition alone, however, is not a general proof that a language is regular.\n\nAdding unbounded storage changes the model's expressive power. A pushdown automaton has a stack and can recognize languages such as balanced parentheses, which require tracking unbounded nesting. A Turing machine has a read–write tape and supports general computation. The distinction concerns the resources available within a uniform model, not whether an FSM can be expanded to handle a particular fixed maximum. Balanced parentheses up to a predetermined nesting depth can be recognized by a sufficiently large finite automaton.\n\nEngineering notations frequently augment state diagrams with variables, guards, and actions. In an extended finite-state machine, a transition might be enabled only when a counter is below a limit. If every variable has a finite range, the model can be expanded into an ordinary FSM by including all variable valuations in the state. This expansion may be enormous. Unbounded integers, stacks, or queues can instead produce a genuinely infinite-state system despite a diagram containing only a few control locations.\n\nOther extensions address different needs. A timed automaton combines finitely many locations with real-valued clocks and clock constraints; standard timed-automata theory supports finite abstractions for important decision problems. A Markov chain assigns probabilities to transitions, while a Büchi automaton recognizes infinite input sequences using an acceptance condition based on infinitely recurring accepting states.\n\nThese models retain finite-state structure without sharing all the properties of finite automata on finite strings. Determinization, equivalence, and decidability must therefore be established separately for the particular extension."
    },
    {
      "heading": "Digital hardware and controller implementation",
      "text": "In digital electronics, an FSM is commonly implemented as a synchronous sequential circuit consisting of a state register, next-state logic, and output logic. The register stores the current state. Combinational circuits compute the next state from the current state and sampled inputs, and a clock edge loads that value into the register. Outputs are derived from the state alone or from the state and inputs, corresponding approximately to Moore and Mealy organizations. Logic gates and storage elements turn the abstract transition function into physical behavior.\n\nState encoding is a major implementation choice. Binary encoding uses approximately \\(\\lceil\\log_2 n\\rceil\\) state bits for \\(n\\) states, minimizing the number of storage bits but potentially requiring more complex decoding. One-hot encoding assigns one storage bit to each state, with exactly one asserted during normal operation. It uses more registers but can simplify transition and output logic. The preferred choice depends on the target technology, timing constraints, routing, and synthesis results; the fewest abstract states do not necessarily produce the fastest or smallest circuit.\n\nA controller for a memory transaction might use states idle, request, wait, and complete. The request state asserts a command, wait persists until an acknowledgment arrives, and complete presents the result before returning to idle. Such a model separates control sequencing from the datapath that holds addresses and data. In a microprocessor, similar finite-state control can sequence instruction execution, coordinate pipelines, or manage cache operations. The complete processor is far more complex than a small illustrative controller, but individual control blocks remain natural FSM applications.\n\nPhysical timing introduces issues absent from the abstract model. Mealy outputs can respond combinationally to changing inputs and may glitch as signals propagate. Moore outputs can also glitch if decoded from several state bits that do not switch simultaneously; registering outputs is a distinct design decision. Asynchronous external inputs may violate a register's setup or hold requirements and cause metastability. Synchronization circuitry reduces the probability of its propagation but is not captured by simply drawing another logical transition.\n\nReset behavior and unused state encodings must also be specified. A three-state binary-encoded controller has an additional encoding that may arise through a fault or an invalid initialization. Designers may define recovery to a known state, signal an error, or apply other fault-handling measures. Safety claims must account for the actual implementation and fault assumptions rather than only the intended transition graph.\n\nHardware-description languages express these machines through registers and conditional next-state logic. Synthesis tools can recognize FSM structures and transform their encodings, making preservation of observable behavior more important than preservation of the original state names."
    },
    {
      "heading": "Software, text processing, and communication protocols",
      "text": "In software, finite-state machines organize behavior that depends on the sequence of events rather than on an isolated request. A straightforward implementation stores the current state in an enumeration and uses conditional branches to select a transition. A table-driven implementation indexes a transition table by state and input. Other designs represent state-specific behavior through objects or functions. These are implementation techniques for the same underlying model, provided their transition and action semantics agree.\n\nLexical analysis in a compiler is a classic application. A scanner groups characters into tokens such as identifiers, numbers, and operators. Regular expressions describe token patterns, and finite automata implement their recognition. A scanner generally needs more than a bare yes-or-no acceptor: it records the last accepting position to implement longest-match rules and uses priorities when multiple token classes match the same text. Parsing unbounded nesting typically requires additional machinery, so the scanner–parser distinction reflects a genuine difference in memory requirements.\n\nCommunication protocols use states to distinguish valid messages and operations at different stages. The Transmission Control Protocol, for example, specifies states including LISTEN, SYN-SENT, ESTABLISHED, and TIME-WAIT. Receiving a segment has different consequences depending on the connection state. A complete implementation also maintains sequence numbers, buffers, timers, and other variables, so its compact state diagram describes the control structure rather than every possible concrete configuration.\n\nSimilar patterns appear in user interfaces, transaction workflows, and device drivers. An upload process may move through pending, transferring, completed, canceled, and failed states. Making these states explicit helps prevent actions such as completing an already canceled operation or issuing a second completion notification. The abstraction is useful only if transitions correspond to the actual lifecycle: informal status labels that do not determine permitted behavior may conceal rather than resolve ambiguity.\n\nInteraction with concurrency requires particular care. Two events can race to update a state, and a transition that appears atomic in a diagram may consist of several interruptible instructions. Locks, transactional updates, or serialized event processing can make implementation behavior correspond to the abstract transition. External effects complicate this further: changing a database status and sending a message are not automatically one indivisible operation.\n\nHierarchical descriptions reduce duplication when many states share reactions. David Harel's statecharts, introduced in 1987, support nested states and orthogonal regions. With finitely many bounded components, these structures can be flattened into a finite-state model, but the result may contain a large product of substates. Hierarchy therefore improves specification and comprehension without eliminating the underlying combinations of behavior."
    },
    {
      "heading": "Verification, testing, and state-space growth",
      "text": "A finite-state description makes behavioral questions accessible to systematic analysis. Formal verification can establish properties of all executions allowed by a model rather than only executions observed during tests. A safety property states that something undesirable never happens, such as a controller simultaneously activating incompatible actuators. A liveness property states that something desirable eventually happens, such as every accepted request eventually receiving a response. Liveness usually depends on environmental or scheduling assumptions that must be made explicit.\n\nModel checking explores a transition system against a formal specification. For a simple safety property, the problem may reduce to reachability: is any forbidden state reachable from the initial state? A search can return a counterexample path that shows the sequence of events leading to failure. Breadth-first search finds a shortest counterexample in an unweighted explicit state graph, although storing the explored graph can require substantial memory.\n\nSpecifications in temporal logic express requirements about behavior over time. Linear temporal logic can state that a request is always eventually followed by a grant; branching-time formalisms can distinguish properties involving all possible futures from those involving some possible future. Infinite behaviors matter because a finite graph may support executions that repeat cycles forever. Checking progress therefore requires more than determining which individual states can be reached.\n\nThe main practical obstacle is state-space explosion. If \\(k\\) components each have \\(m\\) local states, their combined system can have \\(m^k\\) state combinations before accounting for data variables, queues, and timers. Several techniques address this. Symbolic methods represent sets of states compactly, for example with binary decision diagrams. Partial-order reduction avoids exploring some redundant interleavings of independent actions. Abstraction merges concrete configurations while retaining properties relevant to the question. Bounded model checking encodes executions up to a chosen depth as a Boolean satisfiability problem, or a related constraint problem; failure to find a counterexample within that bound is not automatically an unbounded proof.\n\nFSM-based testing derives test sequences from states and transitions. State coverage and transition coverage measure whether selected model elements have been exercised, but neither guarantees that an implementation conforms to the model. Distinguishing sequences and conformance-testing methods seek inputs that expose incorrect state or output behavior. Their guarantees depend on assumptions, such as determinism and a bound on implementation states.\n\nVerification results apply to the stated model and assumptions. An accurate control graph can still omit integer overflow, message loss, reset behavior, or timing faults present in the implementation. Establishing the correspondence between model and system is therefore part of the verification problem itself."
    },
    {
      "heading": "Historical development and scientific significance",
      "text": "Finite-state ideas emerged from several lines of research rather than a single invention. Sequential switching circuits provided a practical setting in which the current outputs depended on stored internal conditions. In 1943, Warren McCulloch and Walter Pitts published a logical model of networks of idealized neurons. Their work connected discrete internal configurations, logical operations, and temporal behavior, helping establish a mathematical language for reasoning about finite networks. Later automata theory developed these connections independently of the biological interpretation.\n\nStephen Cole Kleene's work established the relationship between finite automata and regular expressions, with his major account appearing in 1956 in Automata Studies. The equivalence showed that a language described through algebraic operations on patterns could also be recognized by a finite transition system. This was a foundational link between symbolic descriptions and mechanisms, and it remains central to text-processing tools and compiler construction.\n\nGeorge H. Mealy's 1955 paper on synthesizing sequential circuits and Edward F. Moore's 1956 work on sequential machines developed influential formulations of machines with outputs. Their names became attached to the transition-output and state-output models. Michael O. Rabin and Dana Scott's 1959 paper, Finite Automata and Their Decision Problems, developed nondeterministic automata and important decision-theoretic results. These contributions helped separate questions of machine representation from questions of the languages machines can recognize.\n\nThe field also acquired structural characterizations. John Myhill's work in 1957 and Anil Nerode's in 1958 underlie the equivalence-class characterization of regular languages. That result explains both why minimization is possible and why some tasks cannot be performed with finite memory. Ken Thompson's 1968 work connected regular-expression compilation directly to practical text searching. Hopcroft's efficient minimization algorithm followed in 1971, while statechart and model-checking research in later decades broadened the role of state-based descriptions in engineering.\n\nFinite-state machines also provide a useful contrast with modern machine learning. A hand-specified FSM has explicit discrete states and transitions; a learned model may infer behavior from examples or represent history in continuous-valued vectors. Automata-learning methods can infer finite-state models through observations and queries, and extracted machines can sometimes provide interpretable descriptions of learned or black-box systems. Such a model's fidelity still depends on what behavior was observed and what assumptions were imposed.\n\nThe finite-state viewpoint remains significant because it isolates a precise question: which distinctions among past events must a system retain to behave correctly in the future? In language theory this becomes an equivalence relation on prefixes; in circuit design it becomes stored state bits; in protocol analysis it becomes a graph of permitted interactions. The same abstraction supports exact mathematics while remaining directly implementable."
    }
  ],
  "links": [
    "computer-science",
    "software-engineering",
    "formal-language",
    "directed-graph",
    "mealy-machine",
    "regular-language",
    "algorithm",
    "pumping-lemma",
    "turing-machine",
    "markov-chain",
    "logic-gate",
    "one-hot-encoding",
    "microprocessor",
    "compiler",
    "device-driver",
    "concurrent-computing",
    "formal-verification",
    "model-checking",
    "breadth-first-search",
    "boolean-satisfiability-problem",
    "machine-learning"
  ],
  "sources": [],
  "license": "https://creativecommons.org/licenses/by/4.0/"
}