Skip to main content
ProductsDesktop toolsTASTECADDrawing reviewTASTEFILESFile managementTASTEFTPFile transferTASTESSHRemote workspaceTASTEZIPCompression and extractionTASTEWINMFile managementDeveloper toolsTASTECODERust integrated development environmentTASTESTUDIOIntegrated development and test environmentTASTEETLData integration (ETL)ServersTASTEREMOTERemote desktop serverTASTEGEOGeospatial serverTASTEMAILMail workspaceInvestingTASTESTOCKStock auto-trading desktop appGet startedDownloadsDocumentationBuyAll products
Marketplace
News
TechNewsToday's dev newsDeveloper docsProgramming languagesRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWeb front-end frameworksNext.jsReactVue.js · NuxtSvelteKitAngularServer frameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressApp & desktop frameworksTauriFlutterReact NativeElectronAlgorithmsAlgorithm basicsCore algorithmsAdvanced algorithmsPractical algorithms
CommunityProjectsDevelopment logsPromptsAI tool issuesShowcaseCommunity guide
Work with usTech transferWebsite buildDesktop app buildRelease and payment pipelineSales partnerContact
ServicesRemote desktopCustom installer packages
TASTEDEV
Products

Desktop tools

TASTECADComplex drawings, opened with easeTASTEFILESJust the files you need, as fast as possibleTASTEFTPThe tidiest path for your filesTASTESSHA stronger link between you and your serversTASTEZIPPack faster, unpack saferTASTEWINMA keyboard-first file manager with two panes

Developer tools

TASTECODEEdit, build, debug and test Rust apps in one windowTASTESTUDIOFrom editing to remote tests and approved AI fixesTASTEETLMove data while you watch the values

Servers

TASTEREMOTEA remote desktop you run on your own serverTASTEGEORebuilding a GeoServer-compatible geospatial server in RustTASTEMAILTake back control of your email

Investing

TASTESTOCKStock auto-trading that follows the rules you set: when, and what

Get started

DownloadsLatest builds of every productDocsHow to use each productBuySubscriptions and perpetual licencesAll productsEvery product at a glance
All products
MarketplaceNews
Tech

News

Today's dev newsOfficial announcements on languages, frameworks, GitHub and AIDeveloper docsGuides to languages, frameworks and algorithms

Programming languages

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Web front-end frameworksNext.jsReactVue.js · NuxtSvelteKitAngular
Server frameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
App & desktop frameworksTauriFlutterReact NativeElectron

Algorithms

Algorithm basicsComplexity analysis · Sorting · Searching · Basic data structures · Trees and heapsCore algorithmsGraph traversal · Shortest paths & minimum spanning trees · Dynamic programming · Greedy algorithms · Divide and conquer · BacktrackingAdvanced algorithmsString algorithms · Math and number theory · Bit manipulation · Segment trees · Union-findPractical algorithmsCoding interview strategy · LRU cache · Rate limiting · Consistent hashing
All development docs
Community
ProjectsDiscover builders and their workDevelopment logsDecisions and lessons learnedPromptsReusable instructionsAI tool issuesProblems and workarounds for Claude, Codex, GeminiShowcaseFinished resultsCommunity guideHow we build in the open
Work with us
Tech transferNative apps in Rust and eguiWebsite build10 languages, accounts, docs and downloadsDesktop app buildRust and egui, no WebViewRelease and payment pipelineSigning, MSI, deb, rpm, AppImage, hashesSales partnerRecommend us and earn 30%ContactBuilds, partnerships and investment
Services
Remote desktopReach your computer from a browserCustom installer packagesOnly the features you need, settings preloaded
Buy
EN
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Log in
Log in
TASTEDEV

From small tools to better development.

support@tastedev.netSupport TASTEDEV
ProductsProduct lineupBuyDocsDownloadsMarketplaceSupport
CommunityProjectsDevelopment logsPromptsAI tool issuesShowcase
PoliciesAbout usPrivacy policyTerms of serviceSubscription termsRefund policyCommunity guidelines
AccountLog inSign up
Visitors
Today
Yesterday
Total views
Company
GXSOFT
Representative
CHOI YOUNG GU
Business registration number
853-44-00368
Address
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Phone
+82-10-4404-1523
Email
whitecalvin@tastedev.net
Privacy officer
CHOI YOUNG GU

© 2026 TASTEDEVProduct information is based on verified development sources.Released · improving

Backtracking docs
Backtracking
Backtracking ConceptsHow It WorksImplementationComplexityPractice ProblemsBacktracking in the Real World
Discussions

Backtracking guide · 6/6

Backtracking in the Real World

Backtracking is more than an interview technique. It runs inside tools you use every day: regular expression engines, SAT solvers, constraint programming libraries, and logic programming languages. This chapter covers where it shows up, the pitfalls you meet in production code, and where to read more.

Where backtracking runs

  • Regular expression engines: Python re, Java java.util.regex, JavaScript, and PCRE try each alternative of a pattern (|, *, +) in turn and back up on failure. That is what makes features like backreferences possible, and also why some inputs take exponential time.
  • SAT solvers and DPLL: the DPLL algorithm assigns Boolean variables one at a time and backtracks on a contradiction. It is the foundation of modern CDCL SAT solvers used in hardware verification and package dependency resolution.
  • Constraint programming: solvers such as Google OR-Tools CP-SAT model timetables, shift rosters, and production schedules as variables and constraints, and use constraint propagation to prune branches before exploring them.
  • Logic programming: in Prolog, trying rules from the top and falling back to the next rule on failure is the execution model itself.
  • Puzzles and games: Sudoku, crossword, and exact cover solvers (Knuth's Dancing Links) are classic examples.
  • Parsers: PEG parsers and some recursive descent parsers try grammar alternatives in order and rewind the input position when one fails.

Pitfall 1: catastrophic backtracking in regexes

A pattern like (a+)+$ can split a run of a characters in exponentially many ways, so on input whose ending does not match, the engine tries every split. Applying such a pattern to user-supplied text opens the door to a denial-of-service attack (ReDoS).

import re
import time

pattern = re.compile(r"(a+)+$")
for n in (16, 18, 20, 22):
    text = "a" * n + "!"
    start = time.perf_counter()
    pattern.match(text)
    print(n, f"{time.perf_counter() - start:.3f}s")
# every extra character roughly doubles the time

Fixes include removing the nested repetition (a+$ matches the same strings here), limiting input length, or switching to an engine with linear-time guarantees such as RE2.

Pitfall 2: recursion depth and copying

Python's default recursion limit is around 1000, so searches thousands of levels deep raise RecursionError. You can raise the limit with sys.setrecursionlimit, but that risks overflowing the C stack; for deep searches an explicit stack is safer.

def subsets_iterative(nums):
    result = []
    stack = [(0, [])]                 # (next index, partial solution)
    while stack:
        i, path = stack.pop()
        if i == len(nums):
            result.append(path)
            continue
        stack.append((i + 1, path))               # branch that skips nums[i]
        stack.append((i + 1, path + [nums[i]]))   # branch that takes it
    return result

print(subsets_iterative([1, 2]))  # [[1, 2], [1], [2], []]

An explicit stack copies state instead of undoing it, so it uses more memory. When the depth is modest, the recursive version is simpler and faster.

Pitfall 3: reinventing the standard library

For plain permutations, combinations, or Cartesian products, the standard library is faster and already tested. Write your own backtracking when you need to prune along the way.

from itertools import combinations, permutations, product

print(list(combinations("ABC", 2)))   # [('A', 'B'), ('A', 'C'), ('B', 'C')]
print(len(list(permutations(range(4)))))  # 24
print(list(product([0, 1], repeat=2)))     # [(0, 0), (0, 1), (1, 0), (1, 1)]

Other things to watch

  • A missing or misordered undo leaks state into other branches, and the results go quietly wrong. Always write choose and unchoose as a pair.
  • A pruning rule that is too aggressive cuts off branches that contain real solutions. For small inputs, keep a test that compares against brute force.
  • If input sizes can grow, estimate the worst-case search size up front and add a time or node budget so the service never hangs.
  • Real scheduling problems with complex constraints are usually better handed to a solver such as CP-SAT than implemented by hand.

Summary

  • Backtracking is the core engine of practical tools: regex engines, SAT solvers, constraint programming, and Prolog.
  • Catastrophic backtracking, recursion depth, and forgotten undo steps are the most common production problems.
  • Leave standard enumerations to the library and hard constraint problems to dedicated solvers; implement backtracking yourself where custom pruning pays off.

Further reading

  • Backtracking (Wikipedia)
  • Eight queens puzzle (Wikipedia)
  • Sudoku solving algorithms (Wikipedia)
  • Constraint satisfaction problem (Wikipedia)
  • itertools (Python documentation)
  • Constraint Optimization (Google OR-Tools)
  • Regular expression Denial of Service - ReDoS (OWASP)
Questions about this chapter?
Previous chapterPractice Problems

0 comments

Top commentsNewest first

Sign in · Sign in to leave a comment.