---
id: wiki-2026-0508-brute-force
title: Brute-force
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [Exhaustive-Search, Naive-Algorithm]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
verification_status: applied
tags: [algorithm, search, baseline]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
  language: python
  framework: stdlib
---

# Brute-force

## 매 한 줄
> **"매 모든 후보를 매 enumerate해서 매 검사 — 매 단순함이 매 최대 무기"**. 매 algorithmic paradigm으로서 매 baseline + correctness oracle. 매 2026 ML/AI에서도 매 grid search, 매 fuzzing, 매 password cracking, 매 small-n CSP 에서 매 still alive — 매 GPU + parallelism으로 매 brute force가 매 더 viable.

## 매 핵심

### 매 핵심 idea
- 매 search space 전체를 매 systematic enumerate.
- 매 correctness가 매 trivially provable.
- 매 complexity는 매 보통 exponential — 매 small n only.

### 매 응용
1. String matching (naive: $O(nm)$ vs KMP $O(n+m)$).
2. Cryptanalysis: brute-force key search (e.g., 56-bit DES → cracked 1998).
3. Hyperparameter grid search (small grid).
4. Test oracle (fast brute-force vs optimized — fuzz to verify).
5. Combinatorial: TSP, SAT, knapsack — 매 small n.
6. Fuzzing: AFL/libFuzzer 매 brute random + coverage feedback.

## 💻 패턴

### Naive substring search
```python
def find_naive(text, pat):
    n, m = len(text), len(pat)
    for i in range(n - m + 1):
        if text[i:i+m] == pat:
            return i
    return -1
# O(n*m) — fine for short pattern; KMP/Boyer-Moore better large m
```

### Subset enumeration
```python
from itertools import combinations
def best_subset(items, score_fn):
    best = (None, float('-inf'))
    for r in range(len(items)+1):
        for combo in combinations(items, r):
            s = score_fn(combo)
            if s > best[1]: best = (combo, s)
    return best
# 2^n subsets — only for n <= 20
```

### Permutation TSP (exact for n<=10)
```python
from itertools import permutations
def tsp_brute(dist, start=0):
    n = len(dist)
    best = float('inf'); best_path = None
    for perm in permutations(range(1, n)):
        path = (start,) + perm + (start,)
        cost = sum(dist[path[i]][path[i+1]] for i in range(n))
        if cost < best: best, best_path = cost, path
    return best, best_path
```

### Brute force as test oracle
```python
def fast_solve(input_): ...    # production
def brute_solve(input_): ...   # obvious O(n^k)

def test_with_fuzz():
    import random
    for _ in range(10_000):
        x = random_input()
        assert fast_solve(x) == brute_solve(x), x
```

### Grid hyperparameter search
```python
import itertools
def grid_search(model_fn, param_grid, X, y):
    best = (None, float('-inf'))
    keys = list(param_grid)
    for vals in itertools.product(*[param_grid[k] for k in keys]):
        params = dict(zip(keys, vals))
        score = cv_score(model_fn(**params), X, y)
        if score > best[1]: best = (params, score)
    return best
# Use Optuna/random search for >5 dims
```

### Pruning + brute (branch-and-bound hybrid)
```python
def knapsack_bnb(weights, values, cap):
    best = [0]
    def rec(i, w, v):
        if w > cap: return
        if i == len(weights):
            best[0] = max(best[0], v); return
        # upper bound (LP relax) — prune if can't beat best
        rec(i+1, w + weights[i], v + values[i])
        rec(i+1, w, v)
    rec(0, 0, 0)
    return best[0]
```

## 매 결정 기준
| n size | Brute viable? |
|---|---|
| $n \le 10$ | $O(n!)$ OK |
| $n \le 25$ | $O(2^n)$ OK |
| $n \le 50$ | $O(2^{n/2})$ meet-in-the-middle |
| $n > 50$ | DP / heuristic / approximation |

**기본값**: 매 첫 implementation은 매 brute. 매 그것이 매 너무 slow일 때만 매 optimize. 매 brute는 매 reference oracle로 매 keep.

## 🔗 Graph
- 부모: [[Algorithm-Complexity-Big-O]]
- 변형: [[Greedy-Algorithms]] (heuristic) · [[Dynamic-Programming]] (memoize) · Branch-and-Bound
- 응용: Cryptanalysis · [[Combinatorial-Optimization]]
- Adjacent: [[Bubble-Sort]] · [[BFS vs DFS]]

## 🤖 LLM 활용
**언제**: 매 first implementation, 매 correctness oracle, 매 small n problem.
**언제 X**: 매 n>50, 매 production hot path — 매 better algorithm 필수.

## ❌ 안티패턴
- **Brute in production hot loop**: 매 $O(n^2)$ when $O(n \log n)$ trivial.
- **Throwing away brute baseline**: 매 optimized version에 매 bug — 매 oracle 없음.
- **Brute force without bound**: 매 무한 loop — 매 max iterations / timeout 필수.

## 🧪 검증 / 중복
- Verified (CLRS Ch.31, Skiena Algorithm Design Manual).
- 신뢰도 A.

## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — brute paradigm + oracle pattern |
