<?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 Yuda Wiliperdana on Medium]]></title>
        <description><![CDATA[Stories by Yuda Wiliperdana on Medium]]></description>
        <link>https://medium.com/@wiliperdana?source=rss-0f8d6f13cc97------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Yuda Wiliperdana on Medium</title>
            <link>https://medium.com/@wiliperdana?source=rss-0f8d6f13cc97------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 18:16:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wiliperdana/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[SOLID Principle: Technical Deep Dive]]></title>
            <link>https://medium.com/@wiliperdana/solid-principle-technical-deep-dive-5888065a82c6?source=rss-0f8d6f13cc97------2</link>
            <guid isPermaLink="false">https://medium.com/p/5888065a82c6</guid>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Yuda Wiliperdana]]></dc:creator>
            <pubDate>Tue, 29 Apr 2025 09:06:13 GMT</pubDate>
            <atom:updated>2025-05-22T12:21:34.655Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OzwARbvHUg1RlZ7LYyLCrg.png" /><figcaption>SOLID Principle</figcaption></figure><p>In the domain of software engineering, maintainability, scalability, and readability are critical aspects of long-lived applications. One of the most effective ways to achieve these qualities is by following proven design principles. Among these, the SOLID principles stand out as a cornerstone of object-oriented design. Introduced by Robert C. Martin (Uncle Bob), SOLID is an acronym that represents five foundational principles intended to guide developers in crafting robust and scalable software architecture.</p><p>Applied correctly, SOLID principles help reduce coupling, increase cohesion, and enable code that is easier to test and extend. This article delves into each principle — <strong>Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion</strong> — with clear explanations and advanced ASP.NET Core code examples. The goal is to equip developers with a deep, technical understanding of how these principles can be implemented in real-world web applications.</p><h3>1. Single Responsibility Principle (SRP)</h3><p><strong>Definition</strong>: A class should have only one reason to change, meaning it should encapsulate only one responsibility or functionality.</p><p>The essence of SRP is about <strong>separation of concerns</strong>. If a class is handling more than one job, it becomes harder to modify and maintain. In ASP.NET Core, this principle often translates into separating business logic, data access, and controller actions.</p><p><strong>Example</strong>: Let’s consider a reporting service that violates SRP by mixing data retrieval and email sending logic:</p><pre>// BAD: Violates SRP<br>public class ReportService<br>{<br>    public string GenerateReport()<br>    {<br>        // Generate report logic<br>        return &quot;Report content&quot;;<br>    }<br><br>    public void EmailReport(string email, string content)<br>    {<br>        // Email sending logic<br>    }<br>}</pre><p>The code above <strong>violates the Single Responsibility Principle</strong> because the ReportService class has <strong>more than one responsibility</strong>:</p><ol><li><strong>Generating the report</strong> (GenerateReport()).</li><li><strong>Sending the report via email</strong> (EmailReport()).</li></ol><p>When a class handles multiple responsibilities, a <strong>change in one area</strong> (e.g., modifying the email sending logic) can <strong>affect the other</strong> (report generation), which increases the risk of bugs and makes the code <strong>harder to maintain and test</strong>.</p><p>Refactored Using SRP:</p><pre>public class ReportGenerator<br>{<br>    public string GenerateReport()<br>    {<br>        return &quot;Generated Report Content&quot;;<br>    }<br>}<br><br>public class EmailService<br>{<br>    public void SendEmail(string to, string content)<br>    {<br>        // Send email logic<br>    }<br>}</pre><p>In this refactored version, responsibilities are <strong>clearly separated into distinct classes</strong>:</p><ul><li>ReportGenerator is only responsible for <strong>creating the report</strong>.</li><li>EmailService is only responsible for <strong>sending emails</strong>.</li></ul><p>With this separation:</p><ul><li>Changes in the email logic won’t affect the report generation logic.</li><li>Each class is now <strong>more modular, easier to test, and easier to maintain</strong>.</li></ul><p>Controller:</p><pre>public class ReportController : ControllerBase<br>{<br>    private readonly ReportGenerator _generator;<br>    private readonly EmailService _emailService;<br><br>    public ReportController(ReportGenerator generator, EmailService emailService)<br>    {<br>        _generator = generator;<br>        _emailService = emailService;<br>    }<br><br>    [HttpPost(&quot;send-report&quot;)]<br>    public IActionResult SendReport(string email)<br>    {<br>        var content = _generator.GenerateReport();<br>        _emailService.SendEmail(email, content);<br>        return Ok(&quot;Report sent.&quot;);<br>    }<br>}</pre><p>The ReportController acts as an <strong>orchestrator</strong>, coordinating the two responsibilities without violating SRP. It does not handle the internal logic of report generation or email sending directly, but instead delegates these to the appropriate services via <strong>dependency injection</strong>.</p><p>This demonstrates a <strong>full SRP-compliant implementation across application layers</strong>, where each component has a <strong>single reason to change</strong>.</p><h3>2. Open/Closed Principle (OCP)</h3><p><strong>Definition</strong>: Software entities (classes, modules, functions) should be open for extension but closed for modification.</p><p>Instead of altering existing logic when new behavior is needed, new functionality should be added via abstraction. This is often accomplished using <strong>polymorphism</strong> and <strong>strategy patterns</strong>.</p><p><strong>Use Case</strong>: Let’s implement an extensible discount service.</p><pre>public interface IDiscountStrategy<br>{<br>    decimal ApplyDiscount(decimal total);<br>}<br><br>public class NoDiscount : IDiscountStrategy<br>{<br>    public decimal ApplyDiscount(decimal total) =&gt; total;<br>}<br><br>public class PercentageDiscount : IDiscountStrategy<br>{<br>    private readonly decimal _percent;<br><br>    public PercentageDiscount(decimal percent) =&gt; _percent = percent;<br><br>    public decimal ApplyDiscount(decimal total) =&gt; total - (total * _percent);<br>}</pre><p>We define an interface IDiscountStrategy, which serves as an abstraction for discount behavior. This allows different types of discount logic to be implemented separately while adhering to a common contract.</p><p>The NoDiscount class represents a scenario where no discount is applied. It implements IDiscountStrategy and simply returns the original total.</p><p>The PercentageDiscount class applies a percentage-based discount. This implementation is <strong>plug-and-play</strong>—it can be added without modifying any existing logic, demonstrating the power of OCP.</p><p>By extending the IDiscountStrategy interface, we can introduce new discount types (e.g., fixed amount discount, tiered discounts) without altering existing service code.</p><p>Service using OCP:</p><pre>public class CheckoutService<br>{<br>    private readonly IDiscountStrategy _discountStrategy;<br><br>    public CheckoutService(IDiscountStrategy discountStrategy)<br>    {<br>        _discountStrategy = discountStrategy;<br>    }<br><br>    public decimal Checkout(decimal total)<br>    {<br>        return _discountStrategy.ApplyDiscount(total);<br>    }<br>}</pre><p>Adding a new discount type (e.g., FixedAmountDiscount) requires <strong>no modification</strong> to CheckoutService, only extension. The CheckoutService depends on the <strong>abstraction</strong> (IDiscountStrategy) rather than on concrete implementations. This means we can inject any kind of discount strategy at runtime—such as NoDiscount, PercentageDiscount, or any new strategy we define in the future.</p><p>As a result:</p><ul><li>The service is <strong>closed for modification</strong> — we don’t need to touch this class when adding new discount types.</li><li>The service is <strong>open for extension</strong> — new behaviors can be introduced by implementing the interface.</li></ul><p>This architecture follows OCP closely and promotes <strong>scalability, testability, and clean separation of concerns</strong>.</p><h3>3. Liskov Substitution Principle (LSP)</h3><p><strong>Definition</strong>: Objects of a superclass should be replaceable with objects of its subclasses without affecting correctness.</p><p>This principle enforces <strong>behavioral integrity</strong> between base and derived classes. Violations often stem from overriding methods in ways that break expectations.</p><p><strong>Example</strong>: Suppose we are building a notification system.</p><pre>public abstract class Notification<br>{<br>    public abstract Task SendAsync(string to, string message);<br>}<br><br>public class EmailNotification : Notification<br>{<br>    public override Task SendAsync(string to, string message)<br>    {<br>        // Send email<br>        return Task.CompletedTask;<br>    }<br>}<br><br>public class SmsNotification : Notification<br>{<br>    public override Task SendAsync(string to, string message)<br>    {<br>        // Send SMS<br>        return Task.CompletedTask;<br>    }<br>}</pre><p>Here, Notification is an abstract base class that defines the contract for sending messages asynchronously. Any subclass must implement the SendAsync method.</p><p>Both EmailNotification and SmsNotification <strong>respect the contract</strong> defined by the base class. They override the SendAsync method appropriately and do not introduce unexpected behavior.</p><p>These subclasses are <strong>fully substitutable</strong> for the Notification type. That means anywhere the base Notification is used, we can safely use either subclass without breaking the logic.</p><p>Consumer code:</p><pre>public class NotificationSender<br>{<br>    private readonly Notification _notification;<br><br>    public NotificationSender(Notification notification)<br>    {<br>        _notification = notification;<br>    }<br><br>    public Task Notify(string to, string msg) =&gt; _notification.SendAsync(to, msg);<br>}</pre><p>Any subclass (EmailNotification, SmsNotification) can substitute Notification without causing unexpected behavior—<strong>satisfying LSP</strong>. NotificationSender depends on the abstract Notification type. Thanks to LSP, we can inject either EmailNotification or SmsNotification into this class, and it will behave as expected.</p><p>This makes the code:</p><ul><li><strong>Polymorphic</strong> — easily adaptable to different notification types.</li><li><strong>Flexible and maintainable</strong> — no need to modify NotificationSender when new notification types (e.g., push notification, Slack notification) are added.</li><li><strong>Aligned with SRP and OCP</strong> — each class has a single responsibility and is open for extension via polymorphism.</li></ul><h3>4. Interface Segregation Principle (ISP)</h3><p><strong>Definition</strong>: Clients should not be forced to depend on interfaces they do not use.</p><p>Rather than having one large, catch-all interface, it’s better to have multiple, small interfaces that are client-specific. This increases <strong>flexibility and modularity</strong>.</p><p><strong>Violation Example:</strong></p><pre>public interface IWorker<br>{<br>    void Work();<br>    void Eat();<br>}</pre><p>This interface <strong>violates ISP</strong> because it combines two unrelated responsibilities: <strong>working</strong> and <strong>eating</strong>. Not all workers in a system may need to “eat”. For example, a robot can work but doesn’t need to eat — yet it’s still forced to implement this method.</p><p>This creates unnecessary coupling and can lead to <strong>empty or meaningless method implementations</strong>, which reduce code clarity and increase maintenance overhead.</p><p><strong>Refactored Using ISP</strong>:</p><pre>public interface IWorkable<br>{<br>    void Work();<br>}<br><br>public interface IFeedable<br>{<br>    void Eat();<br>}<br><br>public class HumanWorker : IWorkable, IFeedable<br>{<br>    public void Work() { /*...*/ }<br>    public void Eat() { /*...*/ }<br>}<br><br>public class RobotWorker : IWorkable<br>{<br>    public void Work() { /*...*/ }<br>}</pre><p>Here, the original IWorker interface is split into two smaller interfaces:</p><ul><li>IWorkable — represents the ability to work.</li><li>IFeedable — represents the ability to eat.</li></ul><p>Now, classes only implement the interfaces that are <strong>relevant to their behavior</strong>, aligning perfectly with the Interface Segregation Principle.</p><p>The HumanWorker implements both IWorkable and IFeedable because humans both <strong>work</strong> and <strong>need food</strong>. The interface contracts match the class&#39;s actual capabilities, making the code intuitive and logically consistent.</p><h3>5. Dependency Inversion Principle (DIP)</h3><p><strong>Definition</strong>: High-level modules should not depend on low-level modules. Both should depend on abstractions.</p><p>DIP is about <strong>inverting control</strong> — high-level modules rely on interfaces, not concrete classes. This principle is fundamental to <strong>dependency injection</strong>, a first-class citizen in ASP.NET Core.</p><p><strong>Example</strong>: Logging service using DIP.</p><pre>public interface ILoggerService<br>{<br>    void Log(string message);<br>}<br><br>public class FileLogger : ILoggerService<br>{<br>    public void Log(string message)<br>    {<br>        File.AppendAllText(&quot;log.txt&quot;, $&quot;{DateTime.UtcNow}: {message}\n&quot;);<br>    }<br>}</pre><p>We define an interface ILoggerService that represents the abstraction for logging. This interface does <strong>not dictate how</strong> logging is performed—it simply defines the <strong>contract</strong>.</p><p>The FileLogger is a <strong>low-level class</strong> that handles the actual file-writing operation. It implements ILoggerService, so it adheres to the contract but <strong>can be swapped easily</strong> with another logger (e.g., console logger, database logger, cloud logger) without changing any of the high-level modules that use it.</p><p>Injected via constructor:</p><pre>public class OrderService<br>{<br>    private readonly ILoggerService _logger;<br><br>    public OrderService(ILoggerService logger)<br>    {<br>        _logger = logger;<br>    }<br><br>    public void PlaceOrder(string productId)<br>    {<br>        // Logic<br>        _logger.Log($&quot;Order placed for {productId}&quot;);<br>    }<br>}</pre><p>OrderService is a <strong>high-level module</strong> that contains core business logic. It <strong>does not depend on any concrete logger</strong>—only on the ILoggerService abstraction.</p><p>This means:</p><ul><li>OrderService does not care how logging is implemented.</li><li>We can change the logging mechanism without touching this class.</li><li>It’s easy to <strong>unit test</strong> using mocks or stubs.</li></ul><p>This is a textbook example of the Dependency Inversion Principle in action.</p><p>Registered in Startup.cs (or Program.cs in .NET 6+):</p><pre>builder.Services.AddScoped&lt;ILoggerService, FileLogger&gt;();</pre><p>In modern .NET applications, the DI container is used to <strong>bind abstractions to concrete implementations</strong>. Here we tell the application:</p><blockquote><em>“Whenever a class needs an </em><em>ILoggerService, provide an instance of </em><em>FileLogger.&quot;</em></blockquote><p>This registration ensures that the correct dependency is injected at runtime, maintaining <strong>inversion of control</strong> and honoring DIP.</p><h3>Final Thoughts</h3><p>The SOLID principles form a foundation for building software systems that are <strong>extensible, maintainable, and testable</strong>. Each principle targets a specific axis of software design, from the way responsibilities are distributed (SRP) to how dependencies are managed (DIP). In ASP.NET Core applications, SOLID isn’t just theory — it translates into everyday coding patterns through middleware composition, service abstraction, controller decomposition, and more.</p><p>While adopting SOLID may initially introduce complexity, especially in smaller applications, its long-term benefits in large-scale systems are substantial. By embracing these principles, developers equip themselves to write code that gracefully evolves with business requirements and technological changes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5888065a82c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Big O Notation: Time and Space Complexity]]></title>
            <link>https://medium.com/@wiliperdana/big-o-notation-time-and-space-complexity-ac95b96a617c?source=rss-0f8d6f13cc97------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac95b96a617c</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[back-end-development]]></category>
            <dc:creator><![CDATA[Yuda Wiliperdana]]></dc:creator>
            <pubDate>Mon, 28 Apr 2025 12:53:57 GMT</pubDate>
            <atom:updated>2025-04-29T01:22:45.610Z</atom:updated>
            <content:encoded><![CDATA[<h3>Big O Notation: Time Complexity</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ENAP16Z-YXbzEebQllXFYA.jpeg" /></figure><p>Big O notation serves as a fundamental tool in computer science for characterizing the efficiency of algorithms. By abstracting away machine-specific details, it allows us to focus on how an algorithm’s runtime grows relative to its input size, typically denoted as <em>n</em>. However, Big O is just one of three key asymptotic notations: Big Θ (Theta) captures both upper and lower bounds — offering a tight estimate of performance — while Big Ω (Omega) provides a lower bound, assuring us of the minimum work an algorithm must perform. Together, these notations furnish a comprehensive language for describing best-case, average-case, and worst-case scenarios, enabling developers to reason rigorously about algorithmic behavior even before a single line of code is written.</p><p>Beyond time complexity, which measures how execution time scales, space complexity examines how much memory an algorithm consumes as its input grows. In practice, an optimal solution balances both dimensions, trading off between additional memory allocation and faster execution when necessary. Whether you’re sorting a massive dataset or designing a graph traversal routine, understanding time-space complexity empowers you to make informed choices: sometimes sacrificing extra space can reduce runtime dramatically, while in other contexts, minimizing memory usage is paramount. Mastery of these concepts is essential for crafting high-performance software that scales gracefully under real-world constraints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jQ4lodeRFmOIIi1COTFImw.jpeg" /></figure><h3>Big O (O-notation)</h3><p>Big O notation provides an upper bound on a function’s growth rate, capturing the worst-case behavior of an algorithm as its input size <em>n</em> approaches infinity. Formally, a function <em>f(n)</em> is in <strong>O(g(n))</strong> if there exist constants <em>c &gt; 0</em> and <em>n₀</em> such that for all <em>n ≥ n₀</em>,</p><blockquote>0 ≤ f(n) ≤ c g(n)</blockquote><p>This definition allows us to ignore constant factors and lower-order terms when analyzing large inputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*VdPv_OyGsEoNlf0cpLqexQ.png" /><figcaption>Big O</figcaption></figure><h3>Big Ω (Omega-notation)</h3><p>Big Ω notation offers a lower bound on growth rate, reflecting the best-case or guaranteed minimal performance of an algorithm. Specifically, <em>f(n)</em> is in <strong>Ω(g(n))</strong> if there exist constants <em>c &gt; 0</em> and <em>n₀</em> such that for all <em>n ≥ n₀</em>,</p><blockquote>0 ≤ c g(n) ≤ f(n)</blockquote><p>Big Ω is essential when one must ensure an algorithm runs at least this fast for large inputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*zQAZdTYZ_L1XyDgUsFutFw.png" /><figcaption>Big Omega</figcaption></figure><h3>Big Θ (Theta-notation)</h3><p>Big Θ notation characterizes a tight bound, combining both Big O and Big Ω. We say <em>f(n)</em> is in <strong>Θ(g(n))</strong> if it is simultaneously in O(g(n)) and Ω(g(n)), i.e., there exist constants <em>c₁, c₂ &gt; 0</em> and <em>n₀</em> such that for all <em>n ≥ n₀</em>,</p><blockquote>c1 g(n) ≤ f(n) ≤ c2 g(n)</blockquote><p>This indicates that <em>f(n)</em> grows at the same rate as <em>g(n)</em> up to constant factors</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*Ba3ARznTUdPNdfGah9kqDw.png" /><figcaption>Big Theta</figcaption></figure><h3>Exploration of Big O Notation</h3><p>Big O notation abstracts away hardware-specific constants and lower-order terms to focus solely on the dominant factor that dictates performance as the problem size grows without bound. In formal terms, analyzing an algorithm’s time complexity with Big O involves expressing the number of elementary operations, <em>T(n)</em>, as a function bounded above by <em>c·g(n)</em> for sufficiently large <em>n</em>, where <em>g(n)</em> represents a simpler, canonical function such as <em>n</em>, <em>n log n</em>, or <em>n²</em>. This simplification is instrumental in comparing algorithms: two algorithms with complexities <em>O(n²)</em> and <em>O(n log n)</em>, respectively, will exhibit vastly different growth behaviors for large <em>n</em>, regardless of constant-time optimizations.</p><p>Furthermore, Big O notation is often used in algorithmic literature and formal proofs to demonstrate upper bounds on runtime or space usage. By proving that <em>T(n)</em> ∈ O(g(n)), one shows that there exists an <em>n₀</em> beyond which the algorithm will never take more than <em>c·g(n)</em> steps, ensuring predictability in performance scaling. This property is especially valuable for guaranteeing that an algorithm will meet specified performance requirements under worst-case conditions, a critical consideration in real-time and large-scale systems design</p><h3>Constant Time: O(1)</h3><p>Constant time complexity implies the execution time is independent of input size. Formally,</p><blockquote>T(n) = O(1)</blockquote><p>meaning there exists <em>c</em> and <em>n₀</em> such that <em>T(n) ≤ c</em> for all <em>n ≥ n₀</em>. In most scenarios, accessing a single array element exemplifies O(1) behavior.</p><pre>def get_first_element(arr):<br>    return arr[0]</pre><p>When reading a specific key from a hash table, no matter how many items exist, the lookup remains constant time. Python’s dictionary get operation is a canonical O(1) case as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*LYjETLnht2b6Z355D67lCQ.png" /><figcaption>Constant Time</figcaption></figure><h3>Linear Time: O(n)</h3><p>Linear time indicates runtime grows in direct proportion to input size. Specifically,</p><blockquote>T(n) = O(n)</blockquote><p>so doubling <em>n</em> roughly doubles <em>T(n)</em>. Consider summing an array’s elements: one operation per element yields linear complexity.</p><pre>def sum_list(arr):<br>    total = 0<br>    for x in arr:<br>        total += x<br>    return total</pre><p>Here, the loop executes <em>n</em> times, making operations scale exactly with the array length.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*yF3iFmVsDlS45UlwxE2UoQ.png" /><figcaption>Linear</figcaption></figure><h3>Logarithmic Time: O(log n)</h3><p>An algorithm exhibits logarithmic complexity when the input size is reduced multiplicatively at each step. Formally,</p><blockquote>T(n) = O(log⁡ n)</blockquote><p>implying that if <em>n</em> grows exponentially, <em>T(n)</em> increases linearly. Binary search perfectly illustrates this class.</p><pre>def binary_search(arr, target):<br>    left, right = 0, len(arr)-1<br>    while left &lt;= right:<br>        mid = (left + right) // 2<br>        if arr[mid] == target:<br>            return mid<br>        elif arr[mid] &lt; target:<br>            left = mid + 1<br>        else:<br>            right = mid - 1<br>    return -1</pre><p>In each iteration, the searchable portion halves, resulting in a logarithmic number of steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*1ezyFkNBdhZP93BS__KO-Q.png" /><figcaption>Logarithmic</figcaption></figure><h3>Linear Logarithmic Time: O(n log n)</h3><p>Algorithms in this class combine linear and logarithmic behaviors. Formally,</p><blockquote>T(n) = O(n log⁡ n)</blockquote><p>Many divide-and-conquer sorting algorithms, such as mergesort, fall into this category.</p><pre>def mergesort(arr):<br>    if len(arr) &lt;= 1:<br>        return arr<br>    mid = len(arr) // 2<br>    left = mergesort(arr[:mid])<br>    right = mergesort(arr[mid:])<br>    return merge(left, right)</pre><p>The recurrence <em>T(n) = 2T(n/2) + O(n)</em> solves to <em>O(n log n)</em>, reflecting the cost of splitting (log n levels) and merging (O(n) per level).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*-4kYsAKC-iiFI9ztUlvllg.png" /><figcaption>Linear Logarithmic</figcaption></figure><h3>Quadratic Time: O(n²)</h3><p>Quadratic complexity arises when runtime is proportional to the square of input size. Formally,</p><blockquote>T(n) = O(n²)</blockquote><p>Simple sorting algorithms like bubble sort and insertion sort in their worst cases demonstrate O(n²) behavior.</p><pre>def bubble_sort(arr):<br>    n = len(arr)<br>    for i in range(n):<br>        for j in range(0, n - i - 1):<br>            if arr[j] &gt; arr[j + 1]:<br>                arr[j], arr[j + 1] = arr[j + 1], arr[j]<br>    return arr</pre><p>Here, nested loops each up to <em>n</em> iterations yield on the order of <em>n²</em> comparisons and swaps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*NM5HWxNWC-o5-GRQZ7BgKQ.png" /><figcaption>Quadratic</figcaption></figure><h3>Exponential Time: O(2ⁿ)</h3><p>Exponential time complexity doubles the work for each additional input element. Formally,</p><blockquote>T(n) = O(2ⁿ)</blockquote><p>A classic example is the naive recursive solution to the Fibonacci sequence.</p><pre>def fib(n):<br>    if n &lt;= 1:<br>        return n<br>    return fib(n - 1) + fib(n - 2)</pre><p>Each call spawns two more calls (except at the base), leading to approximately 2ⁿ calls for input <em>n.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*crfjSPG8CgqFdbaf0Vegxw.png" /><figcaption>Exponential</figcaption></figure><h3>Factorial Time: O(n!)</h3><p>Factorial time complexity grows faster than any exponential of fixed base. Formally,</p><blockquote>T(n) = O(n!)</blockquote><p>Generating all permutations of <em>n</em> items typifies this class.</p><pre>import itertools<br><br>def all_permutations(arr):<br>    return list(itertools.permutations(arr))</pre><p>There are <em>n!</em> permutations, so listing them requires time proportional to <em>n!.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*1FsMQSGza2hGF4oYZ4RGlQ.png" /><figcaption>Factorial</figcaption></figure><h3>Comparison Chart</h3><p>​To effectively compare the computational growth of the seven primary Big O time complexities — O(1), O(log n), O(n), O(n log n), O(n²), O(2ⁿ), and O(n!). For small input sizes, differences between complexities may appear negligible. however, as n increases, the disparities become pronounced. For instance, O(1) remains constant regardless of input size, depicted as a horizontal line. O(log n) grows slowly, reflecting efficient algorithms like binary search. Linear (O(n)) and linearithmic (O(n log n)) complexities show moderate growth, common in algorithms like simple loops and efficient sorts. Quadratic (O(n²)) complexity, often seen in naive sorting algorithms, exhibits a steeper curve. Exponential (O(2ⁿ)) and factorial (O(n!)) complexities escalate rapidly, indicating algorithms that become impractical even for relatively small n.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*C3TJWOBgEiIplXNmyWMA3A.jpeg" /><figcaption>Big O NotationComparison</figcaption></figure><h3>Conclusion</h3><p>Big-O notation provides a standardized way to describe the asymptotic performance of algorithms and to compare them abstractly​. It tells us how the runtime or space grows with input size, ignoring machine-specific details. By using Big-O (along with Ω and Θ), developers can predict scaling behavior and identify bottlenecks. For example, understanding that quicksort runs in <em>O(n\log n)</em> on average while bubble sort runs in <em>O(n²)</em> helps engineers choose the right algorithm for large data sets. As Bruno Bernardes notes, this insight is <em>“a critical advantage in modern software engineering, where efficiency and scalability are often key requirements.”</em>​. Ultimately, mastering these notations and their typical values allows us to judge algorithms’ efficiency: constant, logarithmic, linear, and quasilinear algorithms will complete in reasonable time even for very large <em>n</em>, whereas quadratic, exponential, and factorial algorithms become impractical except on tiny inputs​</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac95b96a617c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>