We must consider every shift s from 0 to n−m. → outer loop.
For a fixed s, "is this shift valid?" means: compare P[0] with T[s], P[1] with T[s+1], … → inner loop over j=0…m−1.
The moment any character mismatches, this shift is dead — break early (optimization), no point checking the rest.
If the inner loop finishes without breaking, all m chars matched → record s.
NAIVE-MATCH(T, P): n = len(T); m = len(P) for s = 0 to n - m: # candidate start positions j = 0 while j < m and T[s+j] == P[j]: j = j + 1 if j == m: # inner loop ran to completion report match at s
Imagine you have a long sentence and a short word written on a transparent ruler. You lay the ruler at the very start of the sentence and check letter by letter: does the first letter match? second? If all letters of the little word match the letters underneath, you found it! If at any point a letter is wrong, you stop, slide the ruler one step to the right, and try again from the beginning of the word. You keep sliding until the ruler reaches the end of the sentence. That sliding-and-checking is the whole trick. It's simple but can be slow because every time you slide, you start checking from scratch.
Naive pattern matching ka idea bilkul simple hai: tumhare paas ek bada text T hai (length n) aur ek chhota pattern P hai (length m), aur tumhe dhoondhna hai ki P text ke andar kahan-kahan aata hai. Tareeka? Pattern ko text ke upar slide karo — pehle position 0 par rakho, fir 1, fir 2... har position par letter-by-letter check karo ki match ho raha hai ya nahi. Agar saare m characters match ho gaye to wahan ek match mil gaya; agar beech mein koi ek bhi mismatch hua to turant ruk jao (early break) aur agle position par slide kar do.
Kitni positions check karni padti hain? Sirf 0 se n−m tak, yaani n−m+1 positions — kyunki uske aage pattern text se bahar nikal jaayega. Har position par worst case mein m comparisons lagte hain, isliye total time O(nm) ho jaata hai. Yeh worst case tab aata hai jab text mein bahut repetition ho, jaise T="AAAAA" aur P="AAB" — har baar last character par jaake fail hota hai, full kaam karna padta hai.
Practical baat: real English text ya random data par yeh actually kaafi fast chalta hai, kyunki zyadatar jagah pehle ya doosre character par hi mismatch ho jaata hai, to inner loop chhota reh jaata hai — almost O(n) behave karta hai. Lekin guarantee nahi de sakte, isliye worst case ke liye KMP, Boyer-Moore ya Rabin-Karp jaise smart algorithms aaye, jo pehle se match kiya hua information reuse karke redundant comparisons skip karte hain. Naive ki sabse badi "kamzori" yahi hai ki har slide par wo sab kuch bhool kar j=0 se phir shuru karta hai.