<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Krishpatel on Medium]]></title>
        <description><![CDATA[Stories by Krishpatel on Medium]]></description>
        <link>https://medium.com/@krishpatel20217?source=rss-77898ac3004b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*g20M15b_6mGePX3z</url>
            <title>Stories by Krishpatel on Medium</title>
            <link>https://medium.com/@krishpatel20217?source=rss-77898ac3004b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 15:03:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@krishpatel20217/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Hashing in DSA: How Maps and Sets Optimize Algorithm Performance]]></title>
            <link>https://medium.com/@krishpatel20217/hashing-in-dsa-how-maps-and-sets-optimize-algorithm-performance-06d43d33043e?source=rss-77898ac3004b------2</link>
            <guid isPermaLink="false">https://medium.com/p/06d43d33043e</guid>
            <category><![CDATA[hashing]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[algorithm-analysis]]></category>
            <category><![CDATA[hash-collision]]></category>
            <dc:creator><![CDATA[Krishpatel]]></dc:creator>
            <pubDate>Sat, 05 Dec 2026 05:56:05 GMT</pubDate>
            <atom:updated>2026-12-05T05:56:05.788Z</atom:updated>
            <content:encoded><![CDATA[<p>Hashing is a technique used in DSA to store and retrieve data efficiently. It uses a hash function to convert a given key into an index, which determines where the data should be stored in a data structure called a Hash Table.</p><p>Instead of searching through every element one by one, hashing allows us to directly access the location where the required data is stored.</p><p>For example, suppose we have an array containing 10,000 elements and we want to find a particular number.</p><ul><li>Without Hashing: We may need to check each element one by one using Linear Search, which takes O(n) time in the worst case.</li><li>With Hashing: We can use a hash function to calculate the index where the element is stored and access it directly, achieving O(1) average-case lookup time.</li></ul><p>This makes hashing particularly useful when we need to perform frequent searching, insertion, and deletion operations.</p><h4><strong>Why do we use hashing?</strong></h4><p>Hashing allows us to perform searching, insertion, and deletion operations efficiently, with an average time complexity of O(1).</p><h4><strong>How Does a Hash Function Map a Key to an Index?</strong></h4><p>A hash function is a function that takes a key as input and converts it into an integer that can be used as an index in a hash table.</p><p>In simple terms: Key → Hash Function → Index</p><p>The calculated index determines where the corresponding data should be stored.</p><h4><strong>What is a Hash Table and How Does It Store Key-Value Pairs?</strong></h4><p>A Hash Table is a data structure that uses a hash function to store and retrieve data efficiently.</p><p>It stores data in the form of key-value pairs, where:</p><ul><li>Key: A unique identifier used to access the data.</li><li>Value: The actual data associated with that key.</li></ul><p>Okay so lets say the studentID are (101,102,103) and their name are (krish,rahul,aman). Here studentID acts as key and name acts as value. When we insert a key-value pair into a hash table, the hash function calculates an index using the key. The key-value pair is then stored at the calculated location.</p><p>Suppose we have a hash table of size 10 and use the following hash function: h(key) = key % 10</p><p>Key → Hash Function → Index</p><p>101 → 101 % 10 → 1 like this for all keys (101,102,103) the calculated index are (1,2,3). so in hash tabel the first key value(101-krish) pair is stored 1st index and so for rest key-value pairs.</p><p>Now, suppose we want to retrieve the name associated with student ID 102.</p><ol><li>We pass the key 102 to the hash function.</li><li>The hash function calculates 102 % 10 = 2.</li><li>We directly access index 2.</li><li>We retrieve the corresponding value, which is “Rahul”.</li></ol><p>This is how a hash table allows us to retrieve data efficiently without searching through every entry.</p><p>In short: A hash table uses a hash function to determine where a key-value pair should be stored, allowing efficient insertion, searching, and deletion.</p><h4>What are Hash Collisions and How Are They Handled?</h4><p>A hash collision occurs when two or more different keys produce the same index after passing through a hash function.</p><p>Suppose we have a hash table of size 10 and the hash function is:</p><p>h(key) = key % 10</p><p>Now, consider the following keys:</p><ul><li>23</li><li>33</li><li>43</li></ul><p>Applying the hash function:</p><p>23 % 10 → 3</p><p>33 % 10 → 3</p><p>43 % 10 → 3</p><p>All three keys produce the same index, which is 3.</p><p>This creates a collision because multiple keys are trying to occupy the same location in the hash table.</p><p><strong>How Do We Handle Hash Collisions?</strong></p><p>There are 2 major types of collision resolution technique</p><ol><li>Separate Chaining</li><li>Open Addressing</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*9WO5j0Ye3wExwNkEZeD95g.png" /></figure><h4>A. Separate Chaining</h4><p>Separate Chaining is a collision resolution technique in which each index of the hash table stores a collection of elements instead of storing only one element.</p><p>Usually, a linked list is used to store multiple elements that produce the same index.</p><p>Let’s take our previous example:</p><p>23, 33, 43</p><p>All three keys produce index 3.</p><p>Instead of replacing the existing key, we store all three keys in a linked list at index 3.</p><p><strong>Representation:</strong></p><p>Index 3 → 23 → 33 → 43</p><p>This allows multiple keys to exist at the same index without losing any data.</p><p>Suppose we want to search for key 33.</p><ol><li>Calculate its index using the hash function.</li><li>The hash function returns index 3.</li><li>Go to the linked list stored at index 3.</li><li>Traverse the list until key 33 is found.</li></ol><h4>B. Open Addressing</h4><p>Open Addressing is another collision resolution technique in which all elements are stored directly inside the hash table itself.</p><p>When a collision occurs, instead of storing multiple elements at the same index using a linked list, we search for another available index in the hash table. This process is called probing.</p><p>There are three commonly used probing techniques:</p><h4>1. Linear Probing</h4><p>Linear Probing resolves collisions by checking the next consecutive index until an empty position is found.</p><p>Suppose we have a hash table of size 10 and the hash function:</p><p>h(key) = key % 10</p><p>We want to insert:23, 33, 43</p><p>Step 1: Insert 23. 23 % 10 = 3</p><p>Index 3 is empty, so 23 is stored there.</p><p>Step 2: Insert 33. 33 % 10 = 3</p><p>Index 3 is already occupied by 23. Therefore, we check the next index, which is 4.</p><p>Index 4 is empty, so 33 is stored there.</p><p>Step 3: Insert 43. 43 % 10 = 3</p><p>Index 3 is occupied, and index 4 is also occupied. We continue checking the next index, which is 5.</p><p>Index 5 is empty, so 43 is stored there.</p><p>The general formula for Linear Probing is:</p><p>h(key, i) = (h(key) + i) % tableSize</p><p>Here, i represents the number of probing attempts, starting from 0.</p><p>Disadvantage: Primary Clustering</p><p>Linear Probing can create groups of consecutive occupied positions. These groups are called primary clusters. As these clusters grow, finding an empty position becomes slower.</p><h4>2. Quadratic Probing</h4><p>Quadratic Probing is similar to Linear Probing, but instead of checking consecutive indices, it uses quadratic increments to find the next available position.</p><p>For example, if the original hash index is 3, the probing sequence can be:</p><ul><li>First attempt: 3</li><li>Second attempt: 3 + 1²= 4</li><li>Third attempt: 3 + 2²= 7</li><li>Fourth attempt: 3 + 3²= 12, which becomes 2 for a table of size 10.</li></ul><p>The general formula is:</p><p>h(key, i) = (h(key) + i²) % tableSize</p><p>This helps reduce primary clustering because elements do not necessarily occupy consecutive positions.</p><p>Disadvantage: Secondary Clustering</p><p>Keys that have the same initial hash index follow the same probing sequence. This is known as secondary clustering.</p><h4>3. Double Hashing</h4><p>Double Hashing uses two different hash functions to determine the next available position when a collision occurs.</p><p>The first hash function calculates the initial index, while the second hash function determines the step size for probing.</p><p>The general formula is:</p><p>h(key, i) = (h1(key) + i × h2(key)) % tableSize</p><p>Where:</p><ul><li>h1(key) calculates the initial index.</li><li>h2(key) calculates the step size.</li><li>i represents the probing attempt.</li></ul><p>For example, suppose:</p><ul><li>Table size = 10</li><li>h1(key) = key % 10</li><li>h2(key) = 7 - (key % 7)</li></ul><p>For key 23:</p><p>h1(23) = 23 % 10 = 3</p><p>h2(23) = 7 - (23 % 7) = 5</p><p>If index 3 is occupied, the next position is:</p><p>(3 + 1 × 5) % 10 = 8</p><p>Therefore, we check index 8 for an empty position.</p><p>Double Hashing helps reduce clustering because different keys can have different probing step sizes.</p><h4>Average-Case vs Worst-Case Lookup Complexity</h4><p>Hashing is popular because it provides efficient searching, insertion, and deletion operations.</p><p>However, its performance depends on how effectively the hash function distributes keys across the hash table and how collisions are handled.</p><p>Let’s understand the two important cases.</p><p>Average-Case Time Complexity: O(1)</p><p>In the average case, a good hash function distributes keys relatively evenly across the available indices.</p><p>This means that most keys can be accessed with a small number of operations.</p><p>For example, suppose we want to search for a key in a hash table.</p><ol><li>Apply the hash function to the key.</li><li>Calculate the corresponding index.</li><li>Access the required location.</li></ol><p>Since we can calculate the index directly, we generally do not need to search through all the elements.</p><p>Therefore, searching, insertion, and deletion typically take O(1) average time under suitable conditions.</p><p>Worst-Case Time Complexity: O(n)</p><p>The worst case occurs when many keys produce the same hash index, resulting in a large number of collisions.</p><p>Consider a hash table where multiple keys are stored in the same linked list using Separate Chaining.</p><p>If we want to search for a key located at the end of that linked list, we may need to traverse all the elements.</p><p>If there are n elements in that chain, the operation can take O(n) time.</p><p>Therefore, the worst-case time complexity of searching, insertion, and deletion can be O(n).</p><h4><strong>What is Load Factor?</strong></h4><p>Load Factor measures how full a hash table is. It is calculated using the following formula:</p><p>Load Factor = Number of Stored Elements / Total Table Capacity</p><p>A higher load factor generally increases the likelihood of collisions, which can affect performance.</p><h4>What is Rehashing?</h4><p>Rehashing is the process of creating a larger hash table and inserting the existing elements into the new table using the hash function again. It is generally performed when the hash table becomes too full and its load factor crosses a predefined threshold. Rehashing helps maintain efficient performance by providing more available positions for storing elements.</p><h4>How Map and Set Use Hashing in JavaScript</h4><p>A <strong>Map</strong> is a data structure that stores data in the form of key-value pairs. Each key in a Map is unique, but multiple keys can have the same value.</p><p><strong>Important Map Methods:</strong></p><p>map.set(key, value)Inserts or updates a key-value pair.</p><p>map.get(key)Returns the value associated with a key.</p><p>map.has(key)Checks whether a key exists.</p><p>map.delete(key)Deletes a key-value pair.</p><p>map.sizeReturns the number of entries.</p><p>map.clear()Removes all entries.</p><p>Map is particularly useful when we need to store information associated with unique keys and retrieve it efficiently.</p><pre>const map = new Map();<br><br>map.set(101, &quot;Krish&quot;);<br>map.set(102, &quot;Rahul&quot;);<br><br>console.log(map.get(101)); // Krish<br><br>console.log(map.has(102)); // true<br><br>map.delete(101);<br><br>console.log(map.size); // 1</pre><p>A <strong>Set</strong> is a data structure that stores unique values. Unlike Map, it does not store key-value pairs. It stores only values, and duplicate values are automatically ignored.</p><p><strong>Important Set Methods:</strong></p><p>set.add(value)Adds a new value.</p><p>set.has(value)Checks whether a value exists.</p><p>set.delete(value)Removes a value.</p><p>set.sizeReturns the number of unique values.</p><p>set.clear()Removes all values.</p><pre>const set = new Set([10, 20, 30]);<br><br>console.log(set.has(20)); // true<br><br>set.add(40);<br><br>set.delete(10);<br><br>console.log(set.size); // 3</pre><h4><strong>Practical Applications of Hashing in DSA</strong></h4><p>Understanding hashing theory is important, but its real usefulness becomes clear when we apply it to coding problems.</p><p>Lets understand it with problems:</p><ol><li><strong>Group Anagrams</strong></li></ol><p>Problem Statement: Given an array of strings, group the anagrams together. Anagrams are words that contain the same characters with the same frequencies, but their order can be different.</p><pre>Input:<br>strs = [&quot;eat&quot;, &quot;tea&quot;, &quot;tan&quot;, &quot;ate&quot;, &quot;nat&quot;, &quot;bat&quot;]<br><br>Output:<br>[[&quot;eat&quot;, &quot;tea&quot;, &quot;ate&quot;], [&quot;tan&quot;, &quot;nat&quot;], [&quot;bat&quot;]]</pre><p>One straightforward approach is to compare every string with the other strings and check whether they are anagrams.</p><pre>function groupAnagrams(strs) {<br>    const visited = new Set();<br>    const result = [];<br><br>    for (let i = 0; i &lt; strs.length; i++) {<br>        if (visited.has(i)) continue;<br><br>        const group = [strs[i]];<br>        visited.add(i);<br><br>        for (let j = i + 1; j &lt; strs.length; j++) {<br>            if (visited.has(j)) continue;<br><br>            const a = strs[i].split(&quot;&quot;).sort().join(&quot;&quot;);<br>            const b = strs[j].split(&quot;&quot;).sort().join(&quot;&quot;);<br><br>            if (a === b) {<br>                group.push(strs[j]);<br>                visited.add(j);<br>            }<br>        }<br><br>        result.push(group);<br>    }<br><br>    return result;<br>}</pre><p>Time Complexity: O(n² × k log k)</p><p>This approach is inefficient for large inputs because we repeatedly sort and compare strings. Instead of comparing every string with every other string, we can use a Hash Map to group anagrams directly.</p><pre>function groupAnagrams(strs) {<br>    const map = new Map();<br><br>    for (const str of strs) {<br>        const key = str.split(&quot;&quot;).sort().join(&quot;&quot;);<br><br>        if (!map.has(key)) {<br>            map.set(key, []);<br>        }<br><br>        map.get(key).push(str);<br>    }<br><br>    return Array.from(map.values());<br>}</pre><p>Time Complexity: O(n × k log k)</p><p>Instead of comparing every string with every other string, we generate a common key for anagrams and use a Hash Map to group them efficiently.</p><p><strong>2. Top K Frequent Elements</strong></p><p>Problem Statement: Given an integer array nums and an integer k, return the k most frequent elements. In other words, we need to find the elements that appear most frequently in the array.</p><pre>Input:<br>nums = [1, 1, 1, 2, 2, 3]<br>k = 2<br><br>Output:<br>[1, 2]</pre><p>One straightforward approach is to: Find all unique elements in the array then count the frequency of each element then sort the elements based on their frequencies in descending order then return the first k elements but it will take O(n²) time complexity.</p><p>Instead of repeatedly counting the frequency of each element, The idea is to group numbers according to their frequency.</p><pre><br>var topKFrequent = function(nums, k) {<br>    const map = new Map();<br><br>    // Step 1: Count frequencies<br>    for (const num of nums) {<br>        map.set(num, (map.get(num) || 0) + 1);<br>    }<br><br>    // Step 2: Create frequency buckets<br>    const buckets = Array.from(<br>        { length: nums.length + 1 },<br>        () =&gt; []<br>    );<br><br>    // Step 3: Place numbers into their frequency bucket<br>    for (const [num, frequency] of map) {<br>        buckets[frequency].push(num);<br>    }<br><br>    // Step 4: Collect k most frequent elements<br>    const result = [];<br><br>    for (let i = buckets.length - 1; i &gt;= 0; i--) {<br>        for (const num of buckets[i]) {<br>            result.push(num);<br><br>            if (result.length === k) {<br>                return result;<br>            }<br>        }<br>    }<br><br>    return result;<br>};</pre><p>This aprroach will take <strong>O(n)</strong> time complexity.</p><p><strong>3. Longest Consecutive Sequence</strong></p><p>Problem Statement: Given an unsorted array of integers, find the length of the longest consecutive sequence of elements. A consecutive sequence consists of numbers that follow one another without any gaps. The numbers do not need to appear next to each other in the original array.</p><pre>Input:<br>nums = [100, 4, 200, 1, 3, 2]<br><br>Output:<br>4</pre><p>One straightforward approach is to consider every element as the starting point of a possible consecutive sequence.</p><p>For each element:</p><ol><li>Consider it as the starting number.</li><li>Check whether the next consecutive number exists in the array.</li><li>If it exists, continue checking the next number.</li><li>Keep counting until a number is missing.</li><li>Update the maximum sequence length.</li></ol><p>It will take O(n²) time complexity.</p><p>We can optimize this problem using a Hash Set. The main idea is to use a Set to perform fast membership checks instead of repeatedly searching through the original array.</p><p>A number can be the starting point of a consecutive sequence only if the previous number does not exist in the Set.</p><pre>var longestConsecutive = function(nums) {<br>    const set = new Set(nums);<br>        let longest = 0;<br><br>        for (const num of set) {<br><br>            // num is the beginning of a sequence<br>            if (!set.has(num - 1)) {<br><br>                let current = num;<br>                let count = 1;<br><br>                while (set.has(current + 1)) {<br>                    current++;<br>                    count++;<br>                }<br><br>                longest = Math.max(longest, count);<br>            }<br>        }<br><br>        return longest;<br>};</pre><p>This aprroach will take O(n) time complexity.</p><h4>Conclusion</h4><p>Hashing is one of the most useful techniques in DSA because it helps us solve problems more efficiently by reducing repeated searching and comparisons. Understanding hash functions, hash tables, collisions, and collision resolution techniques gives us a strong foundation for using hashing effectively.</p><p>In JavaScript, Map and Set make hashing practical and easy to apply in everyday coding problems. Problems like <strong>Group Anagrams, Top K Frequent Elements, and Longest Consecutive Sequence</strong> demonstrate how choosing the right data structure can transform a brute-force solution into an optimized one.</p><p>The key takeaway is that algorithm optimization is not always about writing more code — sometimes, it is about choosing the right data structure. By recognizing when to use a Map or Set, we can write cleaner, faster, and more efficient solutions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=06d43d33043e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Big O in Practice: Brute Force, Algorithm Optimization, and Time-Space Trade-offs]]></title>
            <link>https://medium.com/@krishpatel20217/big-o-in-practice-brute-force-algorithm-optimization-and-time-space-trade-offs-af61a05a021b?source=rss-77898ac3004b------2</link>
            <guid isPermaLink="false">https://medium.com/p/af61a05a021b</guid>
            <category><![CDATA[brute-force]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[algorithm-analysis]]></category>
            <dc:creator><![CDATA[Krishpatel]]></dc:creator>
            <pubDate>Fri, 04 Dec 2026 05:49:17 GMT</pubDate>
            <atom:updated>2026-12-04T05:49:17.925Z</atom:updated>
            <content:encoded><![CDATA[<h4>1. Brute Force vs Optimized Solutions</h4><p>Knowing the time complexity of an algorithm is important, but understanding how to improve that complexity is equally important.</p><p>When solving a programming problem, there can be multiple ways to reach the same result. Some approaches are straightforward but involve unnecessary operations, while others use better techniques and data structures to solve the problem more efficiently.</p><p>This brings us to two important approaches: Brute Force and Optimized Solutions.</p><p><strong>What is a Brute-Force Approach?</strong></p><p>A brute-force approach is a straightforward method of solving a problem by checking all possible possibilities or directly comparing elements until the required result is obtained.</p><p>It usually focuses on finding a solution without initially worrying about performance optimization.</p><p>For example, consider finding whether an array contains duplicate elements.</p><pre>const arr = [10, 20, 30, 20];</pre><p>One straightforward approach is to compare every element with every other element.</p><pre>function hasDuplicate(arr) {<br>    for (let i = 0; i &lt; arr.length; i++) {<br>        for (let j = i + 1; j &lt; arr.length; j++) {<br>            if (arr[i] === arr[j]) {<br>                return true;<br>            }<br>        }<br>    }<br>    return false;<br>}</pre><p>Time Complexity: O(n²)</p><p>Auxiliary Space Complexity: O(1)</p><p>The main drawback is that the algorithm performs repeated comparisons. As the input size increases, the number of comparisons grows quadratically.</p><p><strong>What is an Optimized Solution?</strong></p><p>An optimized solution aims to achieve the same result while reducing unnecessary operations, execution time, or memory consumption.</p><p>Instead of repeatedly comparing elements, we can use a suitable data structure to make the operation more efficient.</p><p>For our duplicate detection problem, JavaScript provides a built-in data structure called Set.</p><p>A Set stores unique values and supports efficient average-case lookups.</p><pre>function hasDuplicate(arr) {<br>    const seen = new Set();<br><br>    for (let num of arr) {<br>        if (seen.has(num)) {<br>            return true;<br>        }<br><br>        seen.add(num);<br>    }<br><br>    return false;<br>}</pre><p>Time Complexity: O(n) average</p><p>Auxiliary Space Complexity: O(n)</p><p>The optimized approach reduces the time complexity from O(n²) to O(n) by using additional memory.</p><p>This demonstrates an important principle of algorithm optimization: sometimes, choosing the right data structure can make a significant difference in performance.</p><h4>2. Understanding Time-Space Trade-offs</h4><p>When optimizing an algorithm, improving execution time is not always possible without increasing memory consumption.</p><p>This leads us to the concept of a Time-Space Trade-off.</p><p>A time-space trade-off is a technique in which we use additional memory to reduce execution time, or sometimes reduce memory usage at the cost of additional computation.</p><p>In simple terms, we sometimes sacrifice memory to make an algorithm faster.</p><p>In the brute-force approach, we compare elements repeatedly using nested loops.</p><p>This requires O(n²) time but only O(1) auxiliary space.</p><p>However, when we introduce a Set, we store previously encountered elements in memory.</p><p>This additional memory allows us to check whether an element has already appeared without comparing it against every previous element.</p><p>As a result:</p><ul><li>Brute Force: O(n²) time and O(1) auxiliary space.</li><li>Optimized: O(n) average time and O(n) auxiliary space.</li></ul><p>We use more memory, but significantly reduce the number of operations.</p><p>However, additional memory is not always the best choice. Sometime reducing memory consumption may be more important than achieving the fastest possible execution time.</p><p>The goal is to find a suitable balance between execution time and memory consumption.</p><h4>3. How to Identify and Optimize an Algorithm</h4><p><strong>Step 1: Understand the Problem</strong></p><p>Understand what the problem requires, including its inputs, expected outputs, constraints, and edge cases.</p><p><strong>Step 2: Write a Straightforward Solution</strong></p><p>Start with a simple approach that correctly solves the problem without worrying about optimization.</p><p><strong>Step 3: Analyze Time and Space Complexity</strong></p><p>Determine how the algorithm’s execution time and additional memory requirements grow with input size.</p><p><strong>Step 4: Identify Unnecessary Operations</strong></p><p>Look for repeated calculations, unnecessary comparisons, or operations that can be avoided.</p><p><strong>Step 5: Choose a Better Technique or Data Structure</strong></p><p>Use suitable algorithms or data structures, such as Map, Set, Binary Search, or Two Pointers, to improve efficiency.</p><p><strong>Step 6: Compare Both Solutions</strong></p><p>Compare the original and optimized solutions based on time complexity, auxiliary space, and overall performance.</p><h4>4. Applying Algorithm Optimization in Practice</h4><p><strong>Problem 1: Contains Duplicate</strong></p><p><strong>Step 1: Understand the Problem</strong></p><p>Determine whether an array contains any duplicate elements.</p><p><strong>Step 2: Brute-Force Approach</strong></p><p>Use nested loops to compare every element with the remaining elements.</p><pre>function containsDuplicate(nums) {<br>    for (let i = 0; i &lt; nums.length; i++) {<br>        for (let j = i + 1; j &lt; nums.length; j++) {<br>            if (nums[i] === nums[j]) {<br>                return true;<br>            }<br>        }<br>    }<br>    return false;<br>}</pre><p><strong>Step 3: Complexity Analysis</strong></p><ul><li>Time: O(n²)</li><li>Auxiliary Space: O(1)</li></ul><p><strong>Step 4: Optimize the Solution</strong></p><p>Use a Set to store encountered elements and check for duplicates using has().</p><pre>function containsDuplicate(nums) {<br>    const seen = new Set();<br>    for (let num of nums) {<br>        if (seen.has(num)) {<br>            return true;<br>        }<br>        seen.add(num);<br>    }<br>    return false;<br>}</pre><p><strong>Step 5: Compare Both Solutions</strong></p><ul><li>Brute Force: O(n²) time, O(1) space.</li><li>Optimized: O(n) average time, O(n) space.</li></ul><p><strong>Problem 2: Two Sum</strong></p><p><strong>Step 1: Understand the Problem</strong></p><p>Find two elements in an array whose sum equals the given target and return their indices.</p><p><strong>Step 2: Brute-Force Approach</strong></p><p>Use nested loops to check every possible pair of elements.</p><pre>function twoSum(nums, target) {<br>    for (let i = 0; i &lt; nums.length; i++) {<br>        for (let j = i + 1; j &lt; nums.length; j++) {<br>            if (nums[i] + nums[j] === target) {<br>                return [i, j];<br>            }<br>        }<br>    }<br>    return [];<br>}</pre><p><strong>Step 3: Complexity Analysis</strong></p><ul><li>Time: O(n²)</li><li>Auxiliary Space: O(1)</li></ul><p><strong>Step 4: Optimize the Solution</strong></p><p>Use a Map to store previously encountered numbers and their indices. Check whether the required complement already exists.</p><pre>function twoSum(nums, target) {<br>    const map = new Map();<br>    for (let i = 0; i &lt; nums.length; i++) {<br>        const complement = target - nums[i];<br>        if (map.has(complement)) {<br>            return [map.get(complement), i];<br>        }<br>        map.set(nums[i], i);<br>    }<br>    return [];<br>}</pre><p><strong>Step 5: Compare Both Solutions</strong></p><ul><li>Brute Force: O(n²) time, O(1) space.</li><li>Optimized: O(n) average time, O(n) space.</li></ul><p><strong>Problem 3: Valid Anagram</strong></p><p><strong>Step 1: Understand the Problem</strong></p><p>Determine whether two strings contain exactly the same characters with the same frequencies, regardless of their order.</p><p><strong>Step 2: Brute-Force Approach</strong></p><p>Sort both strings and compare the resulting sorted strings.</p><pre>function isAnagram(s, t) {<br>    if (s.length !== t.length) {<br>        return false;<br>    }<br>    const sortedS = s.split(&quot;&quot;).sort().join(&quot;&quot;);<br>    const sortedT = t.split(&quot;&quot;).sort().join(&quot;&quot;);<br>    return sortedS === sortedT;<br>}</pre><p><strong>Step 3: Complexity Analysis</strong></p><ul><li>Time: O(n log n)</li><li>Auxiliary Space: Depends on the sorting implementation.</li></ul><p><strong>Step 4: Optimize the Solution</strong></p><p>Use a Map to count the frequency of each character in the first string and subtract the frequencies using the second string.</p><pre>function isAnagram(s, t) {<br>    if (s.length !== t.length) {<br>        return false;<br>    }<br>    const frequency = new Map();<br>    for (let char of s) {<br>        frequency.set(char, (frequency.get(char) || 0) + 1);<br>    }<br>    for (let char of t) {<br>        if (!frequency.has(char)) {<br>            return false;<br>        }<br>        frequency.set(char, frequency.get(char) - 1);<br>        if (frequency.get(char) &lt; 0) {<br>            return false;<br>        }<br>    }<br>    return true;<br>}</pre><p><strong>Step 5: Compare Both Solutions</strong></p><ul><li>Sorting: O(n log n) time.</li><li>Frequency Map: O(n) average time, O(k) space, where k is the number of distinct characters.</li></ul><h4>Conclusion</h4><p>Understanding Big O notation helps us analyze how an algorithm performs, but writing efficient algorithms requires going a step further.</p><p>As we have seen, the same problem can have multiple solutions, and choosing the right approach or data structure can significantly improve performance.</p><p>By comparing brute-force and optimized solutions, we learned how techniques such as Map, Set, and frequency counting can reduce unnecessary operations and improve execution time.</p><p>However, optimization is not always about achieving the lowest time complexity. Sometimes, using additional memory is a reasonable trade-off for faster execution.</p><p>Ultimately, writing efficient code is about understanding the problem, identifying inefficiencies, and choosing the right balance between execution time and memory consumption.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af61a05a021b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Beyond Tutorials: Understanding this and Prototypes]]></title>
            <link>https://medium.com/@krishpatel20217/javascript-beyond-tutorials-understanding-this-and-prototypes-6ebc37b3a5a0?source=rss-77898ac3004b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ebc37b3a5a0</guid>
            <category><![CDATA[prototype]]></category>
            <category><![CDATA[prototype-chain]]></category>
            <category><![CDATA[javascript-this-keyword]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Krishpatel]]></dc:creator>
            <pubDate>Thu, 03 Dec 2026 13:30:27 GMT</pubDate>
            <atom:updated>2026-12-03T13:30:27.378Z</atom:updated>
            <content:encoded><![CDATA[<h3>Javascript beyond tutorials</h3><h4>1. This keyword</h4><p>“this” keyword depends on how a function is called , it may refer to an object, global object, or be undefined (in strict mode), and its value is determined at runtime based on how the function is invoked.</p><p><strong>1.1 this in global scope</strong></p><p>When this is called in global scope of browser it refers to the windows object. Windows object refers to the browser APIs. if its called in global scope of node.js it refers to blank object {}.</p><pre>console.log(this); // windows object</pre><p><strong>1.2 this in regular function</strong></p><pre>function show() {<br>  console.log(this);<br>}<br>show();</pre><ul><li><strong>Browser (non-strict):</strong> this = window</li><li><strong>Node (non-strict):</strong> this = global</li><li><strong>Strict mode mein:</strong> this = undefined</li></ul><p><strong>1.3 this with object</strong></p><pre>const user = {<br>  name: &quot;Rahul&quot;,<br>  greet() {<br>    console.log(&quot;Hi, &quot; + this.name);<br>  }<br>};<br>user.greet(); // Hi, Rahul</pre><p>When this is called inside a function which is inside a object then it refers to object. In a regular object method, this refers to the object before the dot when the method is called.</p><pre>const fn = user.greet; // reference nikaal liya, object chhod diya<br>fn(); // undefined  (ab dot ke left koi object nahi)</pre><p><strong>1.4 this with arrow function</strong></p><p>Arrow functions don’t have their own this. Instead, they lexically inherit this from their surrounding scope.</p><p>They don’t borrow this from the object that calls them.</p><pre>const user = {<br>  name: &quot;Rahul&quot;,<br>  greet: () =&gt; {<br>    console.log(this.name); // undefined! (user se nahi liya)<br>  }<br>};<br>user.greet();</pre><p>A regular function gets its this from how it is called. Since user calls show(), this refers to user.</p><p>Arrow function inside a regular method. This is where arrow functions become useful:</p><pre>const user = {<br>    name: &quot;Krish&quot;,<br><br>    show() {<br>        const arrow = () =&gt; {<br>            console.log(this.name);<br>        };<br><br>        arrow();<br>    }<br>};<br><br>user.show(); // Krish</pre><p><strong>1.5 this with event handler</strong></p><pre>button.addEventListener(&quot;click&quot;, function () {<br>  console.log(this); // wo button element jispe click hua<br>});</pre><p>This will happen with the regular function but when it comes to arrow function.</p><pre>button.addEventListener(&quot;click&quot;, () =&gt; {<br>  console.log(this); // window (button NAHI)<br>});</pre><ul><li><strong>Global scope</strong> → window in a browser&#39;s regular script.</li><li><strong>Strict mode</strong> → undefined inside a normally called regular function.</li><li><strong>Regular function</strong> → this depends on how it is called.</li><li><strong>Arrow function </strong>→ it depends on where its defined. Inherits this from its surrounding scope.</li></ul><h4>2. call, apply, bind— Explicit Binding</h4><ol><li>call()</li></ol><p>The call() method invokes a function immediately and lets us pass the this object and arguments individually.</p><pre>function introduce(city, country) {<br>    console.log(`I am ${this.name} from ${city}, ${country}`);<br>}<br><br>const user = {<br>    name: &quot;Krish&quot;<br>};<br><br>introduce.call(user, &quot;Ahmedabad&quot;, &quot;India&quot;);</pre><p>2. apply()</p><p>The apply() method works exactly like call(), but the arguments are passed as an array.</p><pre>function introduce(city, country) {<br>    console.log(`I am ${this.name} from ${city}, ${country}`);<br>}<br><br>const user = {<br>    name: &quot;Krish&quot;<br>};<br><br>introduce.apply(user, [&quot;Ahmedabad&quot;, &quot;India&quot;]);</pre><p>3. bind()</p><p>The bind() method does not execute the function immediately. Instead, it returns a new function with this permanently set to the specified object.</p><pre>function introduce() {<br>    console.log(`Hello, I am ${this.name}`);<br>}<br><br>const user = {<br>    name: &quot;Krish&quot;<br>};<br><br>const boundFunction = introduce.bind(user);<br><br>boundFunction();</pre><p><strong>Easy way to remember:</strong></p><ul><li>call → Call the function now.</li><li>apply → Apply arguments as an array.</li><li>bind → Bind this and use the function later.</li></ul><h4>3. Prototypes</h4><p>In JavaScript, a prototype is an object from which another object can inherit properties and methods.</p><p>It allows us to share properties and methods between objects instead of creating them separately for every object.</p><p>prototype vs __proto__</p><ul><li>prototype → A property of a constructor function, used when creating objects with new.</li><li>__proto__ → A property that refers to the prototype of an object.</li></ul><p>__proto__ example:</p><pre>let a = {<br>    name : &quot;krish&quot;,<br>    age:2<br>}<br>let b= [12,3,4];<br>let c = function (){<br>    console.log(&quot;hi&quot;);<br>    <br>}<br>console.log(a);<br>//[[Prototype]]:Object ==&gt; [[Prototype]] → null<br><br>console.log(b);<br>//[[Prototype]]:Array ==&gt; [[Prototype]]:Object ==&gt; [[Prototype]] → null<br><br>console.log(c);<br>//[[Prototype]]:Function ==&gt; [[Prototype]]:Object ==&gt; [[Prototype]] → null</pre><p><strong>“Almost everything in JavaScript is an object or can access object properties through its prototype chain, but not everything is an object.”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mvbb8dOp8lWOoerKpWsKig.png" /></figure><p>Prototype example:</p><pre>function Person(name) {<br>    this.name = name;<br>}<br><br>Person.prototype.greet = function () {<br>    console.log(&quot;Hello &quot; + this.name);<br>};<br><br>const user = new Person(&quot;Krish&quot;);<br><br>user.greet(); // Hello Krish</pre><p><strong>3.1 Prototype chain</strong></p><p>The <strong>prototype chain</strong> is the sequence of objects JavaScript searches through when trying to find a property or method that does not exist directly on an object.</p><p>In simple words, if an object doesn’t have a property, JavaScript checks its prototype, then that prototype’s prototype, and continues until it finds the property or reaches null.</p><pre>const parent = {<br>    name: &quot;Krish&quot;<br>};<br><br>const child = Object.create(parent);<br><br>child.age = 20;<br><br>console.log(child.age);  // 20<br>console.log(child.name); // Krish</pre><p><strong>3.2 Inheritance via Prototypes</strong></p><p><strong>Prototype inheritance</strong> is a mechanism in JavaScript that allows one object to access the properties and methods of another object through its prototype.</p><p>Instead of duplicating properties and methods in multiple objects, we can define them once and let other objects inherit them.</p><pre>const parent = {<br>    name: &quot;Krish&quot;,<br><br>    greet() {<br>        console.log(&quot;Hello &quot; + this.name);<br>    }<br>};<br><br>const child = Object.create(parent);<br><br>child.age = 20;<br><br>console.log(child.name); // Krish<br>console.log(child.age);  // 20<br><br>child.greet(); // Hello Krish</pre><h4>Conclusion</h4><p>JavaScript is much more than just writing functions, loops, and solving problems. Understanding concepts like this, explicit binding with call(), apply(), and bind(), and prototype-based inheritance helps us understand what actually happens behind the scenes.</p><p>These concepts might seem confusing at first, but once we understand how JavaScript determines the value of this, how functions can be reused with different objects, and how objects inherit properties through the prototype chain, the language starts making much more sense.</p><p>The goal of learning JavaScript is not just to make code work, but to understand why it works the way it does. The deeper we explore these fundamentals, the more confidently we can write, debug, and build real-world applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ebc37b3a5a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Space Complexity Explained: Auxiliary Space, Memory Growth, and Big O]]></title>
            <link>https://medium.com/@krishpatel20217/space-complexity-explained-auxiliary-space-memory-growth-and-big-o-b54ab7d5c12a?source=rss-77898ac3004b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b54ab7d5c12a</guid>
            <category><![CDATA[space-complexity]]></category>
            <category><![CDATA[algorithm-analysis]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <dc:creator><![CDATA[Krishpatel]]></dc:creator>
            <pubDate>Thu, 03 Dec 2026 04:47:24 GMT</pubDate>
            <atom:updated>2026-12-03T04:47:24.820Z</atom:updated>
            <content:encoded><![CDATA[<p>Every algorithm needs memory to store data, perform calculations, and execute instructions. But have you ever wondered how much memory an algorithm actually requires?</p><p>An algorithm might execute very quickly but consume a large amount of memory. Another might use very little memory but take considerably more time to execute.</p><p>This is where Space Complexity comes into the picture.</p><p>Space Complexity measures how the memory requirements of an algorithm grow as the input size increases. It helps us understand whether an algorithm can handle large amounts of data without consuming excessive memory.</p><h4><strong>Time complexity and Space complexity</strong></h4><p>Before understanding space complexity, let’s understand how it differs from time complexity.</p><p>Both are used to analyse the efficiency of an algorithm, but they measure different resources.</p><ul><li><strong>Time Complexity:</strong> Measures how the number of operations performed by an algorithm grows as the input size increases.</li><li><strong>Space Complexity:</strong> Measures how the memory requirements of an algorithm grow as the input size increases.</li></ul><p>Both use asymptotic notation, such as Big O, to describe their growth rates independently of specific hardware.</p><p><strong>Do both matter?</strong></p><p>Yes! Both time and space complexity are important when evaluating an algorithm.</p><p>An algorithm might execute very quickly but require a large amount of memory. Another algorithm might use very little memory but take considerably more time.</p><p>Therefore, we need to consider both factors when choosing an algorithm.</p><p>However, minimizing both time and space simultaneously is not always possible. Sometimes, we deliberately use additional memory to make an algorithm faster</p><h4>Space Complexity</h4><p>Space Complexity is the amount of memory an algorithm requires during its execution, expressed as a function of its input size.</p><p>For a useful analysis, we can divide memory requirements into two parts:</p><ol><li>Input Space</li><li>Auxiliary Space</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*bUvKcapSMCx7zcWy3gi1FQ.png" /><figcaption>space complexity = input space + auxiliary space</figcaption></figure><p><strong>Input Space</strong></p><p>Input Space refers to the memory occupied by the input data provided to an algorithm.</p><p>For example, if an algorithm receives an array containing (n) elements, the memory required to store that array is its input space.</p><p>It includes:</p><ul><li>Input arrays</li><li>Strings</li><li>Graphs</li><li>Other data structures passed to the algorithm</li></ul><p><strong>Auxiliary Space</strong></p><p>Auxiliary Space refers to the additional memory an algorithm uses during execution, excluding the memory occupied by its input.</p><p>It depends on how the algorithm is designed.</p><p>It includes:</p><ul><li>Local variables</li><li>Temporary arrays</li><li>Additional hash maps or sets</li><li>Recursion call stack</li></ul><p>For example, consider an algorithm that receives an array and creates another array to store its processed elements. The original array is input space, while the newly created array is auxiliary space.</p><h4><strong>Space Complexity of Common Data Structures</strong></h4><p><strong>Primitive Variables — O(1)</strong></p><p>Primitive variables such as numbers, booleans, and characters generally require a fixed amount of memory.</p><pre>function calculateSum(a, b) {<br>    let sum = a + b;<br>    return sum;<br>}</pre><p>Here, we use a fixed number of variables regardless of the input size.</p><p>Even if the input values become larger, the number of variables remains the same.</p><p>Therefore, the auxiliary space complexity is: O(1)</p><p><strong>Arrays / Lists — O(n)</strong></p><p>An array containing (n) elements requires memory proportional to the number of elements stored.</p><pre>let arr = [10, 20, 30, 40, 50];</pre><p>If the array contains 5 elements, memory is allocated to store those elements. If it contains 100 elements, more memory is required.</p><p>Therefore, an array containing (n) elements generally requires: O(n)</p><p>For a two-dimensional array with (n) rows and (n) columns, the total number of elements is: n²</p><p>Therefore, its space complexity is: O(n²)</p><p><strong>Sets — O(n)</strong></p><p>A Set stores unique elements.</p><p>If a Set contains (n) unique elements, its memory requirement generally grows proportionally to the number of elements.</p><p>Therefore: O(n)</p><p><strong>Maps / Hash Tables — O(n)</strong></p><p>A Map stores key-value pairs.</p><p>If a Map contains (n) key-value pairs, its memory requirement generally grows with the number of entries stored.</p><p>Therefore: O(n)</p><h4><strong>How recursion uses the call stack?</strong></h4><p>Recursion uses the call stack by pausing each active function call and pushing its state (local variables, parameters, and return address) onto a stack in memory until the base case is reached.</p><p>How It Works Step-by-Step</p><ol><li>Push on call: Every time a function calls itself, a new stack frame is added to the top of the call stack.</li><li>Wait for inner calls: Outer calls stay frozen in memory until the inner calls finish and return a result.</li><li>Pop on return: Once the base case hits, frames pop off the stack one by one in Last-In, First-Out (LIFO) order, freeing their memory.</li></ol><h4><strong>In-place Algorithms</strong></h4><p>An in-place algorithm performs operations by reusing the existing input memory instead of creating another data structure to store the result.</p><p>Generally, an in-place algorithm requires: O(1)</p><p>Example: Reversing an Array In-place</p><pre>function reverseArray(arr) {<br>    let left = 0;<br>    let right = arr.length - 1;<br><br>    while (left &lt; right) {<br>        let temp = arr[left];<br><br>        arr[left] = arr[right];<br>        arr[right] = temp;<br><br>        left++;<br>        right--;<br>    }<br><br>    return arr;<br>}</pre><p>Suppose the input array is: [10,20,30,40,50]</p><p>The algorithm swaps the first and last elements, then the second and second-last elements, until the array is reversed.</p><p>The result becomes: [50,40,30,20,10]</p><p>We only used three additional variables: left, right, temp.</p><p>Since the number of additional variables remains constant regardless of the array size, the auxiliary space complexity is: O(1). This is why the algorithm is considered in-place.</p><h4><strong>Analysing Space Complexity with Examples</strong></h4><ol><li><strong>Constant Auxiliary Space — O(1)</strong></li></ol><pre>function findSum(arr) {<br>    let sum = 0;<br><br>    for (let i = 0; i &lt; arr.length; i++) {<br>        sum += arr[i];<br>    }<br><br>    return sum;<br>}</pre><p>Here:</p><ul><li>sum stores the running total.</li><li>i stores the current array index.</li></ul><p>Both variables require a fixed amount of memory.</p><p>Even if the input array contains 10 elements or 10,000 elements, we use the same number of additional variables.</p><p>Therefore, the auxiliary space complexity is: O(1)</p><p><strong>2. Linear Auxiliary Space — O(n)</strong></p><pre>function createArray(n) {<br>    let result = [];<br><br>    for (let i = 0; i &lt; n; i++) {<br>        result.push(i);<br>    }<br><br>    return result;<br>}</pre><p>Here:</p><ul><li>result is an additional array.</li><li>The loop inserts (n) elements into it.</li></ul><p>As the input size increases, the size of the additional array also increases.</p><p>Therefore, the auxiliary space complexity is: O(n)</p><p><strong>3. Quadratic Auxiliary Space — O(n²)</strong></p><pre>function createMatrix(n) {<br>    let matrix = [];<br><br>    for (let i = 0; i &lt; n; i++) {<br>        let row = [];<br><br>        for (let j = 0; j &lt; n; j++) {<br>            row.push(0);<br>        }<br><br>        matrix.push(row);<br>    }<br><br>    return matrix;<br>}</pre><p>Here:</p><ul><li>The outer loop creates (n) rows.</li><li>The inner loop inserts (n) elements into every row.</li></ul><p>Therefore, the total number of elements stored is: n²</p><p>Since the algorithm creates an additional matrix containing n² elements, its auxiliary space complexity is: O(n²).</p><h4>Conclusion</h4><p>Understanding space complexity is just as important as understanding time complexity when analysing an algorithm.</p><p>In this article, we explored how memory requirements grow with input size and understood the difference between input space and auxiliary space. We also learned how common data structures, recursion, and in-place algorithms affect memory consumption.</p><p>Through practical examples, we saw that an algorithm using only a fixed number of additional variables can have O(1) auxiliary space, while creating an additional array or matrix can result in O(n) or O(n²) space complexity.</p><p>Ultimately, efficient algorithm design is not just about reducing execution time. It is also about managing memory effectively, especially when working with large amounts of data.</p><p>The goal is to find a suitable balance between time and space so that an algorithm performs efficiently without consuming unnecessary resources.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b54ab7d5c12a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Code Looks Simple… But How Fast Is It Really? A Beginner’s Guide to Time Complexity]]></title>
            <link>https://medium.com/@krishpatel20217/your-code-looks-simple-but-how-fast-is-it-really-a-beginners-guide-to-time-complexity-84b65b1a67a5?source=rss-77898ac3004b------2</link>
            <guid isPermaLink="false">https://medium.com/p/84b65b1a67a5</guid>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[algorithm-analysis]]></category>
            <category><![CDATA[js]]></category>
            <dc:creator><![CDATA[Krishpatel]]></dc:creator>
            <pubDate>Wed, 02 Dec 2026 05:34:28 GMT</pubDate>
            <atom:updated>2026-12-02T05:34:28.919Z</atom:updated>
            <content:encoded><![CDATA[<p>Writing an algorithm is only one part of solving a problem. We also need to understand how efficiently it performs, especially when the amount of input data increases.</p><p>But how can we determine whether an algorithm is efficient just by looking at its code?</p><p>The answer lies in analysing the structure of the code and understanding how many times its statements are executed. Different programming constructs, such as loops, nested loops, and conditional statements, affect the number of operations in different ways.</p><p>For example, a loop that executes (n) times has a different growth rate from a nested loop where each iteration executes another (n) times. Similarly, a loop that repeatedly doubles or halves a variable can have logarithmic complexity instead of linear complexity.</p><p>In this article, we will learn how to analyse these common programming structures, count their iterations, and determine their time complexity using Big O notation.</p><h4>Analyzing Time Complexity of Different Code Structures</h4><h4>1. Analyzing a single loop</h4><pre>for (let i = 0; i &lt; n; i++) {<br>    console.log(i);<br>}</pre><p>Here, we need to count how many times each statement is executed.</p><ul><li>let i = 0 is executed 1 time because it initializes the loop.</li><li>i &lt; n is executed n + 1 times because the condition is checked before every iteration and once more when the loop terminates.</li><li>i++ is executed n times because the variable is incremented after every iteration.</li><li>console.log(i) is executed n times because the loop body runs once during each iteration.</li></ul><p>Now, let’s form the equation:</p><p>Let (c1,c2,c3,c4) represent the constant execution costs of these statements.</p><p>T(n) = c1 + (n+1).c2 + n.c3 + n.c4</p><p>On further solving: T(n) = (c1+c2)+(c2+c3+c4).n</p><p>The dominant term is ((c2+c3+c4)n). Since the coefficients are constants, we ignore them.</p><p>Therefore, the time complexity is: O(n).</p><p><strong>What if the loop increments by 2 instead of 1?</strong></p><pre>for (let i = 0; i &lt; n; i += 2) {<br>    console.log(i);<br>}</pre><p>In this case, the loop executes approximately (n/2) times instead of (n) times.</p><p>Its time complexity is still: O(n/2)=O(n)</p><p>This is because Big O ignores constant factors. Whether a loop runs (n) times or (n/2) times, its growth rate is linear.</p><h4>2. Understanding Nested Loops</h4><p>A nested loop is a loop placed inside another loop. To analyze it, we need to consider how many times the inner loop executes for every iteration of the outer loop.</p><pre>for (let i = 0; i &lt; n; i++) {<br>    for (let j = 0; j &lt; n; j++) {<br>        console.log(i, j);<br>    }<br>}</pre><p>Here, we have two loops.</p><ul><li>The outer loop executes n times.</li><li>For every iteration of the outer loop, the inner loop also executes n times.</li></ul><p>Therefore, the total number of executions of console.log(i, j) is: n²</p><p>Let’s count the statements:</p><ul><li>let i = 0 is executed 1 time.</li><li>i &lt; n is executed (n+1) times.</li><li>i++ is executed (n) times.</li><li>let j = 0 is executed (n) times because it is initialized again for every outer loop iteration.</li><li>j &lt; n is executed (n(n+1)) times.</li><li>j++ is executed (n^2) times.</li><li>console.log(i, j) is executed (n^2) times.</li></ul><p>Now, let’s form the equation:</p><p>T(n) = c1+(n+1).c2+n.c3+n.c4+n(n+1).c5+n².c6+n².c7</p><p>On expanding and grouping the terms:T(n)=an²+bn+d</p><p>The dominant term is (an²). We ignore the lower-order terms and constant factors.</p><p>Therefore, the time complexity is: O(n²)</p><h4>3. Consecutive Loops</h4><p>Consecutive loops are loops that execute one after another rather than being nested inside each other.</p><pre>for (let i = 0; i &lt; n; i++) {<br>    console.log(i);<br>}<br><br>for (let j = 0; j &lt; n; j++) {<br>    console.log(j);<br>}</pre><p>Here, we have two separate loops.</p><ul><li>The first loop executes (n) times.</li><li>The second loop also executes (n) times.</li></ul><p>Since the loops execute one after another, we add their iterations.</p><p>T(n)=n+n</p><p>T(n)=2n</p><p>Ignoring the constant factor: O(n).</p><p>Let’s consider another example where the loops have different complexities:</p><pre>for (let i = 0; i &lt; n; i++) {<br>    console.log(i);<br>}<br><br>for (let j = 0; j &lt; n * n; j++) {<br>    console.log(j);<br>}</pre><p>Here:</p><ul><li>The first loop executes (n) times.</li><li>The second loop executes (n²) times.</li></ul><p>Therefore:</p><p>T(n)=n+n²</p><p>The dominant term is (n²), so we ignore the smaller term (n).</p><p>so O(n²)</p><h4>4. Logarithmic Complexity</h4><p>So far, we have analysed loops where a variable increases by a fixed amount in every iteration.</p><p>But what happens when a variable is repeatedly multiplied or divided by a constant?</p><pre>for (let i = 1; i &lt; n; i *= 2) {<br>    console.log(i);<br>}</pre><p>Here, the value of i doubles after every iteration.</p><p>The values of i will be: 1,2,4,8,16,32,……</p><p>Instead of increasing by 1, the variable doubles in every iteration.</p><p>Let’s assume the loop executes (k) times.</p><p>After every iteration, the value is multiplied by 2.</p><p>Therefore: i=2^k</p><p>The loop stops when (i) becomes greater than or equal to (n).</p><p>2^k ≥ n</p><p>Taking logarithm on both sides: k.log 2 = log n</p><p>and as log 2 is 1 so k = log n</p><p>Hence, the time complexity is: O(log n).</p><p><strong>What happens when we halve the variable?</strong></p><pre>for (let i = n; i &gt; 1; i /= 2) {<br>    console.log(i);<br>}</pre><p>Here, the value of i is divided by 2 after every iteration.</p><p>The values will be: n,n/2,n/4,n/8,…</p><p>After (k) iterations: i = n / 2^k</p><p>The loop stops when the value becomes less than or equal to 1.</p><p>n / 2^k ≤ 1</p><p>Rearranging: n ≤ 2^k</p><p>Taking logarithm: log n ≤ k log 2</p><p>Therefore, the time complexity is: O(log n).</p><h4>5. Conditional Statements</h4><p>Conditional statements such as if, else if, and else execute different blocks of code depending on a condition.</p><p>Unlike loops, conditional statements do not automatically repeat. To analyse them, we need to consider which branch executes and how much work each branch performs.</p><pre>if (n &gt; 10) {<br>    console.log(&quot;Large&quot;);<br>} else {<br>    console.log(&quot;Small&quot;);<br>}</pre><p>Here, only one of the two branches executes.</p><p>Both branches contain a single statement, so regardless of which branch executes, the amount of work remains constant.</p><p>Therefore: O(1)</p><p><strong>What if the branches have different complexities?</strong></p><pre>if (condition) {<br>    for (let i = 0; i &lt; n; i++) {<br>        console.log(i);<br>    }<br>} else {<br>    for (let j = 0; j &lt; n * n; j++) {<br>        console.log(j);<br>    }<br>}</pre><p>Here:</p><ul><li>The first branch executes a loop (n) times, giving (O(n)).</li><li>The second branch executes a loop (n²) times, giving (O(n²)).</li></ul><p>Since only one branch executes, we do not add their complexities.</p><p>Instead, we analyse the possible cases:</p><p>Best Case: The first branch executes.<br>O(n)</p><p>Worst Case: The second branch executes.<br>O(n²)</p><p>Therefore, the worst-case time complexity is: O(n²).</p><h4>6. Mixed Complexity</h4><p>Sometimes, an algorithm contains different types of loops and programming structures together. In such situations, we need to analyse each part separately and then combine the complexities.</p><pre>for (let i = 0; i &lt; n; i++) {<br>    for (let j = 1; j &lt; n; j *= 2) {<br>        console.log(i, j);<br>    }<br>}</pre><p>Here:</p><ul><li>The outer loop executes (n) times.</li><li>The inner loop doubles its variable in every iteration, so it executes approximately (log n) times.</li></ul><p>Since the inner loop executes for every iteration of the outer loop, we multiply their iterations.</p><p>Therefore: O(n log n)</p><pre>for (let i = 0; i &lt; n; i++) {<br>    console.log(i);<br>}<br><br>for (let j = 0; j &lt; n * n; j++) {<br>    console.log(j);<br>}</pre><p>Here:</p><ul><li>The first loop executes (n) times.</li><li>The second loop executes (n²) times.</li></ul><p>Since these are consecutive loops, we add their complexities.</p><p>T(n)=n+n²</p><p>The dominant term is (n²).</p><p>Therefore: O(n²)</p><pre>for (let i = 0; i &lt; n; i++) {<br>    for (let j = 0; j &lt; n; j++) {<br>        console.log(i, j);<br>    }<br>}<br><br>for (let k = 0; k &lt; n; k++) {<br>    for (let m = 1; m &lt; n; m *= 2) {<br>        console.log(k, m);<br>    }<br>}</pre><p>Here:</p><ul><li>The first nested loop has complexity (O(n²)).</li><li>The second nested loop has complexity (O(n log n)).</li></ul><p>Since they execute consecutively, we add their complexities.</p><p>T(n)=n²+n log n</p><p>The dominant term is (n²).</p><p>Therefore: O(n²)</p><h4>7. Analyzing a While Loop</h4><pre>let i = 0;<br><br>while (i &lt; n) {<br>    console.log(i);<br>    i++;<br>}</pre><p>Here, we need to count how many times each statement is executed.</p><ul><li>let i = 0 is executed <strong>1 time</strong> because it initializes the variable.</li><li>i &lt; n is executed <strong>n + 1 times</strong> because the condition is checked before every iteration and once more when the loop terminates.</li><li>console.log(i) is executed <strong>n times</strong> because the loop body runs once during each iteration.</li><li>i++ is executed <strong>n times</strong> because the variable is incremented after every iteration.</li></ul><p>Now, let’s form the equation:</p><p>Let (c1,c2,c3,c4) represent the constant execution costs.</p><p>T(n) = c1+(n+1)c2+n.c3+n.c4</p><p>The dominant term is the term containing (n).</p><p>Therefore, the time complexity is: O(n).</p><h4><strong>8. Analyzing a Do-While Loop</strong></h4><pre>let i = 0;<br><br>do {<br>    console.log(i);<br>    i++;<br>} while (i &lt; n);</pre><p>A do...while loop is slightly different from a while loop because its condition is checked <strong>after</strong> executing the loop body.</p><p>Here:</p><ul><li>let i = 0 is executed <strong>1 time</strong>.</li><li>console.log(i) is executed <strong>n times</strong>.</li><li>i++ is executed <strong>n times</strong>.</li><li>i &lt; n is executed <strong>n times</strong> because the condition is checked after every iteration.</li></ul><p>Now, let’s form the equation:</p><p>T(n) = c1+nc2+n.c3+n.c4</p><p>The dominant term is the term containing (n).</p><p>Therefore, the time complexity is: O(n).</p><h4>Common Mistakes While Analysing Time Complexity</h4><p>While analysing code, beginners often make a few common mistakes. Let’s understand them so we can avoid incorrect complexity calculations.</p><p><strong>Mistake 1: Assuming Every Nested Loop Is O(n²)</strong></p><p>Not every nested loop has O(n²) complexity.</p><p>Consider:</p><pre>for (let i = 0; i &lt; n; i++) {<br>    for (let j = 1; j &lt; n; j *= 2) {<br>        console.log(i, j);<br>    }<br>}</pre><p>The outer loop executes (n) times, but the inner loop executes only (log n) times.</p><p>Therefore, the complexity is: O(n log n).</p><p>We must always check how many times each loop actually executes instead of assuming every nested loop is O(n²).</p><p><strong>Mistake 2: Counting Statements Instead of Growth</strong></p><p>Consider:</p><pre>console.log(&quot;Hello&quot;);<br>console.log(&quot;World&quot;);<br>console.log(&quot;Welcome&quot;);</pre><p>There are three statements, but all of them execute a fixed number of times regardless of input size.</p><p>Therefore, the complexity is: O(1).</p><p>Time complexity is about how the number of operations grows with input size, not simply how many statements appear in the code.</p><p><strong>Mistake 3: Forgetting the Dominant Term</strong></p><p>Consider: T(n)=n²+5n+10</p><p>The terms (5n) and (10) become less significant compared to (n²) as the input size increases.</p><p>Therefore, we keep only the dominant term: O(n²).</p><p><strong>Mistake 4: Confusing O(log n) with O(n)</strong></p><p>A loop that increments a variable by 1 usually has linear complexity.</p><pre>for (let i = 0; i &lt; n; i++) {<br>    console.log(i);<br>}</pre><p>Its complexity is O(n).</p><p>However, a loop that doubles a variable in every iteration has logarithmic complexity.</p><pre>for (let i = 1; i &lt; n; i *= 2) {<br>    console.log(i);<br>}</pre><p>Its complexity is O(log n).</p><p>The difference is in how quickly the variable changes and how many iterations are required.</p><h4>Conclusion</h4><p>Analysing the time complexity of an algorithm becomes easier when we understand how different programming structures affect the number of operations performed.</p><p>In this article, we explored how to analyse single loops, nested loops, consecutive loops, logarithmic loops, and conditional statements. We also learned how to combine different complexities and identify the dominant term when analysing more complex code.</p><p>The key takeaways are:</p><ul><li>A single loop that executes n times generally has O(n) complexity.</li><li>Nested loops can multiply the number of iterations, resulting in complexities such as O(n²).</li><li>Consecutive loops require us to add their complexities and keep the dominant term.</li><li>Loops that repeatedly double or halve a variable generally have O(log n) complexity.</li><li>Conditional statements require us to analyse the different execution paths, especially when determining best-case and worst-case complexity.</li></ul><p>We also explored common mistakes that can lead to incorrect complexity analysis.</p><p>Ultimately, analysing time complexity is not about counting every line of code or simply looking at the number of loops. It is about understanding how the number of operations grows as the input size increases.</p><p>Once you understand this approach, you can analyse almost any algorithm systematically and make better decisions when choosing or designing efficient solutions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84b65b1a67a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Big O, Big Omega and Big Theta: Understanding Algorithm Complexity Beyond Execution Time]]></title>
            <link>https://medium.com/@krishpatel20217/big-o-big-omega-and-big-theta-understanding-algorithm-complexity-beyond-execution-time-a194b82997c3?source=rss-77898ac3004b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a194b82997c3</guid>
            <category><![CDATA[algorithm-analysis]]></category>
            <category><![CDATA[big-o-notation]]></category>
            <category><![CDATA[time-and-space-complexity]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <dc:creator><![CDATA[Krishpatel]]></dc:creator>
            <pubDate>Tue, 01 Dec 2026 06:28:52 GMT</pubDate>
            <atom:updated>2026-12-01T06:28:52.917Z</atom:updated>
            <content:encoded><![CDATA[<p>Asymptotic notation is a mathematical method used in algorithm analysis to describe how the time or space requirements of an algorithm grow as the input size increases.</p><p>In other words, it help us understand how efficiently an algorithm performs when the input becomes very larger.</p><p>So basically we can compare algorithms without depending on computers processing speed, programming language used, hardware specification, actual execution time.</p><p>Why do we use Asymptotic Notation?</p><p>Suppose we have two algorithms that search for an element in an array of 10,000 elements.</p><ul><li>Algorithm A takes approximately 10,000 operations.</li><li>Algorithm B takes approximately 14 operations.</li></ul><p>Asymptotic notation helps us describe and compare their growth rates as the input size increases.</p><p>Why do we focuses on the input size?</p><p>We focuses on the large input size because efficiency difference between algoriths become more noticable as input grows.</p><p>Let say for 1,000,000 elements in array we perform linear and binary search</p><p>Linear search will do 1,000,000 comparision in worst case senario.</p><p>Binary search will do 20 comparision in worst case senario.</p><p>So binary search require significantly fewer operations. Therfore we focuses on large input size.</p><p><strong>Growth rate</strong>: Growth rate tells us how quickly an algorithm becomes more expensive as the amount of input data increases.</p><p>Different algorithms will require different amounts of work to process these inputs. Growth rate helps us understand and compare that difference.</p><p>Different types of growth rates:</p><p>1. Constant Time — O(1)</p><p>The number of operations remains constant regardless of the input size. The algorithm takes approximately the same amount of time whether the input contains 10 elements or 10,000 elements.</p><p>2. Logarithmic Time — O(log n)</p><p>The number of operations increases very slowly as the input size increases. In this type of algorithm, the problem size is generally reduced by a constant factor at each step, such as dividing it into half.</p><p>3. Linear Time — O(n)</p><p>The number of operations increases proportionally to the input size. If the input size doubles, the number of operations also approximately doubles.</p><p>4. Linearithmic Time — O(n.log n)</p><p>The number of operations grows slightly faster than linear time but significantly slower than quadratic time. It commonly occurs in efficient sorting algorithms.</p><p>5. Quadratic Time — O(n²)</p><p>The number of operations increases proportionally to the square of the input size. It commonly occurs when an algorithm uses two nested loops, each processing the input.</p><p>6. Cubic Time — O(n³)</p><p>The number of operations increases proportionally to the cube of the input size. It commonly occurs when an algorithm uses three nested loops, each processing the input.</p><p>7. Exponential Time — O(2^n)</p><p>The number of operations grows exponentially as the input size increases. In many cases, each additional input element can approximately double the number of operations, making such algorithms inefficient for large inputs.</p><p>8. Factorial Time — O(n!)</p><p>The number of operations grows extremely rapidly as the input size increases. It commonly occurs when an algorithm generates all possible permutations of a given set of elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YX4tYuudLtkOyn7cVHCZWg.png" /></figure><p>Why do we ignore machine-dependent factors?</p><p>Different computers have different processing speed, memory capacities, and hardware configurations. For eg same alogorithm takes 2 sec on computer A and takes 5 sec on computer B, the difference might be caused by their hardware, not the algorithm itself. So thats why Asymptotic analysis focuses on the growth of operations rather then actual execution time.</p><p>There are total 5 asymptotic notation:</p><ul><li>Big-O</li><li>Big Omega</li><li>Big Theta</li><li>Little o</li><li>Little omega</li></ul><h4>Big O Notation</h4><p>Big O notation is used to describe the upper bound of an algorithm’s time or space complexity as the input size increases. It tells us how the resource requirements of an algorithm grow when we give it more input.</p><p>For eg:- if an algorithm takes 10 operations for 10 elements, 100 operations for 100 elements and 1000 operation for 1000 elements then we represent it as O(n) which means number of operations grows proportionally with the input size.</p><p>Mathematical definition of Big O is A function f(n) is said to be O(g(n)) if there exist positive constants c and n0 such that:</p><p>0 ≤ f(n) ≤ c . g(n)</p><p>for all n ≥ n0.</p><ul><li>f(n): The actual function representing the algorithm’s resource usage (number of operations or memory requirements).</li><li>g(n): The comparison function that represents the upper-bound growth rate. It is often chosen based on the dominant term of f(n).</li><li>c is a positive constant.</li><li>n0 a minimum input size after which the inequality holds</li></ul><p>Lets say a algorithms f(n) is f(n)= 3n + 2 we want to prove that f(n) ≤ c . g(n) by substituting the value</p><p>3n + 2 ≤ c . n Let’s choose c = 4 and n0 = 2.</p><p>3n + 2 ≤ 4n where n ≥ 2.</p><p>hence 3n + 2 = O(n) this proves that the function has a linear upper bound.</p><h4>Big Omega (Ω) Notation</h4><p>Big Omega notation is used to describe the <strong>lower bound</strong> of an algorithm’s time or space complexity as the input size increases. It tells us the minimum rate at which the resource requirements of an algorithm grow.</p><p>For eg:- if an algorithm takes at least 10 operations for 10 elements, at least 100 operations for 100 elements and at least 1000 operations for 1000 elements, we can represent this growth as Ω(n), assuming these are guaranteed lower bounds. This means the number of operations grows at least proportionally with the input size.</p><p>Mathematical definition of Big Omega is: A function f(n) is said to be Ω(g(n)) if there exist positive constants c and n0 such that:</p><p>0 ≤ c . g(n) ≤ f(n)</p><p>for all n ≥ n0.</p><ul><li><strong>f(n):</strong> The actual function representing the algorithm’s resource usage (number of operations or memory requirements).</li><li><strong>g(n):</strong> The comparison function that represents the lower-bound growth rate.</li><li><strong>c:</strong> A positive constant.</li><li><strong>n₀:</strong> A minimum input size after which the inequality holds.</li></ul><p>Let’s say an algorithm has the function f(n)=3n+2. We want to prove that f(n) is Ω(n) by satisfying the mathematical definition.</p><p>c . n ≤ 3n + 2</p><p>Let’s choose c=3 and n0=1.</p><p>3n ≤ 3n+2</p><p>This inequality is true for all n ≥ 1.</p><p>Hence,</p><p>3n + 2 = Ω(n)</p><p>This proves that the function has a linear lower bound.</p><h4>Big Theta (Θ) Notation</h4><p>Big Theta notation is used to describe the tight bound of an algorithm’s time or space complexity as the input size increases. It tells us that the resource requirements of an algorithm grow at the same asymptotic rate as a given comparison function.</p><p>For eg:- if an algorithm takes approximately 10 operations for 10 elements, 100 operations for 100 elements and 1000 operations for 1000 elements, we can represent its growth as Θ(n). This means the number of operations grows proportionally with the input size, within constant factors.</p><p>Mathematical definition of Big Theta is: A function f(n) is said to be Θ(g(n)) if there exist positive constants c1, c2 and n0 such that:</p><p>0 ≤ c1 . g(n) ≤ f(n) ≤ c2 . g(n)</p><p>for all n ≥ n0.</p><ul><li>f(n): The actual function representing the algorithm’s resource usage (number of operations or memory requirements).</li><li>g(n): The comparison function that represents the tight-bound growth rate.</li><li>c₁: A positive constant used to establish the lower bound.</li><li>c₂: A positive constant used to establish the upper bound.</li><li>n₀: A minimum input size after which both inequalities hold.</li></ul><p>Let’s say an algorithm has the function f(n)=3n+2. We want to prove that f(n) is Θ(n) by satisfying the mathematical definition.</p><p>c1 . n ≤ 3n + 2 ≤ c2 . n</p><p>Let’s choose c1 = 3, c2 = 4 and n0 = 2.</p><p>First, prove the lower bound:</p><p>3n ≤ 3n+2</p><p>Now, prove the upper bound:</p><p>3n+2 ≤ 4n</p><p>The upper-bound inequality is true for all n ≥ 2, and the lower-bound inequality is also true.</p><p>Therefore, both conditions are satisfied.</p><p>Hence,</p><p>3n + 2 = Θ(n)</p><p>This proves that the function has a tight linear bound.</p><h4>Quick comparision</h4><p>Big O — Upper bound — Growth does not exceed this bound asymptotically.</p><p>Big Omega —Lower bound — Growth is at least this bound asymptotically.</p><p>Big Theta — Tight bound — Growth is bounded both above and below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*c_Q4GGId57a47JrgTaJPiQ.png" /></figure><p><strong>Myth: Is Big O Notation the Same as Worst-Case Complexity?</strong></p><p>Big O notation describes the asymptotic upper bound of an algorithm’s resource usage, whereas worst-case analysis describes the situation in which an algorithm performs the maximum number of operations for a given input size.</p><p>Let’s understand this with an example.</p><p>Suppose we have an array containing 1,000 elements and we want to search for a particular number using Linear Search.</p><p>There are three possible situations:</p><ul><li>Best Case: The element is found at the first position, so the algorithm performs only one comparison.</li><li>Average Case: The element is somewhere in the middle, so the algorithm performs approximately 500 comparisons.</li><li>Worst Case: The element is at the last position or is not present in the array, so the algorithm may perform all 1,000 comparisons.</li></ul><p>For Linear Search, the worst-case time complexity is \(O(n)\).</p><p>Here, we use Big O to express the upper bound of the worst-case number of operations.</p><p>But does this mean Big O always represents the worst case? No.</p><p>Big O is a mathematical notation that represents an upper bound. We can use it to describe the best-case, average-case or worst-case function, depending on which function we are analysing.</p><p>For example, Linear Search has:</p><ul><li>Best-case complexity: O(1)</li><li>Average-case complexity: O(n)</li><li>Worst-case complexity: O(n)</li></ul><p>Therefore, Big O itself does not mean worst case. It is simply the notation we commonly use to express the upper bound of an algorithm’s worst-case performance.</p><p>The key difference:</p><ul><li>Worst Case tells us <em>which input condition we are analysing</em>.</li><li>Big O tells us <em>how the resource requirements grow asymptotically under that condition</em>.</li></ul><p>Understanding this difference helps avoid one of the most common misconceptions in algorithm analysis.</p><h4><strong>Time Complexity Analysis of Linear Search</strong></h4><p>Let’s take a Linear Search algorithm and calculate its time complexity step by step.</p><pre>function linearSearch(arr, target) {<br>    for (let i = 0; i &lt; arr.length; i++) {<br>        if (arr[i] === target) {<br>            return i;<br>        }<br>    }<br>    return -1;<br>}</pre><p>To calculate time complexity, we count how many times each statement executes.</p><p>let i = 0 is executed 1 time.</p><p>i &lt; arr.lengthis executed n+1 times.</p><p>i++is executed n times.</p><p>arr[i] === targetis executed n times.</p><p>return -1is executed 1 time.</p><p><strong>Form a time complexity equation:</strong></p><p>Let:</p><ul><li>c1 = cost of initialization.</li><li>c2 = cost of checking the loop condition.</li><li>c3 = cost of incrementing the variable.</li><li>c4 = cost of comparing the array element.</li><li>c5 = cost of returning -1.</li></ul><p>Now multiply each statement’s cost by its number of executions.</p><p>T(n) = c1 + c2.(n+1) + c3.n + c4.n + c5</p><p>solving further</p><p>T(n) = (c2 + c3 + c4) . n + (c1 + c2 + c5)</p><p>Let the constants be combined into a and b.</p><p>T(n) = a.n + b</p><p><strong>Determining time complexity:</strong></p><p>step 1 : Ignore constant factors.</p><p>T(n) = n + b</p><p>Step 2: Ignore lower-order terms.</p><p>T(n) = n</p><p>Step 3: Apply Big O notation.</p><p>O(n)</p><p>This means Linear Search has a linear time complexity because the number of operations grows proportionally with the input size.</p><p>so for</p><ul><li>Best case time complexity is O(1)</li><li>Average case time complexity is O(n)</li><li>Worst case time complexity is O(n)</li></ul><h4>Time Complexity Analysis of Binary Search</h4><p>Let’s take a Binary Search algorithm and calculate its time complexity step by step.</p><p><strong>Important:</strong> Binary Search works only on a <strong>sorted array</strong> because it repeatedly divides the search space into half.</p><pre>function binarySearch(arr, target) {<br>    let low = 0;<br>    let high = arr.length - 1;<br><br>    while (low &lt;= high) {<br>        let mid = Math.floor((low + high) / 2);<br><br>        if (arr[mid] === target) {<br>            return mid;<br>        }<br><br>        if (arr[mid] &lt; target) {<br>            low = mid + 1;<br>        } else {<br>            high = mid - 1;<br>        }<br>    }<br><br>    return -1;<br>}</pre><p>To calculate time complexity, we count how many times each statement executes.</p><p>Let’s assume the target element is <strong>not present in the array</strong>. This represents the worst case because the algorithm continues dividing the search space until no elements remain.</p><ul><li>let low = 0 is executed 1 time.</li><li>let high = arr.length - 1 is executed 1 time.</li><li>low &lt;= high is checked approximately log n + 1 times.</li><li>let mid = Math.floor((low + high) / 2) is executed approximately log n times.</li><li>arr[mid] === target is executed approximately log n times.</li><li>arr[mid] &lt; target is executed approximately log n times.</li><li>low = mid + 1 or high = mid - 1 is executed approximately log n times in total.</li><li>return -1 is executed 1 time.</li></ul><p><strong>Form a time complexity equation:</strong></p><p>Let:</p><ul><li>c1 = cost of initializing low.</li><li>c2 = cost of initializing high.</li><li>c3 = cost of checking the while-loop condition.</li><li>c4 = cost of calculating the middle index.</li><li>c5 = cost of comparing the middle element with the target.</li><li>c6 = cost of updating low or high.</li><li>c7 = cost of returning -1.</li></ul><p>Now multiply each statement’s cost by its number of executions.</p><p>Let k = log n.</p><p>T(n) = c1 + c2 + c3(k + 1) + c4.k + c5.k + c6.k + c7</p><p>Solving further will give T(n) = a log n + b</p><p><strong>Determining time complexity:</strong></p><p>step 1 : Ignore constant factors.</p><p>T(n) = log n + b</p><p>Step 2: Ignore lower-order terms.</p><p>T(n) = log n</p><p>Step 3: Apply Big O notation.</p><p>O(log n)</p><p>This means Binary Search has logarithmic time complexity because it divides the search space into half after every iteration. As a result, even when the input size increases significantly, the number of operations increases very slowly.</p><p>so for</p><ul><li>Best case time complexity is O(1)</li><li>Average case time complexity is O(log n)</li><li>Worst case time complexity is O(log n)</li></ul><p><strong>Conclusion</strong></p><p>Algorithm analysis is not just about calculating how much time an algorithm takes to execute; it is about understanding how efficiently an algorithm performs as the input size increases.</p><p>Through asymptotic notation, we can describe the growth of an algorithm’s time and space requirements without depending on hardware specifications, programming languages, or processing speeds.</p><p>We explored three major asymptotic notations: Big O, Big Omega, and Big Theta, which help us understand the upper bound, lower bound, and tight bound of an algorithm’s complexity.</p><p>We also analysed Linear Search and Binary Search to understand how time complexity is calculated mathematically.</p><p><strong>Ultimately, the goal of algorithm analysis is not just to make an algorithm work, but to make it work efficiently, especially when dealing with large amounts of data.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a194b82997c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Algorithms: The Foundation of Data Structures and Algorithm Analysis]]></title>
            <link>https://medium.com/@krishpatel20217/understanding-algorithms-the-foundation-of-data-structures-and-algorithm-analysis-28b52d9c3f5c?source=rss-77898ac3004b------2</link>
            <guid isPermaLink="false">https://medium.com/p/28b52d9c3f5c</guid>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[algorithm-analysis]]></category>
            <dc:creator><![CDATA[Krishpatel]]></dc:creator>
            <pubDate>Mon, 30 Nov 2026 07:55:31 GMT</pubDate>
            <atom:updated>2026-11-30T07:55:31.599Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>What is an algorithm?</strong></h3><p>An algorithm is a step by step procedure which defines a set of instruction to be executed in a certain order to get the desire output. or in other words it is a finite, step by step set of unambiguous instructions used to process data stored in data structure to solve a specific problem.</p><p>so now the question might arise why do we need an algorithm ?</p><p>We need algorithms to give computers clear, step-by-step instructions that solve problems quickly, accurately, and at scale. Without them, software cannot reliably process data, make decisions, or handle complex tasks.</p><p>In everyday life, algorithms are step-by-step routines used by both people and technology to solve problems and make decisions.</p><p>In terms of computer science algorithm are designed in such a way that its should be correct and effecient.</p><p>well there might be confusion between algorithm and program, an algorithm is a language-independent, step-by-step blueprint for solving a problem, while a program is the actual code implementation of that blueprint written in a specific programming language.</p><p><strong>Real-world examples :</strong></p><ul><li>Apps like Google Maps use pathfinding algorithms (such as Dijkstra’s or A*) combined with live traffic data to calculate the fastest route from home to work.</li><li>Email providers and banks use pattern-recognition algorithms to block junk mail or flag unusual card transactions automatically.</li><li>Apps like UPI platforms or Uber use matching and routing algorithms to verify transfers instantly or pair you with the nearest available driver.</li></ul><p><strong>Categories of algorithms:</strong> searching, sorting, inserting, updating, deleting.</p><p><strong>Characteristics of a algorithms :</strong></p><ul><li>Input : An algorithm should have 0 or more well defined inputs.</li><li>Output : An algorithm should have 1 or more well defined outputs.</li><li>Unambiguous : Algorithm should be clear and unambiguous. Each of its step and their inputs/outputs should be clear and must lead to only one meaning.</li><li>Finiteness : Algorithm must terminate after a finite number of steps.</li><li>Effectiveness : Every step must be simple, practical, and executable using available resources and technology.</li><li>Language Independent : An algorithm should have step by step direction, which should be independent of any programming code.</li></ul><p><strong>what makes an algorithm good </strong>:</p><ul><li>Correctness : Proving that the steps will always produce the right output for every valid input and eventually finish.</li><li>Efficiency : Efficiency measures how well an algorithm uses time and space to reach the solution.</li><li>Readability : Readability means a algorithm should be clear, well structured and easy for other human to understand, debug and modify.</li><li>Scalability : Scalability measures how gracefully an algorithm’s performance holds up when the <strong>input size grows from tiny to massive.</strong></li></ul><p><strong>What is algorithm analysis ?</strong></p><p>Algorithm analysis is a process of measuring how much time and memory an algorithm needs to run, especially as the input size grows.</p><p><strong>Why do we analyse algorithms?</strong></p><p>We analyze algorithms to predict their performance and resource usage before investing time in coding, ensuring that software remains fast, reliable, and scalable in the real world.</p><p><strong>Why is correct output not enough?</strong></p><ul><li>A weather forecast algorithm that takes 48 hours to predict tomorrow’s weather is completely useless, even if it is 100% accurate. Similarly, a navigation app must reroute in milliseconds, not minutes.</li><li>An algorithm that gives the right answer by loading 500 GB of data into memory will crash a smartphone that only has 8 GB of RAM.</li></ul><p>So having a correct output is not good enough it should be efficient with time and space.</p><p><strong>Why can two algorithms solve the same problem but have different performance?</strong></p><p>Lets say there are 2 person going to mumbai obe is going via flight and one is going via train, and as you already know that the person going via plane will reach first as compare to person via train. so same way if one algorithm uses 10ms to complete the task and one uses 1m to complete, even though they gives same output but the first one will be effecient why? because it uses less time. so thats the reason why choosing a way to solve a problem is more important.</p><p><strong>What are time and space resources?</strong></p><ul><li>Time : How long the processor takes to execute all the algorithm’s basic operations.</li><li>Space : How much temporary workspace the computer needs to hold variables, data structures, and function calls while the algorithm is running.</li></ul><p><strong>Why do we analyse algorithms before implementing them?</strong></p><p>we analyse algorithms before implementing it in order to save</p><ul><li>human effort like writting the code , debug the error.</li><li>save computational resources.</li><li>reveal edge case failure early.</li></ul><h3><strong>Time Complexity</strong></h3><p>Time complexity is not a measure of how many seconds an algorithm takes to run — it is a measure of how the number of basic operations grows as the input size increases.</p><p>Well you will often seen input size n , what exacty is input size n ?</p><p>Input size (n) is a measure of how much data an algorithm is given to process and As input size (n) grows, the number of operations increases according to the specific strategy (growth rate) of the algorithm.</p><p>There is a difference between actual execution time and time complexity. Actual execution time is the real-world clock time (in milliseconds or seconds) a program takes to run on a specific machine, whereas time complexity is a theoretical measure of how the number of operations grows as the input size (n) increases.</p><p>the question might arise like Why do we count operations instead of measuring seconds?</p><p>We count operations instead of measuring seconds because seconds change depending on the computer, programming language, and background workload, whereas the number of operations stays constant for a given algorithm.</p><h3><strong>Space Complexity</strong></h3><p>Space complexity is the total amount of computer memory (RAM) an algorithm needs to run to completion, expressed as a function of the input size (n).</p><p>There are two type of space input space and auxilary space. Input space is the memory required simply to store the original data given to the algorithm, whereas auxiliary space is the temporary extra memory the algorithm creates and uses while solving the problem.</p><p>Extra memory (also called auxiliary space) is any additional RAM an algorithm allocates and uses on top of the memory already occupied by the original input.</p><p>okay so lets see it with a example</p><p>In constant extra space, instead of creating a new array, we swap elements directly inside the original array using two index pointers (left and right).</p><pre>function reverseInPlace(arr) {<br>  let left = 0;                  // 1 variable<br>  let right = arr.length - 1;    // 1 variable<br><br>  while (left &lt; right) {<br>    // Swap values directly inside the original array<br>    let temp = arr[left];        // 1 variable<br>    arr[left] = arr[right];<br>    arr[right] = temp;<br><br>    left++;<br>    right--;<br>  }<br><br>  return arr;<br>}<br><br>const nums = [10, 20, 30, 40, 50];<br>console.log(reverseInPlace(nums)); // [50, 40, 30, 20, 10]</pre><p>While in Linear Extra Space we leave the original array untouched and allocate a brand-new array to store the reversed elements.</p><pre>function reverseWithNewArray(arr) {<br>  const reversed = []; // New array that will grow to size &#39;n&#39;<br><br>  for (let i = arr.length - 1; i &gt;= 0; i--) {<br>    reversed.push(arr[i]); // Allocates memory for every single item<br>  }<br><br>  return reversed;<br>}<br><br>const nums =;<br>console.log(reverseWithNewArray(nums)); // [50, 40, 30, 20, 10]</pre><p>Well note this sometimes an algorithm with better time complexity requires more memory because it stores pre-calculated results or organized lookups in RAM so the computer doesn’t have to recalculate or re-scan data repeatedly.</p><h3><strong>Cases used in algorithm analysis</strong></h3><p>There are three cases used in algorithm analysis which are</p><ul><li>Best-case analysis</li><li>Average-case analysis</li><li>Worst-case analysis</li></ul><p>Best-case analysis measures the <strong>minimum number of operations</strong> an algorithm takes when given the most favorable possible input of size n.</p><p>Average-case analysis calculates the <strong>expected number of operations</strong> across all possible random inputs of size n, assuming typical real-world data distribution.</p><p>Worst-case analysis measures the <strong>maximum number of operations</strong> an algorithm could ever take on the hardest, most unfavorable input of size n.</p><p>Worst-case analysis is commonly used because it gives an absolute performance guarantee: your algorithm will never run slower than this upper limit, no matter how bad the input data is.</p><p>Lets understand all three cases with a example of linear search</p><p>Suppose we have an array of <strong>n = 8</strong> numbers:<br>const arr = [14, 27, 8, 42, 19, 3, 55, 11];</p><pre>function linearSearch(arr, target) {<br>  for (let i = 0; i &lt; arr.length; i++) {<br>    if (arr[i] === target) {<br>      return i; // Target found at index i<br>    }<br>  }<br>  return -1; // Target not found<br>}</pre><p>Walking Through All Three Cases (n = 8)</p><p>1. Best Case — Target Is the Very First Item</p><ul><li>Search for: target = 14 (located at index 0)</li><li>What happens: The loop checks arr[0] === 14 on its very first step, finds a match immediately, and exits.</li><li>Comparisons made: 1</li><li>Complexity: Ω(1) / O(1) (Constant time—even if the array had 1,000,000 items, finding the first item still takes just 1 step).</li></ul><p>2. Average Case — Target Is Somewhere in the Middle</p><ul><li>Search for: target = 19 (located at index 4)</li><li>What happens: The loop checks 14, 27, 8, 42, and finally matches 19 on the 5th check. Across all possible random positions (1, 2, 3, ..., n), the expected number of checks is roughly half the list: (n + 1) / 2.</li><li>Comparisons made: 5 (for n = 8, average is (8 + 1) / 2 = 4.5 steps)</li><li>Complexity: Θ(n) / O(n) (Linear time—because we drop constant multipliers like / 2, half of n still scales linearly with n).</li></ul><p>3. Worst Case — Target Is at the Very End (or Missing)</p><ul><li>Search for: target = 11 (at the last index 7) OR target = 99 (not in the array at all)</li><li>What happens: The loop is forced to check every single element from index 0 all the way to index 7 before either finding 11 on the final step or returning -1.</li><li>Comparisons made: 8 (n comparisons)</li><li>Complexity: O(n) (Linear time—every single item had to be inspected).</li></ul><h3><strong>Introduction to Asymptotic analysis</strong></h3><p>asymptotic means describing how a function or algorithm behaves as its input size (n) grows infinitely large—approaching infinity.</p><p><strong>Asymptotic analysis focuses on the growth rate and ignores constant factors and lower-order terms when considering sufficiently large input sizes.</strong></p><p>For example:</p><p>T(n)=3n²+5n+10</p><p>The dominant term is n², so the growth rate is Theta(n²).</p><p>We study algorithms as input size <strong>(</strong>n) grows because small datasets hide bad designs—almost any algorithm runs fast on 10 items, but real-world software must survive millions or billions of items without crashing.</p><p>How does asymptotic analysis remove machine-dependent factors?</p><p>Asymptotic analysis removes machine-dependent factors by measuring an algorithm’s rate of growth relative to input size (n) rather than measuring exact execution time in seconds. Here growth rate means how quickly the number of operations increases as the input size (n) gets larger.</p><p><strong>Big O (</strong><strong>O), Big Omega (</strong><strong>Ω), and Big Theta (</strong>Θ) are the three standard asymptotic notations used to describe the upper, lower, and tight growth bounds of an algorithm as the input size (n) grows very large. we will study this in detail later.</p><h4><strong>Lets study comparision between Linear search and Binary search</strong></h4><p>Linear search : Linear Search is the simplest searching technique. It starts from the first element and checks each element sequentially until the target value is found or the array ends.</p><p>Suppose we have an array:</p><p>[10, 20, 30, 40, 50, 60, ...]</p><p>We want to find the number 50.</p><p>The algorithm checks:</p><ol><li>Is 10 equal to 50? No.</li><li>Is 20 equal to 50? No.</li><li>Is 30 equal to 50? No.</li><li>Is 40 equal to 50? No.</li><li>Is 50 equal to 50? Yes!</li></ol><p>The target is found after 5 comparisons.</p><p>Time Complexity:</p><ul><li>Best Case: O(1) — The target is the first element.</li><li>Average Case: O(n) — The algorithm checks approximately half the elements.</li><li>Worst Case: O(n) — The target is the last element or does not exist.</li></ul><p>For an array of 10,000 elements, Linear Search may require up to 10,000 comparisons.</p><p>Binary Search : Binary Search uses a more efficient approach. Instead of checking every element, it repeatedly divides the search space into two halves. However, there is one important prerequisite: <strong>The array must be sorted.</strong></p><p>Let’s use the same example:</p><p>[10, 20, 30, 40, 50, 60, 70, 80, 90]</p><p>We want to find 80.</p><p>Step 1: Check the middle element (50).</p><p>Since 80 is greater than 50, we can eliminate the left half.</p><p>Step 2: Search the remaining right half:</p><p>[60, 70, 80, 90]</p><p>Check the middle element. If it is 70, we know that 80 must be on the right side.</p><p>Step 3: Search the remaining elements:</p><p>[80, 90]</p><p>We find 80!</p><p>Notice that instead of checking every element, Binary Search eliminates approximately half of the remaining elements in each step.</p><p>Time Complexity:</p><ul><li>Best Case: O(1) — The target is found at the middle in the first comparison.</li><li>Average Case: O(log n).</li><li>Worst Case: O(log n) — The search space keeps getting divided until the target is found or no elements remain.</li></ul><p>For an array of 10,000 elements, Binary Search requires at most approximately 14 comparisons.</p><p>Both Linear Search and Binary Search solve the same problem, but they approach it differently. Linear Search is simple and works without sorting, making it useful for small or unsorted datasets. Binary Search is significantly faster for large, sorted datasets because it reduces the search space with every iteration. The important lesson is that choosing the right algorithm is not just about getting the correct output. It is also about getting that output efficiently, especially as the size of the input grows.</p><p>So overall algorithm analysis is essential for programmers because it turns coding from guesswork into engineering — allowing you to write software that stays fast, scalable, and reliable when real-world data grows large.</p><p>DSA (Data Structures and Algorithms) teaches you <em>what</em> tools exist and <em>how</em> to implement them in code, while DAA (Design and Analysis of Algorithms) teaches you <em>why</em> those algorithms work, <em>how</em> to invent new ones, and <em>how</em> to mathematically prove their efficiency.</p><p>In the next article we will learn asymptotic notations in detail……</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28b52d9c3f5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Javascript Works]]></title>
            <link>https://medium.com/@krishpatel20217/how-javascript-works-225f7a142b62?source=rss-77898ac3004b------2</link>
            <guid isPermaLink="false">https://medium.com/p/225f7a142b62</guid>
            <category><![CDATA[scope-in-javascript]]></category>
            <category><![CDATA[closures-in-javascript]]></category>
            <category><![CDATA[hoisting-in-javascript]]></category>
            <category><![CDATA[javascript-call-stack]]></category>
            <category><![CDATA[execution-context]]></category>
            <dc:creator><![CDATA[Krishpatel]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 16:35:56 GMT</pubDate>
            <atom:updated>2026-10-26T16:41:38.478Z</atom:updated>
            <content:encoded><![CDATA[<p>Javascript is a single threaded synchronous programming language. yes you might get confuse that we can perform a async operations then how can it be a scnchronous programming language so answer to this is javascript itself is a scnchronous programming language , (browser and nodejs) enviornment is the reason that helps the javascript to do async operations.</p><p>When we write JavaScript code and run it in Chrome, the browser uses the V8 engine to execute it. V8 parses the code and uses an interpreter to execute it, while its JIT compilation mechanisms can compile and optimize frequently executed code into machine code. The interpreter and compilers are components of the V8 JavaScript engine. The browser provides the runtime environment around V8, including APIs such as the DOM, timers, and networking. These browser APIs, along with the event loop and task queues, enable JavaScript to handle asynchronous operations without blocking the execution of other JavaScript code while waiting for certain operations to complete.</p><p>so this is what the a complete picture looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*vUSSAK77Z8MMj_a740FItA.png" /></figure><p>so if this is the code :</p><pre>console.log(&quot;Start&quot;);<br><br>setTimeout(() =&gt; {<br> console.log(&quot;Timer finished&quot;);<br>}, 2000);<br><br>console.log(&quot;End&quot;);</pre><p>When the JavaScript code starts executing, V8 executes console.log(&quot;Start&quot;), so &quot;Start&quot; is printed first.</p><p>Next, V8 executes the setTimeout() call. The browser&#39;s timer API handles the timer and starts counting down for 2 seconds. V8 does not wait for those 2 seconds; it continues executing the next line, console.log(&quot;End&quot;), so &quot;End&quot; is printed immediately afterward.</p><p>Once the timer expires, the browser makes the timer callback eligible to run by scheduling it as a task. The event loop coordinates when that task can be processed. When the JavaScript execution context is available, V8 executes the callback, printing &quot;Timer finished&quot;.</p><p>Therefore, the output is &quot;Start&quot;, &quot;End&quot;, and then &quot;Timer finished&quot;.</p><h3>Execution context</h3><p>An <strong>Execution Context (EC)</strong> is the environment in which JavaScript code is evaluated and executed. It keeps track of the information needed to execute the code, including variables &amp; functions.</p><p>There are two important types of execution contexts that we commonly learn about: the Global Execution Context (GEC) and the Function Execution Context (FEC).</p><ol><li><strong>Global Execution Context</strong></li></ol><p>GEC is automatically created at the moment we run our program. there is only one GEC for a whole script file.</p><p>2. <strong>Function Execution Context</strong></p><p>A FEC is created every time a function is called. When a function is finished a FEC is destroyed.</p><p>There are two phases of execution context.</p><ol><li><strong>Creation Phase </strong>(memory creation)</li><li><strong>Execution Phase </strong>(code execution)</li></ol><p>In creation phase js code is scaned and memory allocation and memory setup is done, like all var variables get memory and are set as undefined.</p><p>And in execution phase the code run line by line assigning real values to variable expressions are evaluated and function calls are made.</p><p>so lets understand by taking a example</p><pre>var x = 10;<br><br>function greet() {<br>  console.log(&quot;Hello&quot;);<br>}<br><br>greet();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MBb4N5jNE01nAwhRRrHnJw.png" /></figure><ul><li>The GEC is created.</li><li>During creation, x is initialized to undefined, and the greet function declaration is registered.</li><li>During execution, x is assigned 10.</li><li>greet() is invoked, creating an FEC.</li><li>console.log(&quot;Hello&quot;) executes and prints Hello.</li><li>The function returns undefined.</li><li>The global script finishes executing.</li></ul><h3>Call Stack</h3><p>The call stack is a data structure used by the JavaScript engine to keep track of which execution contexts are currently active. When a function is called, its execution context is pushed onto the stack. When the function finishes, its context is popped off.</p><ul><li>Initially, the call stack is empty. Stack: []</li><li>The GEC is created and pushed onto the call stack. Stack: [GEC]</li><li>The GEC executes the global code. x is assigned 10, and the greet function declaration is available. The GEC remains on the stack. Stack: [GEC]</li><li>greet() is called, so its FEC is pushed onto the stack. Stack: [GEC, FEC]</li><li>The FEC executes console.log(&quot;Hello&quot;). Hello is printed. Once greet() finishes, its FEC is popped off the stack. Stack: [GEC]</li><li>The global script finishes. The GEC is removed from the call stack, leaving it empty. Stack: []</li></ul><p><strong>Stack overflow</strong> occurs when the call stack exceeds its available capacity, usually because too many function calls are active at the same time.</p><p>for ex:</p><pre>function greet() {<br>    greet();<br>}<br><br>greet();</pre><h3><strong>Hosting</strong></h3><p>Hoisting is JavaScript’s behavior of processing variable and function declarations before executing the code in their respective scopes.</p><h4>Example with var</h4><pre>console.log(a);<br>var a = 10;</pre><p><strong>Output:</strong></p><pre>undefined</pre><p>As we know, when JavaScript starts executing a script, the Global Execution Context (GEC) is created. During the creation phase, the variable a is registered and initialized with undefined because it is declared using var.</p><p>After that, during the code execution phase, JavaScript executes console.log(a) before reaching the assignment a = 10. Since a currently holds the value undefined, the output is undefined. Later, JavaScript executes a = 10 and assigns the value 10 to the variable.</p><h4>Example with let</h4><pre>console.log(a);<br>let a = 10;</pre><p><strong>Output:</strong></p><pre>ReferenceError</pre><p>Unlike var, a let variable is not initialized with undefined during the creation phase. It remains uninitialized in the Temporal Dead Zone (TDZ) until execution reaches its declaration. Therefore, accessing a before its declaration is evaluated results in a ReferenceError.</p><p>The same principle applies to const, which also remains uninitialized in the TDZ until its declaration is evaluated.</p><h3><strong>Function declaration vs functionn expression</strong></h3><p><strong>Function declaration → fully hoisted.</strong> You can call it before it’s defined:</p><pre>sayHi(); // ✅ &quot;Hi&quot; — works<br>function sayHi() {<br>  console.log(&quot;Hi&quot;);<br>}</pre><p><strong>Function expression → follows the variable’s hoisting rules.</strong> The variable is hoisted, but the function is <em>not</em> assigned until that line runs:</p><pre>sayBye(); // ❌ TypeError: sayBye is not a function<br>var sayBye = function () {<br>  console.log(&quot;Bye&quot;);<br>};</pre><p>Here sayBye is hoisted as undefined (because of var), so calling undefined() throws a TypeError. With let/const it would throw a ReferenceError (TDZ) instead.</p><h3><strong>Scope</strong></h3><p>In JavaScript, <strong>scope defines where a variable can be accessed in your code.</strong> It determines which parts of your program can use a particular variable.</p><p>JavaScript has four important scope concepts to understand: global scope, function scope, block scope, and lexical scope.</p><h4>1. Global Scope</h4><p>A variable declared outside any function or block has global scope. It can be accessed from different parts of the code, including inside functions.</p><pre>let appName = &quot;MyApp&quot;;</pre><pre>function show() {<br>  console.log(appName);<br>}</pre><pre>show(); // MyApp<br>console.log(appName); // MyApp</pre><p>Here, appName is declared outside the function, so both the function and the global code can access it.</p><h4>2. Function Scope</h4><p>A variable declared inside a function is accessible only within that function and its nested scopes.</p><p>Variables declared using var, let, or const inside a function are all limited to that function.</p><pre>function test() {<br>  var secret = 42;<br>  let username = &quot;Sara&quot;;<br>  const age = 21;</pre><pre>  console.log(secret);   // 42<br>  console.log(username); // Sara<br>  console.log(age);      // 21<br>}</pre><pre>test();</pre><pre>console.log(secret); // ReferenceError</pre><p>The variables are available inside test(), but they cannot be accessed from outside it.</p><h4>3. Block Scope</h4><p>A block is a section of code enclosed in curly braces { }, such as the body of an if statement, a loop, or a standalone block.</p><p>Variables declared with let and const are <strong>block-scoped</strong>, meaning they are accessible only within the block where they are declared.</p><p>However, var is not block-scoped. It ignores ordinary block boundaries, although it remains limited to its enclosing function if one exists.</p><pre>{<br>  let a = 1;<br>  const c = 3;<br>  var b = 2;<br>}</pre><pre>console.log(b); // 2<br>console.log(a); // ReferenceError<br>console.log(c); // ReferenceError</pre><p>Here, a and c remain inside the block, while b can be accessed outside it because it was declared using var.</p><p><strong>Remember:</strong> let and const respect block boundaries; var does not.</p><h4>4. Lexical Scope</h4><p>The word <em>lexical</em> refers to where code is written in the source code.</p><p><strong>Lexical scope means that a function’s access to variables is determined by where that function is defined, not where it is called.</strong></p><p>Consider this example:</p><pre>function outer() {<br>  let name = &quot;Sara&quot;;</pre><pre>  function inner() {<br>    console.log(name);<br>  }</pre><pre>  inner();<br>}</pre><pre>outer(); // Sara</pre><p>The inner() function is defined inside outer(). Because of this nesting, it can access the name variable declared in outer().</p><p>This is lexical scoping: the inner function can access variables from its surrounding lexical scope.</p><p>Lexical scope is also the foundation of <strong>closures</strong>, which allow a function to retain access to variables from its surrounding scope even after the outer function has finished executing.</p><h3>Scope chaining</h3><p>when we use variable , js looks for it in order : current scope , outer scope , outer scope till global scope</p><pre>let a = 10;<br>function outer() {<br>  let b = 20;<br>  function inner() {<br>    let c = 30;<br>    console.log(a, b, c); // 10 20 30<br>  }<br>  inner();<br>}<br>outer();</pre><h3>Closures</h3><p>A closure is a function that remembers and can access variables from its lexical environment, even after the outer function has finished executing.</p><pre>function outer() {<br>  let name = &quot;Sara&quot;;<br><br>  function inner() {<br>    console.log(name);<br>  }<br><br>  return inner;<br>}<br><br>const myFunc = outer();<br>myFunc(); // Sara</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=225f7a142b62" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>