Big O(n²) Notation ๐๐ฅ
Big O(n²) ka matlab hai ki jaise-jaise input size nn badhta hai, kaam ka time n×nn × n (square) ke hisaab se badhta hai.
Socho tumhe ek kaam karna hai jisme har input ke saath baaki sab inputs ko compare karna hai. Isliye, agar inputs badhenge, toh comparisons bahut zyada badh jayenge. ๐ต
Ek Simple Example Se Samjho ๐ซ๐ค
Socho tumhare classroom mein sabko ek-dusre se handshake karna hai:
- Agar class mein 2 log hain:
- A → B (1 handshake)
- Agar 3 log hain:
- A → B, A → C, B → C (total 3 handshakes)
- Agar 4 log hain:
- A → B, A → C, A → D, B → C, B → D, C → D (total 6 handshakes)
Jaise-jaise log badhenge, handshakes ka number bohot tezi se badhega. ๐คฏ
Ye quadratic growth hai, matlab n2n² ke hisaab se badhta hai.
Example in Code ๐ป
function printAllPairs(array) {
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array.length; j++) {
console.log(array[i], array[j]);
}
}
}
Yahaan har element ko doosre element ke saath compare kar rahe hain. Agar array mein 10 elements hain, toh total 10 × 10 = 100 operations honge. ๐ฌ
Real-Life Examples ๐ก
Friendship Circle ๐ค:
Har dost ek-dusre ke saath handshake kar raha hai. Agar dost 5 hain, toh 25 handshakes honge. Agar dost 10 ho gaye, toh 100 handshakes.Combinations Banani ๐๐ฅค:
Socho tumhare paas 5 food items aur 5 drinks hain. Tumhe har food ke saath har drink ka combination banana hai. Jitne zyada options badhenge, combinations aur zyada ho jayenge!Tic-Tac-Toe Game Board ๐ฎ:
Agar tumhe ek 3x3 board ke har square ke liye moves check karni hain, toh total checks 9 squares × 9 squares = 81 checks honge. Agar board 10x10 ho gaya, toh 100 × 100 = 10,000 checks! ๐ฑ
Easy Formula ๐ง
Jaise-jaise input nn badhta hai:
- n=3n = 3 -> n2=9n² = 9
- n=10n = 10 -> n2=100n² = 100
- n=100n = 100 -> n2=10,000n² = 10,000
Matlab, input badhne par kaam ka time double ya triple nahi, balki bahut zyada badh jata hai! ๐
Key Points to Yaad Rakho:
- Big O(n²) ka matlab: Kaam ka time input ka square ke hisaab se badhta hai.
- Kab hota hai? Jab nested loops ya combinations ka kaam ho.
- Efficient hai? Chhoti input size ke liye thik hai, but bade inputs ke liye avoid karo. ๐ซ
Moral of the story: ๐♂️ Input jitna bada, kaam utna slow!
Comments
Post a Comment