3.7.1 · HinglishAlgorithm Paradigms

Brute force — exhaustive search, when acceptable

1,989 words9 min readRead in English

3.7.1 · Coding › Algorithm Paradigms


WHAT is brute force?

Do ingredients:

  1. 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).
  2. 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).


Figure — Brute force — exhaustive search, when acceptable

WHEN is brute force acceptable?

Brute force accept karo jab koi bhi yeh conditions hold karti ho:

  1. 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).
  2. Yeh ek one-off hai / performance-critical nahi hai. Run-once scripts, config-time computation.
  3. Tumhe ek correct reference chahiye optimized solution ko test karne ke liye (differential testing).
  4. 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 best
  • 1 << n masks kyun? Ek bitmask mask se 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?
Solution space mein har candidate enumerate karo aur har ek ko test karo; koi shortcut/insight use nahi hota. Correct hai agar enumeration complete ho aur verifier correct ho.
Brute force guaranteed correct kyun hai?
Agar enumeration koi candidate miss nahi karta, toh sach mein answer unhi mein se ek hoga jo check kiye gaye.
Ek n-element set ke subsets ki sankhya aur kyun?
— har element independently andar ya bahar hai (2 choices, n baar).
n items ke permutations ki sankhya aur kyun?
— slot 1 ke liye choices, slot 2 ke liye , … 1 tak.
n items se unordered pairs ki sankhya?
.
Brute force ki general time cost?
(#candidates) × (ek ko verify karne ki cost).
Compare karne ke liye rough operations-per-second budget?
~ (se ) simple ops/sec.
Agar constraint hai, toh kaunsa brute force OK hai?
Subset enumeration kyunki .
Agar constraint hai, toh kaunsa brute force OK hai?
Permutation enumeration .
Bitmasks se saare subsets kaise enumerate karte hain?
mask ko 0 se tak loop karo; bit set ⇔ item included.
Brute force kab use NAHI karna chahiye?
Jab search-space × verify cost ≫ ho aur exploitable structure (sorting, hashing, DP, greedy) exist kare.
Pairs ke liye common enumeration bug aur fix?
Double counting/self-pairs; fix: inner loop ko i+1 se start karo.
Optimize karne ke baad bhi brute-force version kyun rakhna chahiye?
Fast algorithm ki differential/stress testing ke liye ek correct reference ke roop mein.

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

Concept Map

needs

needs

complete enumeration gives

correct predicate gives

used to test

serves as

cost is

equals candidates times verify

counted by

subsets 2^n, perms n!

forces

else use

Brute Force / Exhaustive Search

Enumeration - list every candidate

Verification - test each candidate

Always correct

Baseline for comparison

Time cost T

Combinatorial explosion

Search space sizes

Acceptable when small input

Smarter paradigms