Brute force — exhaustive search, when acceptable
3.7.1· Coding › Algorithm Paradigms
WHAT is brute force?
Do ingredients:
- Enumeration — ek tarika har candidate ko exactly ek baar list karne ka (e.g. saare subsets, saare permutations, saare pairs, ek range mein saare integers).
- Verification — ek predicate jo check karta hai ki koi candidate answer hai ya nahi.
WHY does it work (and why is it slow)?
Kimat hai time. Cost hai:
Candidates ki sankhya usually combinatorially badhti hai. Chaliye famous waalon ko first principles se derive karte hain.
Toh total time hai e.g. ek subset search ke liye. Yeh tezi se explode hota hai — yahi wajah hai ki humein eventually smarter paradigms chahiye (greedy, DP, divide-and-conquer).

WHEN is brute force acceptable?
Brute force accept karo jab koi bhi yeh conditions hold karti ho:
- Chhota input bound. Agar constraints subsets ke liye () ya permutations ke liye () kehti hain, toh total budget mein fit ho jata hai (roughly simple operations per second).
- Yeh ek one-off hai / performance-critical nahi hai. Run-once scripts, config-time computation.
- Tumhe ek correct reference chahiye optimized solution ko test karne ke liye (differential testing).
- Koi better algorithm known nahi hai (kuch NP-hard problems — tum pruning ke saath brute force karte ho).
Reject karo jab search space tumhara time budget exceed kare aur exploit karne layak structure ho.
| Constraints mein pattern | Likely intended complexity | Brute force OK? |
|---|---|---|
| haan (permutations) | ||
| – | haan (subsets) | |
| borderline | ||
| shayad | ||
| nahi | ||
| / | nahi |
Worked Example 1 — Two-Sum by brute force
Problem: array aur target diya gaya hai, indices dhundho jahan .
def two_sum_brute(a, t):
n = len(a)
for i in range(n): # candidate first index
for j in range(i+1, n): # candidate second index
if a[i] + a[j] == t:
return (i, j)
return None- Nested loop kyun? Candidates unordered pairs hain; saare pairs enumerate karna poori space ko exactly ek baar cover karta hai (hum ko se start karte hain duplicates aur self-pairs se bachne ke liye).
- Correct kyun? Har valid pair koi hoga jahan , aur hum sab ko visit karte hain.
- Cost: . kuch hazaar ke liye acceptable; ke liye hash set use karo ().
Worked Example 2 — Subset sum (max value under a weight cap)
Problem: items ka ek subset chunno jo total value maximize kare jab total weight ho.
def best_subset(weights, values, W):
n = len(weights)
best = 0
for mask in range(1 << n): # all 2^n subsets, encoded as bits
wt = val = 0
for i in range(n):
if mask & (1 << i): # is item i in this subset?
wt += weights[i]
val += values[i]
if wt <= W:
best = max(best, val)
# Why this step? we only update best for FEASIBLE subsets
return best1 << nmasks kyun? Ek bitmaskmaskse tak har subset enumerate karta hai: bit set ⇔ item chosen. Yeh us count ko realise karta hai jo humne derive kiya tha.- Correct kyun? Optimal subset koi na koi subset hai → woh masks mein se ek hai → usse consider kiya jata hai.
- Cost: . ke liye theek hai. Uske baad, DP pe switch karo ().
Worked Example 3 — Cracking a 4-digit PIN
def crack(check): # check(pin) -> True if correct
for pin in range(10000): # 10^4 candidates
s = f"{pin:04d}"
if check(s):
return s- kyun? 10 digits pe length-4 string → candidates. Bahut chhota, isliye brute force instant hai — yahi wajah hai ki chhote PINs weak hote hain.
Recall Feynman: ek 12-saal ke bacche ko explain karo
Socho tumhari ghar ki chaabi kho gayi aur tumhare paas ek bade ring par 200 chaabiyan hain. Brute force bas har ek chaabi ko ek ek karke try karna hai jab tak darwaza na khule. Tum zaroor andar aa jaoge eventually — yeh acchi baat hai. Buri baat yeh hai ki agar bahut saari chaabiyan hain toh bahut time lag sakta hai. Toh brute force tab accha hai jab keyring chhoti ho, aur tab bura idea hai jab woh bahut badi ho — us case mein tum sochna prefer karoge ki kaunsi chaabiyan sahi lag rahi hain (yahi smarter algorithms karte hain).
Flashcards
Brute-force algorithm ko kya define karta hai?
Brute force guaranteed correct kyun hai?
Ek n-element set ke subsets ki sankhya aur kyun?
n items ke permutations ki sankhya aur kyun?
n items se unordered pairs ki sankhya?
Brute force ki general time cost?
Compare karne ke liye rough operations-per-second budget?
Agar constraint hai, toh kaunsa brute force OK hai?
Agar constraint hai, toh kaunsa brute force OK hai?
Bitmasks se saare subsets kaise enumerate karte hain?
Brute force kab use NAHI karna chahiye?
Pairs ke liye common enumeration bug aur fix?
Optimize karne ke baad bhi brute-force version kyun rakhna chahiye?
Connections
- Algorithm Paradigms — brute force baseline paradigm hai
- Time Complexity & Big-O — , , growth kaise estimate karte hain
- Dynamic Programming — exponential subset/sequence brute force ko polynomial DP se replace karta hai
- Greedy Algorithms — exhaustive checking ki jagah ek single myopic choice leta hai
- Backtracking — pruning ke saath brute force; provably-bad branches skip karta hai
- Bitmasking — subsets enumerate karne ki standard technique
- NP-Hard Problems — jahan brute force (pruning ke saath) kabhi kabhi sabse best hota hai jo hum jaante hain