3.7.1 · D4 · HinglishAlgorithm Paradigms

ExercisesBrute force — exhaustive search, when acceptable

2,506 words11 min read↑ Read in English

3.7.1 · D4 · Coding › Algorithm Paradigms › Brute force — exhaustive search, when acceptable

Shuru karne se pehle, yeh mental picture hai jo hum baar baar use karte hain — poora game candidates ke pile ka size count karna hai, phir poochna ki pile itni choti hai ki usse walk-through kiya ja sake.

Figure — Brute force — exhaustive search, when acceptable

Level 1 — Recognition

Goal: ek constraint padho aur search-space size + verdict batao. Koi coding nahi.

Exercise 1.1

Ek problem kehti hai: " items diye hain, har subset consider karo." Kitne subsets hain, aur kya brute force ke andar fit hoga?

Recall Solution 1.1

KYA count karte hain: har subset. KYUN : items mein se har ek independently in ya out hai — yeh choices hain, baar li jaati hain, isliye . ke saath: . Kyunki , brute force theek hai (chaahe har subset par thoda extra cost bhi ho).

Exercise 1.2

Ek problem mein hai aur yeh items ki har ordering (permutation) try karne ko kehti hai. Size? Verdict?

Recall Solution 1.2

KYUN : pehle slot mein choices hain, agle mein (ek item use ho gayi), aur aise neeche tak. Multiply karo: . . Yeh se upar hai. Isliye seedha permutation brute force borderline-to-risky hai — likely bahut slow hoga jab tak verification trivial na ho aur constants bahut chote na hon. Yahaan pruning (backtracking) ya DP prefer karo.

Exercise 1.3

" mein koi bhi do indices dhundho jahan ho." Kaun si enumeration, kya size, verdict?

Recall Solution 1.3

KYA: saare unordered distinct pairs enumerate karo. KYUN : slot 1 chuno ( ways) aur slot 2 ( ways), phir se divide karo kyunki aur same pair hai: . : . Brute force OK.


Level 2 — Application

Goal: enumeration loop / mask likho aur uska cost count karo.

Exercise 2.1

Ek brute force likho jo saare index pairs , , return kare jahan ho. General ke liye exact pair-checks ka number batao.

Recall Solution 2.1
def all_pairs(a, t):
    n = len(a)
    out = []
    for i in range(n):              # first index
        for j in range(i+1, n):     # second index, strictly after i
            if a[i] + a[j] == t:
                out.append((i, j))
    return out

KYUN j ko i+1 se start karo: yeh enforce karta hai, isliye har unordered pair exactly ek baar visit hoti hai — na self-pairs, na duplicates. Checks ka number: inner loop baar chalta hai. Yahi hai jo humne derive kiya. ke liye yeh exactly checks hain.

Exercise 2.2

Bitmasks use karke count karo ki ke kitne subsets ka sum hai. Masks dikhao.

Recall Solution 2.2

KYUN masks: ek number mask se tak ek subset encode karta hai — bit set element chosen hai. Yeh count realise karta hai. Subsets jinका sum hai:

  • → mask , sum
  • → mask , sum
  • → mask , sum
  • → mask , sum

Yeh 4 subsets hain. (Check: ka koi aur combination total nahi karta.)

Exercise 2.3

Ek length-3 password lowercase letters use karta hai. Worst case mein brute force ko kitne candidates try karne padenge? Kya yeh instant hai?

Recall Solution 2.3

KYUN : positions mein se har ek size ke alphabet se independently fill hoti hai, isliye . . Yeh se bahut neeche hai — practically instant. (Isliye hi 3-character passwords bekaar hote hain.)


Level 3 — Analysis

Goal: enumeration cost aur verify cost ko alag karo, aur totals ke baare mein reason karo.

Exercise 3.1

Ek brute force saare subsets enumerate karta hai, aur har subset ke liye time spend karta hai bits scan karke weight compute karne mein. Total cost batao aur sabse bada jo ke andar rehta hai.

Recall Solution 3.1

Total cost . Hum chahte hain .

  • :
  • :
  • : ✓ (just under)
  • :

Isliye sabse bada safe hai .

Exercise 3.2

Same problem ke do solutions: (A) brute force diye gaye bound ke saath; (B) ek "clever" algorithm ek alag problem par jahan . Kaun kam operations karta hai?

Recall Solution 3.2
  • (A): .
  • (B): . (A) ~ kam operations karta hai. Moral: "exponential" automatically "polynomial" se slow nahi hota — input bound decide karta hai. Chhota exponential ko tame kar deta hai.

Exercise 3.3

Ek subset-sum brute force apna running best aise update karta hai:

best = max(best, val)   # <-- placed BEFORE the weight check
if wt <= W:
    pass

Kya galat hai, aur worst case mein yeh kya return karta hai?

Recall Solution 3.3

Bug: yeh subset ko score karta hai (max(best, val)) subset feasible hai yah confirm karne se pehle (wt <= W). Isliye yeh ek overweight, illegal subset ki value adopt kar sakta hai. Worst case: sabse bhaari, sabse zyada value wala subset — jo violate karta hai — jeet jaata hai, aur ek aisi value return hoti hai jo koi bhi legal packing achieve nahi kar sakta. Answer ek over-estimate hai. Fix: pehle constraint verify karo, phir score karo:

if wt <= W:
    best = max(best, val)

Level 4 — Synthesis

Goal: enumeration + pruning + feasibility decision ko ek complete plan mein combine karo.

Exercise 4.1

Knapsack-style: weights=[2,3,4,5], values=[3,4,5,6], cap W=5. Full subset enumeration se, max value dhundho jahan total weight ho. Reasoning dikhao.

Recall Solution 4.1

Saare subsets enumerate karo; sirf woh rakho jinka weight ho; best value lo. Feasible subsets aur unka (weight, value):

  • → (0, 0)
  • → (2, 3)
  • → (3, 4)
  • → (4, 5)
  • → (5, 6)
  • → (5, 7) ← weight exactly 5, value 7
  • → (6, —) infeasible
  • saare bade subsets 5 exceed karte hain.

Best feasible value = 7, items aur lene se (weight , value ).

Exercise 4.2

Same knapsack items ke saath solve karna hai. Pure brute force ko operations chahiye. Estimate karo, decide karo acceptable hai ya nahi, aur sahi paradigm batao.

Recall Solution 4.2

, times operations. Yeh budget se zyada hai — brute force se hopeless. Structure exist karta hai (overlapping subproblems / optimal substructure), isliye DP use karo: knapsack mein. Moderate ke saath yeh trivial hai. (Agar hai par chota nahi, toh meet-in-the-middle via Bitmasking do halves of mein split karta hai.)

Exercise 4.3

Ek brute force design karo jo saare cities ek baar visit karne ka shortest route dhundhe (Travelling Salesman). Kya enumerate karte ho, size kya hai, aur kis ke liye acceptable hai?

Recall Solution 4.3

Enumerate: cities ki saari orderings (permutations); start city fix karo rotational duplicates khatam karne ke liye, jo tours deta hai. Verify: leg-distances sum karo, har ek . Total order of work.

  • : ✓ theek hai.
  • : ✓ abhi bhi OK.
  • : ✗ borderline/too slow.

TSP NP-hard hai, isliye ~ se aage Bitmasking-DP (Held–Karp, , ~ tak acha) ya heuristics/Backtracking with pruning use karo.


Level 5 — Mastery

Goal: trade-offs judge karo aur sirf constraints se paradigm chuno.

Exercise 5.1

Har constraint ke liye, intended complexity batao aur kya brute force survive karta hai. rule se justify karo. (a) (b) , subsets (c) (d) .

Recall Solution 5.1

(a) ka hint; brute force (permutations) OK. (b) , subsets → ; bhi hai (thoda over), isliye plain OK, borderline — agar verify heavy hai toh meet-in-the-middle use karo. (c) ; borderline par usually light constants ke saath acceptable. (d) ✗; brute force mar jaata hai. Target ✓.

Exercise 5.2

Ek judge deta hai aur best subset kisi constraint ke under maangta hai, bit tricks hint karta hua. Kaun se do paradigms dono viable hain, aur kaise choose karo?

Recall Solution 5.2

, isliye saare subsets par Bitmasking brute force viable hai aur sahi karna sabse simple bhi. Agar constraint mein knapsack-jaisi weight structure hai, DP () bhi viable hai aur large -free structure ke liye faster ho sakta hai. Choose karo: (i) agar enumeration count hai aur correctness sabse zyada matter karti hai → bitmask brute force; (ii) agar badh sakta hai ya chota hai → DP. Jab sure na ho, pehle brute force code karo aur ise DP ke liye reference tester ki tarah use karo.

Exercise 5.3

Tumne ek fast DP likha hai aur chahte ho ki cases par confidence ho ki sahi hai. Describe karo ki brute force yahaan apni value kaise prove karta hai chahe "real" solution DP ho.

Recall Solution 5.3

Brute force ko differential tester ki tarah use karo: bahut saare random small inputs (, jahan instant hai) ke liye, brute force aur DP dono chalao aur assert karo ki unke answers match karte hain. Kyunki complete enumeration guaranteed correct hai, koi bhi mismatch DP mein ek bug locate karta hai. Brute force ki slowness par irrelevant hai; uski correctness-for-free hi poora point hai.


Recall Wrap-up: ek-line procedure (EVE)

Enumerate the candidates, Verify each, Estimate size×cost vs . Agar estimate haare, structure dhundho: recurrence → DP, exchange → greedy, prune-partial → Backtracking, all-subsets small → Bitmasking. Poori complexity language Time Complexity & Big-O se hai.