<?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 Shivam Thakur on Medium]]></title>
        <description><![CDATA[Stories by Shivam Thakur on Medium]]></description>
        <link>https://medium.com/@shivamthakurdev?source=rss-7d0abb59c77e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*M6f6zLPyJ-iv7jrqnt-dUw.jpeg</url>
            <title>Stories by Shivam Thakur on Medium</title>
            <link>https://medium.com/@shivamthakurdev?source=rss-7d0abb59c77e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 01:23:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shivamthakurdev/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[Clean Architecture in ASP.NET Core: Stop Writing Spaghetti Code]]></title>
            <link>https://shivamthakurdev.medium.com/clean-architecture-in-asp-net-core-stop-writing-spaghetti-code-de03daf49e19?source=rss-7d0abb59c77e------2</link>
            <guid isPermaLink="false">https://medium.com/p/de03daf49e19</guid>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Shivam Thakur]]></dc:creator>
            <pubDate>Thu, 12 Nov 2026 06:25:54 GMT</pubDate>
            <atom:updated>2026-11-12T06:25:54.258Z</atom:updated>
            <content:encoded><![CDATA[<p>Software architecture is the collection of decisions you make about how a system is divided into parts, what each part is responsible for, and how those parts are allowed to communicate. It is less about which framework you pick and more about where code lives and which code is allowed to know about which other code.</p><p>Architecture rarely matters on day one. On day one, the codebase is small, and you can hold the entire application in your head. It matters on day 400, when a new developer needs to add a feature without breaking three others, or when the business asks you to swap SQL Server for PostgreSQL. Good architecture makes those tasks boring. Poor architecture makes them risky.</p><p>Most of us have built or inherited an ASP.NET Core API where everything sits in one project. You often find a controller action that validates an HTTP request, checks the database for duplicates using Entity Framework Core, applies a business rule, maps the result to a database entity, calls SaveChanges, and then triggers an SMTP client to send a welcome email.</p><p>It works, but look at what that single method knows about: HTTP status codes, business rules, database schemas, and email providers. As the application grows, business rules scatter across multiple controllers, tests require spinning up a database, and developers become terrified to make changes.</p><p>Clean Architecture, popularised by <strong><em>Robert C. Martin (“Uncle Bob”)</em></strong>, solves this by organising code so your business rules sit at the centre of the application, while everything technical — web frameworks, databases, email providers — sits at the edges and plugs in. The core philosophy is simple: <strong>business logic should not know or care how it is delivered, stored, or notified.</strong></p><h3>Understanding Clean Architecture</h3><p>Clean Architecture is usually visualised as a series of concentric circles. At the centre is your domain and business logic. As you move outward, the software becomes more related to mechanisms, details, and delivery.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*6BkJa4ZLIk-ADbjTFbkUhg.png" /></figure><p>The entire pattern relies on a single, unbreakable directive called the <strong>Dependency Rule</strong>: <em>Source code dependencies must point only inward, toward higher-level policies.</em></p><p>Code in an inner layer must not reference anything declared in an outer layer. Your core domain cannot know about Entity Framework Core, SQL Server, or HTTP requests. The outer layers depend on the inner layers, not the reverse.</p><p>This introduces a common point of confusion: at runtime, the application obviously needs to save data to a database, so how can the business logic not depend on it? The answer is <strong>Dependency Inversion</strong>. The inner layer declares an interface detailing what it needs (e.g., IEmployeeRepository). The outer layer provides a class that implements that interface. At compile time, the inner layer knows nothing about the database. At runtime, the dependency injection container hands the inner layer the concrete implementation.</p><p>Keeping business logic independent means frameworks and databases can change without touching the core rules. It guarantees loose coupling, highly testable code, and long-term maintainability.</p><h3>Understanding the Four Main Layers</h3><p>In a typical ASP.NET Core solution, these concentric circles map directly to four distinct layers.</p><h3>1. Domain Layer</h3><p>The Domain Layer is the heart of the application. It models the business concepts and enforces the rules that are always true, regardless of which screen, API, or background job is involved.</p><ul><li><strong>Contains:</strong> Entities, value objects, enums, domain exceptions, and domain services.</li><li><strong>Rules:</strong> It has <strong>zero dependencies</strong> on any other project or framework. There should be no EF Core attributes, no DbContext, and no HTTP concepts here.</li></ul><h3>2. Application Layer</h3><p>The Application Layer orchestrates use cases. If the Domain answers “what are the rules?”, the Application layer answers “what can a user actually do with the system, step by step?”</p><ul><li><strong>Contains:</strong> Use cases (often separated into Commands and Queries), DTOs, interfaces for external dependencies (repositories, email senders), validators, and application exceptions.</li><li><strong>Rules:</strong> It depends only on the Domain layer.</li></ul><p>You will often see <strong>CQRS</strong> (Command Query Responsibility Segregation) used here. CQRS simply means separating operations that change state (commands) from operations that read state (queries). A CreateEmployeeCommand runs through domain rules, while a GetEmployeeByIdQuery might just read data straight into a DTO. CQRS keeps write paths strict and read paths fast.</p><h3>3. Infrastructure Layer</h3><p>The Infrastructure Layer is where the application talks to the outside world. Everything here exists to satisfy an interface declared further in.</p><ul><li><strong>Contains:</strong> EF Core DbContext, repository implementations, email senders, third-party API clients, and file storage mechanisms.</li><li><strong>Rules:</strong> It depends on the Application and Domain layers. This is where you install EF Core packages and database drivers.</li></ul><h3>4. Presentation Layer</h3><p>The Presentation Layer acts as the entry point for external users and clients.</p><ul><li><strong>Contains:</strong> ASP.NET Core Web API controllers, minimal APIs, HTTP-specific contracts, middleware (exception handling, authentication), and dependency injection configuration.</li><li><strong>Rules:</strong> It depends on the Application layer to trigger use cases, and it references the Infrastructure layer solely to wire up dependency injection in Program.cs. Its job is purely translational: turn an HTTP request into a command, call the use case, and turn the result into an HTTP response.</li></ul><pre>1) Client to Controller: The client sends JSON. ASP.NET Core model binding turns it into a request object. The controller maps it to an application command and calls the use case.<br><br>                                      |<br>2)Controller to Use Case: The application handler validates the input shape. It checks if the email is already in use by calling a repository interface, completely unaware of the actual database.<br><br>                                      |<br>3) Use Case to Domain: The handler calls the Domain entity&#39;s factory method to create the employee. The entity enforces core invariants (e.g., names are required, hire dates cannot be in the future).<br><br>                                      |<br>4) Use Case to Infrastructure: The handler passes the valid entity to the repository interface&#39;s Add method and calls SaveChangesAsync.<br><br>                                      |<br>5) Infrastructure to Database: EF Core translates this into a SQL INSERT statement and executes it.<br><br>                                      |<br>6) Response: The handler returns a DTO back to the controller, which wraps it in an HTTP 201 Created response.</pre><h3>Recommended .NET Project Structure</h3><pre>MyApp.sln<br>│<br>├── src/<br>│   ├── MyApp.Domain/            # Class Library (References nothing)<br>│   ├── MyApp.Application/       # Class Library (References Domain)<br>│   ├── MyApp.Infrastructure/    # Class Library (References Domain &amp; Application)<br>│   └── MyApp.WebApi/            # ASP.NET Core Web API (References Application &amp; Infrastructure)</pre><h3>Common Mistakes to Avoid</h3><p>When adopting Clean Architecture, developers frequently fall into a few traps:</p><ul><li><strong>Putting business logic inside controllers:</strong> Controllers should only parse HTTP requests, pass them to the Application layer, and return HTTP responses.</li><li><strong>Making the Domain Layer dependent on Entity Framework Core:</strong> Your entities should not inherit from EF Core base classes or rely on database-specific attributes ([Table], [Column]). Use fluent API configurations in the Infrastructure layer instead.</li><li><strong>Placing database implementations inside the Application Layer:</strong> The Application layer should only contain interfaces. The actual implementation belongs in Infrastructure.</li><li><strong>Creating unnecessary abstractions:</strong> Don’t create generic repository wrappers over EF Core (which is already a repository and unit of work) unless you specifically need to abstract database details away from the Application layer.</li><li><strong>Allowing dependencies to point outward:</strong> Watch for subtle leaks, like an Application DTO using IFormFile from ASP.NET Core, or a domain exception holding an HTTP status code.</li><li><strong>Overengineering simple applications:</strong> If you are building a small, short-lived CRUD application with no complex business rules, Clean Architecture is overkill.</li></ul><h3>Benefits and Trade-offs</h3><p><strong>Benefits:</strong></p><ul><li><strong>Maintainability:</strong> Every kind of code has a specific home. When a bug arises in a business rule, you know exactly where to look.</li><li><strong>Testability:</strong> You can easily mock external dependencies to unit test your Application layer and Domain layer in milliseconds, without spinning up a database.</li><li><strong>Separation of concerns:</strong> Database code stays completely out of UI code.</li><li><strong>Flexibility:</strong> Switching from SQL Server to PostgreSQL, or replacing a third-party email provider, requires changes only in the Infrastructure layer.</li></ul><p><strong>Trade-offs:</strong></p><ul><li><strong>Initial setup complexity:</strong> Creating four projects, defining interfaces, and mapping between entities and DTOs takes more time upfront than building a monolith.</li><li><strong>Learning curve:</strong> The Dependency Rule and dependency inversion take time to internalize, especially for teams accustomed to tight coupling.</li></ul><h3>Conclusion</h3><p>Clean Architecture is a powerful paradigm that prioritizes your business domain over the tools used to deliver it. By strictly enforcing the Dependency Rule, you ensure that your core logic remains pure, highly testable, and adaptable to change.</p><p>While it introduces initial complexity and boilerplate, the payoff in long-term maintainability is immense for enterprise-grade applications. You do not have to rewrite your entire system today. Start by identifying one feature, moving its business rules out of the controller, and placing database access behind an interface.</p><p>Architecture is not about creating more folders and projects. It is about drawing strict boundaries that protect your business logic from the chaos of the outside world.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de03daf49e19" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Are Linear Models in Machine Learning? A Beginner’s Deep Dive]]></title>
            <link>https://shivamthakurdev.medium.com/what-are-linear-models-in-machine-learning-a-beginners-deep-dive-6a6c6baaf690?source=rss-7d0abb59c77e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a6c6baaf690</guid>
            <dc:creator><![CDATA[Shivam Thakur]]></dc:creator>
            <pubDate>Tue, 20 Oct 2026 12:29:04 GMT</pubDate>
            <atom:updated>2026-10-20T13:18:58.531Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Here is the industry secret:</strong> <strong><em>Before a senior ML engineer spins up a complex transformer or a deep network, they almost always start with a Linear Model.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qD2IR5xcYekkgNLU_4iMYA.png" /></figure><h4>Overview</h4><p>The Linear Model is one of the most straightforward models in machine learning. It is the building block for many complex machine learning algorithms, including deep neural networks. Linear models predict the target variable using a linear function of the input features. In this article, we will cover two crucial linear models in machine learning:</p><h3>1. What Is a Linear Model? (The Coffee Shop Intuition)</h3><p>At its heart, a linear model works on a simple assumption: <strong>the output you want to predict changes proportionally as your input features change.</strong></p><p>Think about your daily coffee runs:</p><ul><li>Suppose a cup of coffee costs <strong>$4</strong>.</li><li>Every extra espresso shot costs <strong>$1</strong>.</li><li>Every pump of flavored syrup costs <strong>$0.50</strong>.</li></ul><p>If you know the number of shots and pumps, you can calculate the total bill with a simple formula:</p><pre>Total Cost = (Base Price)+(Weight 1 × Extra Shots)+(Weight 2 × Syrup Pumps)</pre><p>In Machine Learning terms:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DWdLjlqpmKmpcVF-seHXsQ.png" /></figure><pre>1) Target (y): The total cost you want to predict.<br>2) Features (x): The number of shots, pumps, size, etc.<br>3) Weights (w): How much each feature influences the final price.<br>4) Bias/Intercept (b): The baseline price when all other inputs are zero.</pre><p>Instead of hand-coding these prices, a linear model looks at hundreds of receipts and <strong>learns the weights and bias on its own</strong>.</p><h4>2. Deep Dive: Linear Regression (Predicting a Continuous Number)</h4><p>When the value you want to predict is a continuous number — such as <em>house prices, stock values, or outside temperature </em>— you use <strong><em>Linear Regression.</em></strong></p><p><strong>The Goal: Finding the “Line of Best Fit”</strong><br>Imagine plotting house square footage on the horizontal axis and house price on the vertical axis. The data points will scatter across your graph.</p><p>Linear regression draws a straight line through that cloud of dots such that the overall distance between the dots and the line is as small as possible.</p><pre> Price ($)<br>   ^               *  (Actual data point)<br>   |             / :<br>   |           /   : Error / Residual<br>   |         /.....*<br>   |       / *<br>   |     /<br>   |   / *<br>   +------------------------&gt; Size (Sq Ft)</pre><h4>How the Model Learns: Minimizing Mistakes ?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WN18BcQnEzxXyHQ9DE6TNQ.png" /></figure><p>It uses a loss metric called <strong>Mean Squared Error (MSE)</strong>. <br>1. It measures the vertical gap (the error) between every actual point and its line.<br>2. It squares each error (so positive and negative mistakes don’t cancel each other out, and large mistakes get penalized heavily).<br>3. It tweaks the line’s tilt and height until the average squared error is as low as possible.</p><p><strong>Key Assumptions:</strong><br>For Linear Regression to perform well, it makes a few commonsense assumptions:<br><strong>1. Linearity:</strong> The real relationship between inputs and outputs is reasonably straight, not a rollercoaster.<br><strong>2. Independence:</strong> Your data points don’t influence one another (e.g., measuring one house price doesn’t alter another’s).<br><strong>3. Consistent Spread (Homoscedasticity): </strong>The model’s prediction errors stay roughly the same across low, medium, and high values.<br><strong>4. Normal Errors:</strong> Most prediction errors cluster around zero; massive outliers are rare.</p><pre>#🐍 Python in Action: Linear Regression<br><br>from sklearn.linear_model import LinearRegression<br>import numpy as np<br># Sample data: House size (sq ft) -&gt; Price ($k)<br>X = np.array([[650], [800], [1200], [1500], [2000]])<br>y = np.array([150, 180, 260, 310, 400])<br># Train model<br>model = LinearRegression()<br>model.fit(X, y)<br># Predict price for a 1400 sq ft house<br>predicted_price = model.predict([[1400]])<br>print(f&quot;Estimated Price: ${predicted_price[0]:,.1f}k&quot;)</pre><h3>3. Deep Dive: Logistic Regression (Predicting Categories)</h3><p>Now let’s switch gears. What if you aren’t predicting a price, but answering a <strong>Yes/No question?</strong></p><ul><li>Is this email Spam or Not Spam?</li><li>Will this customer cancel their subscription (Churn or Stay)?</li><li>Is a transaction fraudulent or legitimate?</li></ul><p>Why Can’t We Just Use Linear Regression?<br>If you fit a straight line to predict binary outcomes (0 or 1), things break down fast:</p><ul><li>A straight line extends infinitely into positive and negative space. It can output a probability of <strong>180%</strong> or<strong> -35%</strong>, which makes no sense.</li><li><strong>Extreme outliers</strong> can tilt the entire line and mess up your decision threshold.</li></ul><blockquote><strong>The Solution: The S-Curve (Sigmoid Function)</strong><br>Logistic Regression takes that same straight line and bends it through a mathematical funnel called the <strong>Sigmoid function.</strong></blockquote><pre>Probability<br> 1.0 | - - - - - - (Spam)<br> | /<br> 0.5 | - - - - + ← 50% Decision Boundary<br> | /<br> 0.0 | - - - - (Not Spam)<br> + - - - - - - - - - - - - - → Feature Score</pre><blockquote>The Sigmoid squashes any value — whether it’s -1,000 or +100,000 — into a clean decimal strictly between <strong>0.0 and 1.0.</strong></blockquote><blockquote>Now you have a true probability score !<br>By default, if the probability is <strong>age 0.5 (50%)</strong>, the model predicts <strong>Class 1 (Yes).</strong><br>If it’s <strong>&lt; 0.5</strong>, it predicts <strong>Class 0 (No)</strong>.</blockquote><h4>How It Learns: Log-Loss</h4><p>Instead of <strong>Mean Squared Error</strong>, Logistic Regression uses <strong>Log-Loss (Cross-Entropy).</strong> Think of Log-Loss as a strict teacher: if the model is confident and right <strong>(predicts 99% spam, and it is spam)</strong>, it receives almost zero penalty. But if it is confident and wrong <strong>(predicts 99% safe, but it’s malicious spam)</strong>, the penalty shoots toward infinity.</p><pre>### 🐍 Python in Action: Logistic Regression<br><br>from sklearn.linear_model import LogisticRegression<br>import numpy as np<br># Sample data: Hours studied -&gt; Exam Passed (0 = No, 1 = Yes)<br>X = np.array([[1], [2], [3], [4], [5], [6]])<br>y = np.array([0, 0, 0, 1, 1, 1])<br># Train model<br>classifier = LogisticRegression()<br>classifier.fit(X, y)<br># Predict outcome &amp; probability for 3.5 hours of study<br>prob = classifier.predict_proba([[3.5]])[0][1]<br>print(f&quot;Pass Probability: {prob:.1%}&quot;)</pre><h3>4. Head-to-Head Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AemcczwWX9SHf6-8RhOvag.png" /></figure><pre>| Feature          | Linear Regression                 | Logistic Regression |<br>| : - - - - - - - -|: - - - - - - - - - - - - - - - - -| : - - - - - - - - -  - - - - - - - -|<br>| Problem Type     | Regression (Continuous Numbers)   | Classification (Categories / Flags) |<br>| Output           | Any real number(-infty to +infty) | Probability between 0.0 and 1.0     |<br>| Core Shape       | Straight Line / Flat Hyperplane   | S-Shaped Curve (Sigmoid)            |<br>| Loss Function    | Mean Squared Error (MSE)          | Log-Loss (Binary Cross-Entropy)     |<br>| Primary Metrics  | RMSE, MAE, $R²$ Score             | Accuracy, Precision, Recall, ROC-AUC|<br>| Typical Question | &quot;How much will this cost?&quot;        | &quot;Will this event happen?&quot;           |</pre><h3>5. Where Are Linear Models Used in the Real World?</h3><p>You might wonder: <strong>Do companies actually use these simple models in production?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7rVB7moyEwEbGgYQw7qmxQ.png" /></figure><p>Every single day.</p><ol><li><strong>Credit Scoring &amp; Banking: </strong>Banks evaluate loan applications using logistic regression because financial regulators legally require institutions to explain <strong>why</strong> an applicant was rejected.</li><li><strong>Healthcare &amp; Clinical Trials:</strong> Doctors estimate patient risk scores<em> (e.g., probability of heart disease given age, cholesterol, and blood pressure)</em> using logistic models for clear interpretability.</li><li><strong>Real Estate &amp; Retail Pricing:</strong> Dynamic pricing algorithms use linear regression to adjust rideshare rates, hotel rooms, and property assessments in real time.</li><li><strong>Ad Click-Through Prediction: </strong>Major ad platforms evaluate thousands of linear signals in milliseconds to decide which ad to show you.</li></ol><h3>6. Pros, Cons &amp; The Next Step</h3><p><strong>The Superpowers (Why We Love Them)</strong></p><ol><li><strong>Unmatched Interpretability:</strong> There are no mystery <strong>“black boxes.” </strong>Every feature has a direct weight. You know exactly what pushed a prediction up or down.</li><li><strong>Blazing Speed:</strong> They train in fractions of a second on massive datasets and run inference with virtually zero latency.</li><li><strong>The Perfect Baseline: </strong>Before you build an ensemble of XGBoost models or a neural net, a linear model gives you a benchmark score to beat.</li></ol><h4>The Limitations (When to Move On)</h4><p><strong>1. Can’t Catch Non-Linear Patterns:</strong> If the relationship between your features forms a circle, a wave, or an exponential curve, a simple linear model will underfit.<br><strong>2. Susceptible to Extreme Outliers:</strong> A few wildly incorrect data points can skew the line.</p><p>Drop a comment below with your thoughts, and if you found this guide helpful, don’t forget to leave a few claps! 👏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a6c6baaf690" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top 200 .NET Core Interview Questions and Answers | .NET Core Interview Preparation]]></title>
            <link>https://shivamthakurdev.medium.com/top-200-net-core-interview-questions-and-answers-net-core-interview-preparation-a00b5fa027ee?source=rss-7d0abb59c77e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a00b5fa027ee</guid>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Shivam Thakur]]></dc:creator>
            <pubDate>Thu, 03 Sep 2026 13:35:13 GMT</pubDate>
            <atom:updated>2026-09-03T13:35:13.812Z</atom:updated>
            <content:encoded><![CDATA[<h3>C# Fundamentals</h3><ol><li><strong>What is the difference between a class and an object?</strong></li></ol><p>A <strong>class </strong>is a blueprint that defines data and behaviour. An <strong>Object </strong>is an actual instance created from that class</p><pre>public class Employee<br>{<br>    public string Name { get; set; }<br><br>    public void Work() =&gt; Console.WriteLine(&quot;Working&quot;);<br>}<br><br>Employee employee = new Employee();<br>employee.Name = &quot;Amit&quot;;<br>employee.Work();</pre><p>Here, Employee is the class and employee is the object.</p><p><strong>2. Explain the difference between value types and reference types.</strong></p><p>Value types store their data directly, whereas reference types store a reference to an object in memory.</p><ul><li>Value types: int, double, bool, struct, enum.</li><li>Reference types: class, string, object, arrays, delegates.</li></ul><pre>int a = 10;<br>int b = a;<br>b = 20;<br>// a is still 10</pre><p>For a class:</p><pre>Employee first = new Employee { Name = &quot;Amit&quot; };<br>Employee second = first;<br>second.Name = &quot;Rahul&quot;;<br>// first.Name is now also &quot;Rahul&quot;</pre><p><strong>3. What is boxing and unboxing?</strong></p><p><strong>Boxing</strong> converts a value type into object or an implemented interface. <strong>Unboxing</strong> extracts the value type from the object.</p><pre>int number = 10;<br>object boxed = number;       // Boxing<br>int result = (int)boxed;     // Unboxing</pre><p>Unboxing requires the correct original type. Incorrect casting causes InvalidCastException.</p><p><strong>4. What is the difference between </strong><strong>ref and </strong><strong>out?</strong></p><p>Both pass arguments by reference.</p><ul><li>ref: the variable must be initialised before being passed.</li><li>out: the variable does not need to be initialised, but the method must assign it before returning.</li></ul><pre>void Increment(ref int value)<br>{<br>    value++;<br>}<br><br>bool TryGetValue(string input, out int value)<br>{<br>    return int.TryParse(input, out value);<br>}</pre><p>Use out when a method needs to return an additional result.</p><p><strong>5. What are static members in C#?</strong></p><p>Static members belong to the type itself rather than to a particular object. You access them through the class name.</p><pre>public class MathHelper<br>{<br>    public static int Add(int a, int b) =&gt; a + b;<br>}<br><br>int result = MathHelper.Add(2, 3);</pre><p>All consumers share a static member. Avoid mutable static state unless it is intentionally thread-safe.</p><p><strong>6. What is the difference between </strong><strong>const and </strong><strong>readonly?</strong></p><pre>| Feature              | const          | readonly                   |<br>| -------------------- | -------------- | -------------------------- |<br>| Value assigned       | At declaration | Declaration or constructor |<br>| Evaluated            | Compile time   | Runtime                    |<br>| Can vary per object? | No             | Yes                        |<br>| Implicitly static?   | Yes            | No, unless declared static |</pre><pre>public const double Pi = 3.14159;<br>public readonly string ConnectionName;<br><br>public MyClass(string connectionName)<br>{<br>    ConnectionName = connectionName;<br>}</pre><p><strong>7. What is method overloading and method overriding?</strong></p><p><strong>Overloading</strong> means using the same method name with different parameter lists. It is compile-time polymorphism.</p><p><strong>Overriding</strong> means redefining a base-class virtual or abstract method in a derived class. It is runtime polymorphism.</p><pre>public class Calculator<br>{<br>    public int Add(int a, int b) =&gt; a + b;<br>    public int Add(int a, int b, int c) =&gt; a + b + c;<br>}<br><br>public class Animal<br>{<br>    public virtual void Speak() =&gt; Console.WriteLine(&quot;Animal sound&quot;);<br>}<br><br>public class Dog : Animal<br>{<br>    public override void Speak() =&gt; Console.WriteLine(&quot;Bark&quot;);<br>}</pre><p><strong>8. What is the difference between an abstract class and an interface?</strong></p><p>An abstract class can contain implementation, fields, constructors, properties, and abstract methods. An interface primarily defines a contract, although modern C# interfaces can also contain default implementations.</p><p>Use an abstract class when related types share common state or implementation. Use an interface when unrelated types need to follow the same contract.</p><pre>public abstract class Vehicle<br>{<br>    public string RegistrationNumber { get; set; }<br>    public abstract void Start();<br>}<br><br>public interface ITrackable<br>{<br>    void Track();<br>}</pre><p>A class can inherit one base class but implement multiple interfaces.</p><p><strong>9. What are access modifiers in C#?</strong></p><p>Common access modifiers are:</p><ul><li>public: accessible from anywhere.</li><li>private: accessible only inside the containing type.</li><li>protected: accessible inside the type and derived types.</li><li>internal: accessible within the same assembly.</li><li>protected internal: accessible from the same assembly or derived types.</li><li>private protected: accessible from derived types within the same assembly.</li></ul><p>Use the least permissive modifier that satisfies the design.</p><p><strong>10. What is the purpose of the </strong><strong>using statement?</strong></p><p>The using directive imports a namespace:</p><pre>using System.Collections.Generic;</pre><p>The using statement or declaration also ensures disposal of objects implementing IDisposable.</p><pre>using var connection = new SqlConnection(connectionString);</pre><p>The object is disposed automatically when it leaves scope.</p><h3>OOP Concepts</h3><p><strong>11. What are the four pillars of OOP?</strong></p><p>The four pillars are:</p><ol><li><strong>Encapsulation</strong>: bundling data and behaviour while controlling access.</li><li><strong>Abstraction</strong>: exposing essential behaviour and hiding implementation details.</li><li><strong>Inheritance</strong>: deriving a new type from an existing type.</li><li><strong>Polymorphism</strong>: allowing one interface or base type to represent multiple implementations.</li></ol><p><strong>12. Explain encapsulation with a real-world example.</strong></p><p>Encapsulation protects an object’s internal state and exposes controlled operations.</p><pre>public class BankAccount<br>{<br>    private decimal balance;<br><br>    public decimal Balance =&gt; balance;<br><br>    public void Deposit(decimal amount)<br>    {<br>        if (amount &lt;= 0)<br>            throw new ArgumentException(&quot;Amount must be positive.&quot;);<br><br>        balance += amount;<br>    }<br>}</pre><p>The balance field cannot be changed directly from outside the class. This prevents invalid state.</p><p><strong>13. What is inheritance and where should it be used?</strong></p><p>Inheritance allows a derived class to reuse and extend a base class.</p><pre>public class Employee<br>{<br>    public string Name { get; set; }<br>}<br><br>public class Manager : Employee<br>{<br>    public void ApproveLeave() { }<br>}</pre><p>Use inheritance for a true “is-a” relationship. Do not use it merely to reuse code; composition is often safer and more flexible.</p><p><strong>14. What is polymorphism?</strong></p><p>Polymorphism allows the same operation to behave differently depending on the actual object.</p><pre>Animal animal = new Dog();<br>animal.Speak(); // Bark</pre><p>The variable is typed as Animal, but the overridden Dog.Speak() implementation executes at runtime.</p><p><strong>15. What is abstraction?</strong></p><p>Abstraction hides unnecessary implementation details and exposes only what the caller needs.</p><p>For example, a payment service may expose:</p><pre>public interface IPaymentService<br>{<br>    Task&lt;bool&gt; PayAsync(decimal amount);<br>}</pre><p>The caller knows how to request payment but does not need to know whether the implementation uses a bank API, card gateway, or wallet.</p><p><strong>16. What is the difference between compile-time and runtime polymorphism?</strong></p><p><strong>. Compile-time vs runtime polymorphism</strong></p><ul><li>Compile-time polymorphism is generally achieved through method overloading.</li><li>Runtime polymorphism is achieved through overriding, virtual methods, abstract classes, or interfaces.</li></ul><p>The compiler chooses an overloaded method, while runtime dispatch chooses an overridden implementation.</p><p><strong>17. Can a class implement multiple interfaces?</strong></p><p>Yes. A C# class can implement multiple interfaces.</p><pre>public class Employee : IPrintable, IExportable<br>{<br>    public void Print() { }<br>    public void Export() { }<br>}</pre><p>This provides multiple contracts without requiring multiple class inheritance.</p><p><strong>18. Why is multiple inheritance not supported in C# classes?</strong></p><p>C# avoids multiple class inheritance mainly to prevent ambiguity, especially the diamond problem. If two base classes define the same member, it becomes unclear which implementation should be inherited.</p><p>Interfaces provide a safer way to support multiple capabilities.</p><p><strong>19. What is the difference between aggregation and composition?</strong></p><p>Both describe relationships between objects.</p><ul><li><strong>Aggregation</strong>: a weak “has-a” relationship. The contained object can exist independently.</li><li><strong>Composition</strong>: a strong ownership relationship. The contained object’s lifetime depends on the owner.</li></ul><p>Example:</p><ul><li>A department aggregates employees; employees can exist after the department is removed.</li><li>An order composes order lines; order lines usually belong to that order.</li></ul><p><strong>20. What are sealed classes?</strong></p><p>A sealed class cannot be inherited.</p><pre>public sealed class SecurityTokenProvider<br>{<br>}</pre><p>Use it when extension would be unsafe, meaningless, or undesirable. A sealed method can also prevent further overriding.</p><h3>SOLID Principles</h3><p><strong>21. What does SOLID stand for?</strong></p><p>SOLID represents five object-oriented design principles:</p><ul><li><strong>S</strong> — Single Responsibility Principle.</li><li><strong>O</strong> — Open/Closed Principle.</li><li><strong>L</strong> — Liskov Substitution Principle.</li><li><strong>I</strong> — Interface Segregation Principle.</li><li><strong>D</strong> — Dependency Inversion Principle.</li></ul><p>These principles help create code that is easier to maintain, test, extend, and understand.</p><p><strong>22. Explain the Single Responsibility Principle.</strong></p><p>The Single Responsibility Principle states:</p><blockquote><em>A class should have one reason to change.</em></blockquote><p>A class should focus on one responsibility rather than handling unrelated operations.</p><p>Poor design:</p><pre>public class OrderService<br>{<br>    public void CreateOrder() { }<br>    public void SaveToDatabase() { }<br>    public void SendEmail() { }<br>    public void GenerateInvoice() { }<br>}</pre><p>This class handles order processing, persistence, email, and invoice generation.</p><p>Better design:</p><pre>public class OrderService<br>{<br>    private readonly IOrderRepository repository;<br><br>    public OrderService(IOrderRepository repository)<br>    {<br>        this.repository = repository;<br>    }<br><br>    public void CreateOrder() { }<br>}<br><br>public class EmailService<br>{<br>    public void SendEmail() { }<br>}<br><br>public class InvoiceService<br>{<br>    public void GenerateInvoice() { }<br>}</pre><p><strong>23. What is the Open/Closed Principle?</strong></p><p>The Open/Closed Principle states:</p><blockquote><em>Software entities should be open for extension but closed for modification.</em></blockquote><p>You should be able to add new behaviour without repeatedly changing stable existing code.</p><p>Poor design:</p><pre>public decimal CalculateDiscount(string customerType, decimal amount)<br>{<br>    if (customerType == &quot;Regular&quot;)<br>        return amount * 0.05m;<br><br>    if (customerType == &quot;Premium&quot;)<br>        return amount * 0.10m;<br><br>    return 0;<br>}</pre><p>Every new customer type requires modifying this method.</p><p>Better design:</p><pre>public interface IDiscountStrategy<br>{<br>    decimal Calculate(decimal amount);<br>}<br><br>public class PremiumDiscount : IDiscountStrategy<br>{<br>    public decimal Calculate(decimal amount) =&gt; amount * 0.10m;<br>}</pre><p>New discount strategies can be added without changing the existing calculation logic.</p><p><strong>24. What is the Liskov Substitution Principle?</strong></p><p>The Liskov Substitution Principle states:</p><blockquote><em>Objects of a derived class should be replaceable for objects of the base class without breaking the application.</em></blockquote><p>If a derived class changes the expected behaviour of the base class, the design may violate LSP.</p><p>For example, if a base Bird class containsFly(), then deriving Penguin from it may be problematic because penguins cannot fly. A better design is to separate flying behaviour:</p><pre>public interface IFlyingBird<br>{<br>    void Fly();<br>}</pre><p><strong>25. What is the Interface Segregation Principle?</strong></p><p>The Interface Segregation Principle states:</p><blockquote><em>Clients should not be forced to depend on methods they do not use.</em></blockquote><p>Avoid very large interfaces.</p><p>Poor design:</p><pre>public interface IWorker<br>{<br>    void Work();<br>    void Eat();<br>}</pre><p>A robot may work but does not need to eat.</p><p>Better design:</p><pre>public interface IWorkable<br>{<br>    void Work();<br>}<br><br>public interface IEatable<br>{<br>    void Eat();<br>}</pre><p>Classes can implement only the interfaces relevant to them.</p><p><strong>26. What is the Dependency Inversion Principle?</strong></p><p>The Dependency Inversion Principle states:</p><ol><li>High-level modules should not depend directly on low-level modules.</li><li>Both should depend on abstractions.</li><li>Abstractions should not depend on details.</li><li>Details should depend on abstractions.</li></ol><p>Poor design:</p><pre>public class OrderService<br>{<br>    private readonly SqlOrderRepository repository = new SqlOrderRepository();<br>}</pre><p>The service is tightly coupled to one repository implementation.</p><p>Better design:</p><pre>public class OrderService<br>{<br>    private readonly IOrderRepository repository;<br><br>    public OrderService(IOrderRepository repository)<br>    {<br>        this.repository = repository;<br>    }<br>}</pre><p><strong>27. How do SOLID principles improve maintainability?</strong></p><p>SOLID principles help by:</p><ul><li>Reducing coupling between classes.</li><li>Making code easier to test.</li><li>Allowing features to be added with fewer changes.</li><li>Reducing the risk of breaking existing behaviour.</li><li>Making responsibilities easier to understand.</li><li>Supporting replacement of implementations.</li><li>Improving long-term scalability of the codebase.</li></ul><p>They are guidelines, not rigid rules. Applying them excessively can also create unnecessary abstractions.</p><p><strong>28. Give an example of violating SRP in a real project.</strong></p><p>Suppose a controller:</p><ul><li>Validates an order.</li><li>Calculates tax.</li><li>Saves the order.</li><li>Sends an email.</li><li>Generates a PDF invoice.</li></ul><p>This controller has many reasons to change. A better design delegates each responsibility to appropriate services:</p><pre>public class OrdersController : ControllerBase<br>{<br>    private readonly IOrderService orderService;<br><br>    public OrdersController(IOrderService orderService)<br>    {<br>        this.orderService = orderService;<br>    }<br>}</pre><p>The controller should mainly handle HTTP concerns and delegate business logic.</p><p><strong>29. How does DI relate to DIP?</strong></p><ol><li>What happens when a class has too many responsibilities?</li></ol><h3>Exception Handling</h3><ol><li>What is the difference between try-catch and try-finally?</li><li>When should you use throw versus throw ex?</li><li>What is a custom exception?</li><li>How do you create and use one?</li><li>What is global exception handling in ASP.NET Core?</li><li>Why is exception handling important in production apps?</li><li>What is the difference between handled and unhandled exceptions?</li><li>How do you log exceptions properly?</li><li>What is exception filtering?</li><li>When should you avoid catching Exception?</li></ol><h3>Collections and Generics</h3><ol><li>What is the difference between Array and List&lt;T&gt;?</li><li>What is the difference between List&lt;T&gt; and Dictionary&lt;TKey, TValue&gt;?</li><li>What is the difference between IEnumerable, ICollection, and IList?</li><li>What is the difference between generic and non-generic collections?</li><li>What are hash-based collections?</li><li>What is a HashSet&lt;T&gt; used for?</li><li>What are generics?</li><li>Why are generics useful?</li><li>What is covariance and contravariance?</li><li>What are common collection performance considerations?</li></ol><h3>Delegates, Events, and Lambdas</h3><ol><li>What is a delegate?</li><li>What is the difference between a delegate and an event?</li><li>What are lambda expressions?</li><li>What is a multicast delegate?</li><li>What is the use of Func, Action, and Predicate?</li><li>How do events work in C#?</li><li>What is event subscription and unsubscription?</li><li>What are anonymous methods?</li><li>Where are delegates used in real applications?</li><li>What is the role of delegates in LINQ?</li></ol><h3>LINQ</h3><ol><li>What is LINQ?</li><li>What is the difference between method syntax and query syntax?</li><li>What is deferred execution?</li><li>What is immediate execution?</li><li>What is the difference between Select and SelectMany?</li><li>What is the difference between Where and FirstOrDefault?</li><li>What is the use of Any, All, and Contains?</li><li>What is grouping in LINQ?</li><li>What is projection in LINQ?</li><li>What are common LINQ performance issues?</li></ol><h3>Async, Await, and Multithreading</h3><ol><li>What is the purpose of async and await?</li><li>What is the difference between Task and Thread?</li><li>What is the difference between Task.Run and async/await?</li><li>What is deadlock in async programming?</li><li>What is the difference between concurrency and parallelism?</li><li>What is thread safety?</li><li>What are locks and when should they be used?</li><li>What is the difference between lock, Monitor, and SemaphoreSlim?</li><li>What is CancellationToken?</li><li>What are common pitfalls in asynchronous programming?</li></ol><h3>Garbage Collection and Memory</h3><ol><li>What is garbage collection in .NET?</li><li>What are generations in GC?</li><li>What is the Large Object Heap?</li><li>What is the difference between stack and heap?</li><li>What is memory leak in .NET?</li><li>How does IDisposable help?</li><li>What is the finalizer?</li><li>What is the difference between Dispose and finalizer?</li><li>What is object lifetime?</li><li>What causes high memory usage in .NET applications?</li></ol><h3>ASP.NET Core Basics</h3><ol><li>What is ASP.NET Core?</li><li>What is the difference between ASP.NET and ASP.NET Core?</li><li>What is middleware?</li><li>What is the request pipeline?</li><li>What is dependency injection in ASP.NET Core?</li><li>What is configuration in ASP.NET Core?</li><li>What are appsettings files?</li><li>What is environment-based configuration?</li><li>What is logging in ASP.NET Core?</li><li>What is model binding?</li></ol><h3>ASP.NET Core Web API</h3><ol><li>What is REST?</li><li>What is the difference between PUT and PATCH?</li><li>What is the difference between 200, 201, 400, 401, 403, and 500 status codes?</li><li>What are action filters?</li><li>What is model validation?</li><li>How do you handle validation errors in Web API?</li><li>What is API versioning?</li><li>What are DTOs and why do we use them?</li><li>What is content negotiation?</li><li>What are best practices for REST API design?</li></ol><h3>Authentication and Authorization</h3><ol><li>What is the difference between authentication and authorization?</li><li>What is JWT?</li><li>What is the structure of a JWT token?</li><li>How does JWT authentication work in ASP.NET Core?</li><li>What are claims?</li><li>What is role-based authorization?</li><li>What is policy-based authorization?</li><li>What is ASP.NET Core Identity?</li><li>What is the use of refresh tokens?</li><li>What are common JWT security risks?</li></ol><h3>Entity Framework Core</h3><ol><li>What is EF Core?</li><li>What is the difference between EF Core and ADO.NET?</li><li>What is the difference between Code First and Database First?</li><li>What are migrations?</li><li>What is change tracking?</li><li>What is lazy loading?</li><li>What is eager loading?</li><li>What is explicit loading?</li><li>What is the difference between Add, Attach, and Update?</li><li>How do you optimize EF Core queries?</li></ol><h3>SQL Server</h3><ol><li>What is the difference between INNER JOIN and LEFT JOIN?</li><li>What is the difference between WHERE and HAVING?</li><li>What are subqueries?</li><li>What is a CTE?</li><li>What are window functions?</li><li>What is the difference between RANK, DENSE_RANK, and ROW_NUMBER?</li><li>What are indexes?</li><li>What is the difference between clustered and non-clustered indexes?</li><li>What are stored procedures?</li><li>What are triggers?</li></ol><h3>Angular and TypeScript</h3><ol><li>What is Angular?</li><li>What is TypeScript and why is it used?</li><li>What is the difference between component and module?</li><li>What is data binding in Angular?</li><li>What are directives?</li><li>What are services in Angular?</li><li>What is dependency injection in Angular?</li><li>What are observables?</li><li>What is the difference between observable and promise?</li><li>What is RxJS used for?</li></ol><h3>Angular Advanced</h3><ol><li>What is the Angular component lifecycle?</li><li>What is the difference between template-driven and reactive forms?</li><li>What is lazy loading in Angular?</li><li>What is route guarding?</li><li>What are pipes?</li><li>What is the difference between pure and impure pipes?</li><li>What is state management?</li><li>What are common Angular performance optimizations?</li><li>How do you handle HTTP errors in Angular?</li><li>What are best practices for Angular architecture?</li></ol><h3>HTML, CSS, JavaScript</h3><ol><li>What is the difference between var, let, and const?</li><li>What are arrow functions?</li><li>What is destructuring?</li><li>What are promises?</li><li>What is event bubbling?</li><li>What is the difference between == and ===?</li><li>What are CSS Flexbox and Grid?</li><li>What is responsive design?</li><li>What are semantic HTML tags?</li><li>What is the difference between synchronous and asynchronous JavaScript?</li></ol><h3>System Design</h3><ol><li>How would you design a secure authentication flow?</li><li>How would you design a scalable Web API?</li><li>How would you handle caching in a full stack application?</li><li>How do you reduce database load in a high-traffic system?</li><li>What is the role of microservices?</li><li>When should you avoid microservices?</li><li>How would you design logging and monitoring?</li><li>How would you implement rate limiting?</li><li>What is clean architecture?</li><li>How do you separate concerns in a full stack app?</li></ol><h3>Coding Round</h3><ol><li>Write a C# program to reverse a string.</li><li>Write a C# program to find the second largest number in an array.</li><li>Write a C# program to check whether a string is a palindrome.</li><li>Write a SQL query to find duplicate records.</li><li>Write a SQL query to get the nth highest salary.</li><li>Write a JavaScript function to remove duplicates from an array.</li><li>Write an Angular component to display a list of users.</li><li>Write a C# program to count character occurrences in a string.</li><li>Write a SQL query using ROW_NUMBER.</li><li>Write a C# program to implement a simple dependency injection example.</li></ol><h3>HR and Behavioral</h3><ol><li>Tell me about yourself.</li><li>Why do you want this job?</li><li>What are your strengths?</li><li>What is your biggest weakness?</li><li>Where do you see yourself in 5 years?</li><li>Why are you looking to change your current job?</li><li>Tell me about a challenging project you worked on.</li><li>Tell me about a time you handled conflict in a team.</li><li>How do you handle tight deadlines?</li><li>Why should we hire you?</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a00b5fa027ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Combinatorics and the Basics of Prime Numbers: A Practical Introduction]]></title>
            <link>https://shivamthakurdev.medium.com/combinatorics-and-the-basics-of-prime-numbers-a-practical-introduction-d6a193d46ebd?source=rss-7d0abb59c77e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6a193d46ebd</guid>
            <category><![CDATA[prime-numbers]]></category>
            <category><![CDATA[math]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[combinatorics]]></category>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[Shivam Thakur]]></dc:creator>
            <pubDate>Fri, 01 May 2026 15:53:44 GMT</pubDate>
            <atom:updated>2026-05-01T15:53:44.235Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5xBCohnaU0kPzMLKlJwE7g.png" /></figure><h4>1. Introduction: Why This Matters More Than You Think</h4><p>Imagine you’re sending a private message online. You expect it to stay private, right? Behind the scenes, that security depends heavily on <strong>prime numbers</strong>. Now imagine designing an algorithm that needs to efficiently sort, count, or explore possibilities. That’s where <strong>combinatorics</strong> steps in.</p><p>At first glance, these two areas of math might seem unrelated. One is about special numbers that only divide cleanly in two ways. The other is about counting arrangements and selections. But look closer, and you’ll find they often work together in surprising and useful ways.</p><p>In fact, many real-world systems — from cryptography to data science — quietly rely on the interaction between these ideas.</p><p>So let’s break them down in a way that actually makes sense.</p><h4>2. What Are Prime Numbers?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tzMbgbyiw9AFntLHc8Fu5w.png" /></figure><p>A <strong>prime number</strong> is a number greater than 1 that has exactly two distinct divisors: <strong>1 and itself</strong>.</p><p>That’s it. Simple definition.</p><h3>Examples:</h3><ul><li>2 → Prime</li><li>3 → Prime</li><li>4 → Not prime (divisible by 1, 2, and 4)</li><li>5 → Prime</li><li>6 → Not prime</li></ul><p>You can think of prime numbers as the <strong>building blocks of all numbers</strong>.</p><p>Just like molecules are made from atoms, every whole number can be broken down into a product of primes. For example:</p><ul><li>12 = 2 × 2 × 3</li><li>30 = 2 × 3 × 5</li></ul><p>This idea is called <strong>prime factorization</strong>, and it’s foundational in mathematics.</p><h3>Why do primes matter?</h3><ul><li>They’re used in <strong>encryption systems</strong> like RSA</li><li>They help in <strong>hashing algorithms</strong></li><li>They form the backbone of <strong>number theory</strong></li></ul><p>You might never see them directly, but they’re everywhere behind the scenes.</p><h3>3. Basics of Combinatorics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bqFwlblur1_4KXZL3sjjJQ.png" /></figure><p>Combinatorics is really about one question:</p><blockquote><em>“How many ways can something happen?”</em></blockquote><p>That’s it. Counting, but done smartly.</p><h3>The Addition and Multiplication Rules</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X4lOIZk2o7dH5motcJGW9Q.png" /><figcaption>The Addition and Multiplication Rules</figcaption></figure><p>These are the basic tools.</p><ul><li><strong>Addition Rule</strong>: If you can do task A in 3 ways and task B in 2 ways (and they don’t overlap), total ways = 3 + 2 = 5</li><li><strong>Multiplication Rule</strong>: If task A can happen in 3 ways and task B in 2 ways, total combined ways = 3 × 2 = 6</li></ul><h3>Permutations: When Order Matters</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GuSXarvS0Lau8il3aS99tA.png" /><figcaption>Permutations: When Order Matters</figcaption></figure><p>A <strong>permutation</strong> is an arrangement.</p><p>Think of it like seating people in chairs. Who sits where matters.</p><p><strong>Example:</strong></p><p>How many ways can we arrange the letters A, B, C?</p><ul><li>ABC</li><li>ACB</li><li>BAC</li><li>BCA</li><li>CAB</li><li>CBA</li></ul><p>Total = 6 ways</p><p>Formula:</p><ul><li>For <em>n</em> distinct items → <strong>n! (n factorial)</strong></li><li>3! = 3 × 2 × 1 = 6</li></ul><p>Your notes (page 4) show this exact idea using characters and arrangements .</p><h3>Combinations: When Order Doesn’t Matter</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f2MenE0iQRfoeZERExifGg.png" /><figcaption>Combinations: When Order Doesn’t Matter</figcaption></figure><p>Now imagine picking toppings for a pizza. Does the order matter?</p><p>No.</p><p>That’s a <strong>combination</strong>.</p><p><strong>Example:</strong></p><p>Choose 2 fruits from {Apple, Banana, Mango}</p><ul><li>Apple &amp; Banana</li><li>Apple &amp; Mango</li><li>Banana &amp; Mango</li></ul><p>Total = 3 ways</p><p>Formula:</p><p>[C(n, r) = \frac{n!}{r!(n-r)!}]</p><p>Combinations as selecting items where order doesn’t matter .</p><h3>4. Where They Intersect</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ptpr9UOqAy1wlAT8cSrnUA.png" /><figcaption>Where They Intersect</figcaption></figure><p>Now the interesting part.</p><p>Where do <strong>prime numbers</strong> and <strong>combinatorics</strong> meet?</p><p>More often than you’d expect.</p><h3>4.1) Counting Divisors Using Prime Factorization</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JGVSXkekPnwX_XFv0fnQ6Q.png" /><figcaption>Counting Divisors Using Prime Factorization</figcaption></figure><p>Suppose we want to count how many factors a number has.</p><p>Take:</p><ul><li>12 = ²² × ³¹</li></ul><p>To find total divisors:</p><ul><li>(2 + 1)(1 + 1) = 3 × 2 = 6 divisors</li></ul><p>Why does this work?</p><p>Because we’re counting combinations of powers:</p><ul><li>Choose exponent of 2 (0, 1, or 2)</li><li>Choose exponent of 3 (0 or 1)</li></ul><p>Each choice is a combinatorial decision.</p><h3>4.2) Pascal’s Triangle and Prime Patterns</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NdJIdlJYlr1yBS0tzHEI-A.png" /><figcaption>Pascal’s Triangle and Prime Patterns</figcaption></figure><p>Pascal’s Triangle is built using combinations.</p><p>It looks like this (first few rows):</p><pre>1<br>1 1<br>1 2 1<br>1 3 3 1<br>1 4 6 4 1</pre><p>Here’s the cool part:</p><ul><li>If the row number is a <strong>prime</strong>, all inner numbers are divisible by that prime.</li></ul><p>Example (row 5):</p><ul><li>1 5 10 10 5 1<br>All middle numbers divisible by 5</li></ul><p>Why?</p><p>Because combinations like C(p, k) (where p is prime) have special divisibility properties.</p><p>This connection is subtle but powerful.</p><h3>4.3) Prime Numbers in Combinatorial Proofs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AS1hVWbs0MS8jZKGz0BDcg.png" /><figcaption>Prime Numbers in Combinatorial Proofs</figcaption></figure><p>Many combinatorics proofs rely on primes to simplify reasoning.</p><p>For example:</p><ul><li>Proving divisibility</li><li>Simplifying fractions in combinations</li><li>Understanding symmetry in counting</li></ul><p>Primes act like “clean” numbers with predictable behavior.</p><h3>4.4) Sieve of Eratosthenes Meets Counting</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4eTMHZDm1D2KOIP3xuGodg.png" /><figcaption>Sieve of Eratosthenes Meets Counting</figcaption></figure><p>Want to find all primes up to N?</p><p>Use the <strong>Sieve of Eratosthenes</strong>.</p><p>Start by assuming all numbers are prime, then eliminate multiples .</p><p>This process is inherently combinatorial:</p><ul><li>You systematically remove numbers based on patterns (multiples)</li><li>You’re essentially filtering a set using counting logic</li></ul><h3>5. Practical Applications</h3><p>Let’s bring this back to real life.</p><h3>Cryptography</h3><p>Modern encryption relies on large prime numbers.</p><p>Why primes?</p><p>Because factoring large numbers into primes is hard.</p><p>Combinatorics helps estimate:</p><ul><li>How many possible keys exist</li><li>How secure a system is</li></ul><h3>Algorithms</h3><p>Sorting, searching, and optimization problems often use combinatorics.</p><p>Prime numbers show up in:</p><ul><li>Hash functions</li><li>Random number generation</li><li>Data structures</li></ul><h3>Data Science</h3><p>Combinatorics helps answer:</p><ul><li>How many possible outcomes exist?</li><li>What’s the probability of an event?</li></ul><p>Prime-based structures help ensure:</p><ul><li>Uniform distribution</li><li>Reduced collisions in hashing</li></ul><h3>Computer Science Interviews</h3><p>You’ll often see problems like:</p><ul><li>Count number of subsets</li><li>Generate permutations</li><li>Check for primes efficiently</li></ul><h3>6. Conclusion: What to Take Away</h3><p>Let’s keep it simple.</p><ul><li><strong>Prime numbers</strong> are the building blocks of integers</li><li><strong>Combinatorics</strong> is the art of counting possibilities</li><li>Together, they help solve problems involving structure, patterns, and efficiency</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6a193d46ebd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zero To Mastery: Complete Machine Learning with Python: Regression & Classification Projects, End…]]></title>
            <link>https://shivamthakurdev.medium.com/mds-2410-data-mining-and-artificial-intelligence-9c4f7a94ba7b?source=rss-7d0abb59c77e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c4f7a94ba7b</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[data-science-courses]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Shivam Thakur]]></dc:creator>
            <pubDate>Tue, 21 Apr 2026 14:23:58 GMT</pubDate>
            <atom:updated>2026-09-02T06:22:52.891Z</atom:updated>
            <content:encoded><![CDATA[<h3>Zero To Mastery: Complete Machine Learning with Python: Regression &amp; Classification Projects, End to End (in Google Colab)</h3><p>We are not going to cover the theoretical topics of regression and classification here. We are for the practical exercises of the ML using the Google Colab environment.</p><p>For practice, we have provided bike sharing data and heart disease dataset, and we apply different techniques like Linear Regression &amp; Classification models and more.</p><h3>1. Linear Regression on Bike Sharing (day.csv)</h3><p><a href="https://github.com/ShivamThakurDev/ShivamDevHub/blob/main/Study%20Material/Dataset/day.csv">ShivamDevHub/Study Material/Dataset/day.csv at main · ShivamThakurDev/ShivamDevHub</a></p><p>Steps carried out:</p><h4>1) Load and inspect the data</h4><ul><li>The <strong><em>day.csv</em> </strong>dataset has <strong><em>731 rows X 16 columns</em></strong> and includes variables such as <strong><em>season, yr, mnth, holiday, weekday, workingday, weathersit, temp, atemp, hum, windspeed</em>,</strong> and the target variable <strong><em>cnt</em></strong>(total bike rentals).</li></ul><h4>2) Prepare features and target</h4><ul><li>Dropped identifier/date columns <strong>(<em>instant, dteday</em>) </strong>and fields <strong>(<em>casual, registered)</em></strong><em> </em>that directly sum to the target.</li><li>Selected features: <strong><em>season, yr, mnth, holiday, weekday, working, weathersit, temp, atemp, hum, windspeed</em></strong><em>.</em></li><li>Target:<strong> <em>cnt.</em></strong></li></ul><h4>3) Train-test split and scaling</h4><ul><li>Split the data <strong><em>80/20</em></strong> into training and test sets.</li><li>Standardised features using<em> </em><strong><em>StandardScaler.</em></strong></li></ul><h4>4) Train Linear Regression model</h4><ul><li>Used <strong><em>LinearRegression()</em></strong><em> </em>from scikit-learn.</li><li>Trained on the scaled training set and predicted on the test set.</li></ul><h4>5) Evaluate</h4><ul><li><strong>R² score ≈ 0.83</strong> and <strong>MSE ≈ 691k</strong>, indicating good fit</li><li>Plotted actual vs. predicted counts and residuals.</li></ul><h4>Outputs &amp; Visualisations:</h4><ul><li><strong>Actual vs. Predicted plot </strong>— points close to the diagonal show the model is capturing the trend.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*gbfam3JkH-Eww1aGc5eK_Q.png" /></figure><ul><li><strong>Residual plot — </strong>residuals (errors) scatter around zero without obvious patterns, which supports model approprateness.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*pwSa1I4wqCH_qGxvCMCklQ.png" /></figure><h3>2. Classification on Heart Disease (heart.csv)</h3><p><a href="https://github.com/ShivamThakurDev/ShivamDevHub/blob/main/Study%20Material/Dataset/heart.csv">ShivamDevHub/Study Material/Dataset/heart.csv at main · ShivamThakurDev/ShivamDevHub</a></p><p>Steps carried out:</p><h4>1) Load and inspect the data</h4><ul><li>The <em>heart.csv </em>dataset has <em>1025 rows X 14 columns.</em> The target column is <em>target </em>(1 = disease present, 0 = no disease).</li></ul><h4>2) Prepare features and target</h4><ul><li>Features: all columns except <em>target</em>.</li><li>Performed an <em>80/20 </em>stratified split to preserve class distribution.</li><li>Scaled features for logistic regression (decision trees don’t need scaling).</li></ul><h4>3) Train models</h4><ul><li><strong>Logistic Regression: </strong>LogisticRegression(max_iter=1000).</li><li><strong>Decision Tree Classifier</strong>: DecisionTreeClassifier(random_state=42).</li></ul><h4>4) Evaluate</h4><ul><li>For each model, calculated <strong>accuracy, precision, recall </strong>and <strong>F1 score.</strong></li><li>Generated a confusion matrix for logistic regression and a bar chart comparing accuracies.</li></ul><p>Metrics:</p><pre>| Model               | Accuracy | Precision | Recall | F1 Score |<br>| ------------------- | -------: | --------: | -----: | -------: |<br>| Logistic Regression |     0.81 |      0.76 |   0.91 |     0.83 |<br>| Decision Tree       |     0.99 |      1.00 |   0.97 |     0.99 |</pre><p>The decision tree achieves higher accuracy on this dataset, but be cautious: its near-perfect performance on the test set suggests potential over-fitting, so cross-validation is recommended for robust evaluation.</p><p><strong>Outputs &amp; Visualisations:</strong></p><ul><li><strong>Confusion matrix (logistic regression) — </strong>shows true/false positives/negatives; numbers on the diagonal indicate correct predictions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*LoOCcR1ICkCSeVebnjNtwA.png" /></figure><ul><li><strong>Accuracy comparison bar chart — </strong>compares the two models; the decision tree bar is noticeably higher.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*RG46dZNbD1Bk-a5NHUyFXg.png" /></figure><p>You can run locally (e.g. in Google Colab) for the regression task; adapt it for classification by switching models:</p><pre>#To upload a file from local <br>from google.colab import files<br>uploaded = files.upload()<br><br>import pandas as pd<br>from sklearn.model_selection import train_test_split<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.linear_model import LinearRegression<br>from sklearn.metrics import r2_score, mean_squared_error<br><br># Load dataset<br>df = pd.read_csv(&#39;/content/day.csv&#39;)# Feature selection and target<br>features = [&#39;season&#39;, &#39;yr&#39;, &#39;mnth&#39;, &#39;holiday&#39;, &#39;weekday&#39;, &#39;workingday&#39;,<br>            &#39;weathersit&#39;, &#39;temp&#39;, &#39;atemp&#39;, &#39;hum&#39;, &#39;windspeed&#39;]<br>X = df[features]<br>y = df[&#39;cnt&#39;]<br><br># Train-test split<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)# Standardize features<br>scaler = StandardScaler()<br>X_train_scaled = scaler.fit_transform(X_train)<br>X_test_scaled = scaler.transform(X_test)<br><br># Train model<br>model = LinearRegression()<br>model.fit(X_train_scaled, y_train)<br><br># Predict and evaluate<br>y_pred = model.predict(X_test_scaled)<br>print(&#39;R²:&#39;, r2_score(y_test, y_pred))<br>print(&#39;MSE:&#39;, mean_squared_error(y_test, y_pred))</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c4f7a94ba7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Master DSA Cheat Sheet — PART-06: Trees]]></title>
            <link>https://shivamthakurdev.medium.com/master-dsa-cheat-sheet-part-05-trees-a33a52c5173c?source=rss-7d0abb59c77e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a33a52c5173c</guid>
            <category><![CDATA[cheatsheet]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[binary-tree]]></category>
            <dc:creator><![CDATA[Shivam Thakur]]></dc:creator>
            <pubDate>Wed, 15 Apr 2026 13:46:54 GMT</pubDate>
            <atom:updated>2026-04-15T14:01:04.306Z</atom:updated>
            <content:encoded><![CDATA[<p>In our previous parts, we covered the basics of queue data structure. Today, we dive into one of the most powerful tools in a programmer’s arsenal: Trees.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*Lknw9orQ798VTzUc.jpeg" /></figure><h3>1. Introduction to Trees</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T63I4F8s2gTm2OalluZg-Q.png" /></figure><p>A tree is a <strong>hierarchical data structure</strong>. It comes under the non-linear data structure category, which is quite different in terms of data storage from linear data structures like arrays, linked lists, stacks, and queues.</p><p>The structure of a tree is similar to a company organisation chart or a family tree, which represents the levels in the relationship.</p><pre>        1<br>       / \<br>      2   3<br>     / \   \<br>    4   5   6</pre><h3>2. Basic Terminology</h3><p>Understanding these terms in key:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZWo30xas97waLfqiH2_CpA.png" /></figure><ul><li><strong>Node</strong>: Basic unit of a tree</li><li><strong>Root</strong>: Topmost node(has no parent)</li><li><strong>Parent</strong>: A node that has children</li><li><strong>Child</strong>: Node directly connected below a parent</li><li><strong>Ancestor</strong>: Any node above a given node</li><li><strong>Descendant</strong>: Any node below a given node</li><li><strong>Siblings</strong>: Nodes with the same parent</li><li><strong>Leaf Node</strong>: Node with no children</li></ul><h3>3. Tree Properties:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CbK1QYYD4zn_rAkQPe8rwQ.png" /></figure><h4>Height of a Node</h4><ul><li>Number of edges in the longest path from that node to a leaf</li><li>Height of a leaf node = 0</li></ul><h4>Height of Tree</h4><ul><li>Height of the root node</li></ul><p><strong><em>Formula idea:</em></strong></p><ul><li>Height(node) = max(height(left),height(right)) + 1</li></ul><h3><strong>4. Binary Tree:</strong></h3><p>A binary tree is a tree where each node can have at most 2 children:</p><ul><li>Left child</li><li>Right child</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aqQgDOwTuIVIgmtutVYXEQ.png" /></figure><h4>Node Structure:</h4><pre>class Node:<br>  def __init__(self,value):<br>      self.value = value<br>      self.left = None<br>      self.right = None<br>  <br>  def inorder_traversal(root):<br>      if root:<br>          inorder_traversal(root.left)<br>          print<br> </pre><h3>5. Types of Binary Trees</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yAjXhQxy9McRcV49UeyP-Q.png" /></figure><h4>1. Proper (Full) Binary Tree</h4><ul><li>Every node has either <strong>0 or 2 children</strong></li></ul><h4>2. Complete Binary Tree</h4><ul><li>All levels are filled</li><li>The last level is filled <strong>from left to right</strong></li></ul><h4>3. Perfect Binary Tree</h4><ul><li>All levels are fully filled</li><li>Total nodes = 2^h — 1</li></ul><h3>6. Recursion Strategy (Very Important)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XBYEdoaGgmEKEtxrcBFmxQ.png" /></figure><p>When solving tree problems using recursion:</p><ol><li><strong>Assume </strong>your function works correctly.</li><li>Solve subproblems using that assumption</li><li>Define a <strong>base condition</strong></li></ol><h3>7. Tree Traversals</h3><p>Traversal means visiting all nodes in a specific order.</p><h4>🔹 1. Preorder Traversal (DLR)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ix58mLD6060vQsh6VbTYOA.png" /></figure><p><strong>Rule:</strong> Root → Left → Right</p><ol><li>Visit root</li><li>Traverse left subtree</li><li>Traverse right subtree</li></ol><p>Diagram with order:</p><pre>        1(1)<br>       /    \<br>   2(2)     3(5)<br>   /  \        \<br>4(3) 5(4)     6(6)      </pre><p>Step-by-step flow:</p><pre>Visit 1<br>Go left → Visit 2<br>Go left → Visit 4<br>Back → Visit 5<br>Back → Go right → Visit 3<br>Go right → Visit 6</pre><p>Code:</p><pre>def pre_order_traversal(root): #DLR<br>    if root:<br>        print(root.value,end=&quot;&quot;) #Step 1: Root<br>        pre_order_traversal(root.left)#Step 2: Left<br>        pre_order_traversal(root.right)#Step 3: Right</pre><p>Output</p><pre>1 → 2 → 4 → 5 → 3 → 6</pre><ul><li>Time Complexity: O(N)</li><li>Space Complexity: O(H)</li></ul><h4>🔹 2. Inorder Traversal (LDR)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RWEorl0DkRRxoivqS5UdkQ.png" /></figure><p><strong>Rule:</strong> Left → Root → Right</p><ol><li>Left subtree</li><li>Root</li><li>Right subtree</li></ol><p>Diagram with order:</p><pre>        1(4)<br>       /    \<br>   2(2)     3(5)<br>   /  \        \<br>4(1) 5(3)     6(6)</pre><p>Step-by-step flow:</p><pre>Go left → 4<br>Visit 4<br>Back → Visit 2<br>Visit 5<br>Back → Visit 1<br>Go right → Visit 3<br>Visit 6</pre><p>Code:</p><pre> def inorder_traversal(root):#(LDR)<br>     if root: <br>          inorder_traversal(root.left) #Step:1 Left<br>          print(root.value,end=&quot;&quot;) #Step 2: Root<br>          inorder_traversal(root.right) #Step 3: Right</pre><p>Output:</p><pre>4 → 2 → 5 → 1 → 3 → 6</pre><h4>🔹 3. Postorder Traversal (LRD)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZQbJXuDoRw-lH6FXzxLHiA.png" /></figure><p><strong>Rule:</strong> Left → Right → Root</p><ol><li>Left subtree</li><li>Right subtree</li><li>Root</li></ol><p>Diagram with order:</p><pre>        1(6)<br>       /    \<br>   2(3)     3(5)<br>   /  \        \<br>4(1) 5(2)     6(4)</pre><p>Step-by-step flow:</p><pre>Go left → 4 → Visit<br>Go right → 5 → Visit<br>Visit 2<br>Go right → 6 → Visit<br>Visit 3<br>Visit 1</pre><p>Code:</p><pre> def post_order_traversal(root):<br>        if root:<br>            post_order_traversal(root.left) #Step:1 Left<br>            post_order_traversal(root.right) #Step 2: Right<br>            print(root.value,end=&quot;&quot;) #Step 3: Root</pre><p>Output:</p><pre>4 → 5 → 2 → 6 → 3 → 1</pre><h4>🔹 4. Level Order Traversal (BFS)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3FucdoGCkM6h4nUs79eqOw.png" /></figure><p><strong>Rule:</strong> Level by level (left to right)</p><p>This traversal works <strong>level by level</strong> using a queue.</p><p>Levels:</p><pre>Level 0:        1<br>Level 1:      2   3<br>Level 2:    4  5   6</pre><p>Diagram:</p><pre>Step 1: 1<br>Step 2: 2 → 3<br>Step 3: 4 → 5 → 6</pre><p>Idea:</p><ol><li>Add root to the queue</li><li>Remove node</li><li>Print it</li><li>Add its children</li></ol><p>Code:</p><pre>from collections import deque<br><br># Definition for a  binary tree node<br># class TreeNode:<br>#    def __init__(self, x):<br>#        self.val = x<br>#        self.left = None<br>#        self.right = None<br><br>def level_order_traversal(self,A):<br>    if not A:<br>        return []<br>    result = []<br>    queue = deque([A])<br>    while queue:<br>          level_size = len(queue)<br>          level = []<br>        <br>          for _ in range(level_size):<br>              node = queue.popleft()<br>              level.append(node.val)<br>              if node.left:<br>                 queue.append(node.left)<br>              if node.right:<br>                 queue.append(node.right)<br>          result.append(level)<br>    return result</pre><p>Ouput:</p><pre>1 → 2 → 3 → 4 → 5 → 6</pre><h4>🔹 5. Left View Of Tree</h4><p>👉 First node of each level</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t3CNco26SAb90MHonVpG9A.png" /></figure><p>Levels:</p><pre>Level 0 → 1<br>Level 1 → 2<br>Level 2 → 4</pre><p>Code:</p><ul><li>i == 1→ prints the <strong>first node of each level</strong></li><li>That’s why it gives the <strong>left view</strong></li></ul><pre>from collections import deque<br><br>def left_view(root):<br>    if root is None:<br>        return<br><br>    q = deque()<br>    q.append(root)<br><br>    while q:<br>        size = len(q)<br><br>        for i in range(1, size + 1):<br>            curr = q.popleft()<br><br>            if i == 1:<br>                print(curr.data, end=&quot; &quot;)<br><br>            if curr.left is not None:<br>                q.append(curr.left)<br><br>            if curr.right is not None:<br>                q.append(curr.right)</pre><p>Output:</p><pre>1 → 2 → 4</pre><h4>🔹 6. Right View of Tree</h4><p>👉 Last node of each level</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*burRvUPvNcHp578_0IRyLA.png" /></figure><p>Levels:</p><pre>Level 0 → 1<br>Level 1 → 3<br>Level 2 → 6</pre><p>Code:</p><ul><li>i == size → prints the <strong>last node of each level</strong></li><li>That’s why it gives the <strong>right view</strong></li></ul><pre>from collections import deque<br><br>def right_view(root):<br>    if root is None:<br>        return<br><br>    q = deque()<br>    q.append(root)<br><br>    while q:<br>        size = len(q)<br><br>        for i in range(1, size + 1):<br>            curr = q.popleft()<br><br>            if i == size:<br>                print(curr.data, end=&quot; &quot;)<br><br>            if curr.left is not None:<br>                q.append(curr.left)<br><br>            if curr.right is not None:<br>                q.append(curr.right)</pre><p>Output:</p><pre>1 → 3 → 6</pre><h3>8. Conclusion:</h3><p>Here is a guide to tree structure for your last-minuterevision 👉.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*35WmfwgDxqXtvsC1mLOT4g.png" /></figure><ul><li>Trees are <strong>hierarchical</strong>, not linear</li><li>Recursion is the most natural way to solve tree problems</li><li>Traversals are fundamental and heavily used</li><li>BFS uses <strong>queues</strong>, DFS uses <strong>recursion/stack</strong></li><li>Views (left/right) depend on <strong>level-based processing</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a33a52c5173c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Master DSA Cheat Sheet — PART-04: Stacks]]></title>
            <link>https://shivamthakurdev.medium.com/master-dsa-cheat-sheet-part-04-stacks-c6092a9df444?source=rss-7d0abb59c77e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6092a9df444</guid>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[dsa-courses]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[stacks-queues]]></category>
            <dc:creator><![CDATA[Shivam Thakur]]></dc:creator>
            <pubDate>Sun, 12 Apr 2026 17:27:12 GMT</pubDate>
            <atom:updated>2026-04-12T17:27:12.944Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dvO4HVZ0kBtfnvrTPWQO1w.jpeg" /></figure><p>Let’s start with the basics: what is Stacks?</p><p>A stack is a data structure is a linear data structure which follows the LIFO (Last In First Out) principle, that mean’s insertion and deletion happens only from top.</p><h4>Applications of Stacks</h4><p>Stacks have several key applications:</p><ul><li>Expression Evaluation: Used in the evaluation of arithmetic expressions and in managing operator precedence.</li><li>Undo/Redo Functionality: Useful in applications requiring the reversal of recent actions.</li><li>Recursion Handling: Internally used to keep track of function calls in recursion.</li></ul><h4>Real-Life Analogies:</h4><ol><li>Pile of Plates: Similar to a stack, you can only add or remove plates from the top of the pile.</li><li>Stack of Chairs: Chairs placed on top of each other, highlighting the LIFO nature.</li></ol><h4>Stack Operations</h4><p>Basic Operations</p><ol><li><strong>Push: </strong>Add an element at the top of the stack.</li><li><strong>Pop: </strong>Remove the top element without removing it.</li><li><strong>Peek: </strong>Retrieve the top element without removing it.</li></ol><p>These operations are normally performed in constant time, i.e., O(1)</p><h4>Stack Implementation Using Arrays</h4><p>Stacks can be effectively implemented using arrays. In this approach:</p><ul><li>Elements are inserted at the current size index.</li><li>For the pop operation, it’s sufficient to decrement the size index rather than actually deleting elements.</li></ul><p>Handling Errors</p><ul><li>Stack Overflow : Occurs when pushing elements onto a full stack.</li><li>Stack Underflow: Occurs when attempting to pop from an empty stack.</li></ul><p>Evaluting Expressions</p><p>Postfix (Reverse Polish Notation) Expression Evalution</p><ul><li>Postfix Expressions: These expressions contain operands followed by their operators, eliminating any ambiguity in operator precedence.</li><li>Evaluation Process:</li></ul><ol><li>Travese the array of the expression’s elements.</li><li>Push operands onto the stack</li><li>When an operator is encountered, pop the required number of operands, apply the operator, and push the result back onto the stack.</li></ol><p>Example</p><p>For an infix expression like ((8/(4–2)+ 6) * 9:</p><ul><li>Convert to postfix: 8 4 2 0- /6 + 9 *</li><li>Evaluate using a stack: Perform operations in sequence until a single final result remains.</li></ul><p>Problems Involving Stacks</p><p>Nearest Smaller Elements</p><p>Given an array, the task is to find the nearest smaller element for each index:</p><ul><li>Nearest Smaller on the Left: Travese the array, maintaining a stack of potential candidates for the nearest smaller element.</li></ul><p>Balanced Parantheses</p><p>Balancing parantheses is a classic stack problem where:</p><ul><li>Opening brackets are pushed onto a stack.</li><li>On encountering a closing bracket, check for a matching opening bracket by popping from the stack</li></ul><p>Understanding and Applying Variations</p><p>Possible variations on problems with stack include:</p><ul><li>Nearest Smaller or Greater Element on the Right.</li><li>Changing direction and conditions to find different nearest elements on either side.</li></ul><p>In conclusion, stacks are a fundamental data structure with significant applications in both theoretical and practical computing scenarios. Mastery of stack operations and problem and</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6092a9df444" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Interviewer Asked Me These Simple Questions & I Couldn’t Answer Them]]></title>
            <link>https://shivamthakurdev.medium.com/the-interviewer-asked-me-these-simple-questions-i-couldnt-answer-them-2e6ffc97335b?source=rss-7d0abb59c77e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e6ffc97335b</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[job-interview]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Shivam Thakur]]></dc:creator>
            <pubDate>Thu, 09 Apr 2026 10:41:30 GMT</pubDate>
            <atom:updated>2026-04-09T10:41:30.034Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*40KKgiBKChugC8vF1MFz5g.png" /></figure><p>Recently, I had an interview that I was preparing for. As you know, sometimes we just get overprepared, forgetting to cover the most basic stuff, which is relatively very close to our job, <strong><em>problem-solving.</em></strong></p><p>They simply asked me these questions:</p><h3>1. Write a program to count duplicate characters in a string</h3><p>Example: &quot;Amila Clark&quot; → A: 3, L: 2</p><p>This is a basic problem. I’ve solved harder ones.</p><p>But in that moment, I couldn’t structure a clean answer quickly.</p><p>Here’s the correct way to approach it:</p><pre>//Write a program to code that can count the number of duplicate characters in this string  &quot;Amila Clark&quot; <br>// For example: A: 3<br><br>//Code :<br>using System;<br>using System.Collections.Generic;<br><br>class Program<br>{<br>    static void Main()<br>    {<br>        string input = &quot;Amila Clark&quot;;<br><br>        // Convert to lowercase to count A and a as same<br>        input = input.ToLower();<br><br>        Dictionary&lt;char, int&gt; charCount = new Dictionary&lt;char, int&gt;();<br><br>        foreach (char c in input)<br>        {<br>            // Ignore spaces<br>            if (c == &#39; &#39;)<br>                continue;<br><br>            if (charCount.ContainsKey(c))<br>                charCount[c]++;<br>            else<br>                charCount[c] = 1;<br>        }<br><br>        Console.WriteLine(&quot;Duplicate characters:&quot;);<br><br>        foreach (var item in charCount)<br>        {<br>            if (item.Value &gt; 1)<br>            {<br>                Console.WriteLine($&quot;{char.ToUpper(item.Key)} : {item.Value}&quot;);<br>            }<br>        }<br>    }<br>}</pre><h3>2. What is a Clustered Index vs. a Non-Clustered Index?</h3><h3>📌 Clustered Index</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/0*-1ktEGw2vz59mCaT" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-h7IMZV79EuLatYh" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/0*4Blp5pK2UrsrBiMk" /></figure><h3>✅ Definition</h3><p>A <strong>clustered index</strong> defines the <strong>physical order of data</strong> in a table.</p><h3>💡 Key Points</h3><ul><li>Data is <strong>stored in sorted order</strong></li><li>Table can have <strong>only ONE clustered index</strong></li><li>The <strong>leaf node = actual data rows</strong></li><li>Faster for <strong>range queries</strong> (e.g., BETWEEN, ORDER BY)</li></ul><h3>🧠 Example</h3><p>If you create a clustered index on Id:</p><pre>CREATE CLUSTERED INDEX idx_id ON Students(Id);</pre><p>👉 Data in table will be physically sorted by Id</p><h3>📌 Non-Clustered Index</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/0*G-dlYHYOi-M6dnmU" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QtsETStuWqNykU8x" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*v164zyXsoOfXA1rQ" /></figure><h3>✅ Definition</h3><p>A <strong>non-clustered index</strong> is a <strong>separate structure</strong> that stores pointers to actual data.</p><h3>💡 Key Points</h3><ul><li>Does <strong>NOT change physical data order</strong></li><li>Table can have <strong>multiple non-clustered indexes</strong></li><li>Leaf node contains <strong>index + pointer (row address)</strong></li><li>Slightly slower than clustered (extra lookup)</li></ul><h3>🧠 Example</h3><pre>CREATE NONCLUSTERED INDEX idx_name ON Students(Name);</pre><p>👉 Index stores Name + pointer to actual row</p><h3>⚡ Key Differences (INTERVIEW GOLD)</h3><p>FeatureClustered IndexNon-Clustered IndexData StoragePhysically sortedSeparate structureCountOnly 1Multiple allowedSpeedFasterSlightly slowerLeaf NodeActual dataPointer to dataUse CasePrimary key, range queriesSearch/filter columns</p><h3>🎯 Best Way to Explain in Interview</h3><p>👉 Say this:</p><blockquote><em>“Clustered index stores data physically in sorted order, so it directly contains the data. Non-clustered index is a separate structure that holds pointers to the actual data rows, allowing multiple indexes per table.”</em></blockquote><h3>3. Can we have multiple constructors in a class?</h3><p>Yes ✅ — <strong>you can have multiple constructors in a class</strong> in C#.<br> This is called <strong>Constructor Overloading</strong>.</p><h3>📌 What is Constructor Overloading?</h3><ul><li>Multiple constructors with <strong>different parameter lists</strong></li><li>Same class, same name, different signatures</li></ul><h3>✅ Example in C#</h3><pre>class Student<br>{<br>    public string Name;<br>    public int Age;<br><br>    // Default constructor<br>    public Student()<br>    {<br>        Name = &quot;Unknown&quot;;<br>        Age = 0;<br>    }<br><br>    // Parameterized constructor<br>    public Student(string name)<br>    {<br>        Name = name;<br>        Age = 0;<br>    }<br><br>    // Another constructor<br>    public Student(string name, int age)<br>    {<br>        Name = name;<br>        Age = age;<br>    }<br>}<br><br>class Program<br>{<br>    static void Main()<br>    {<br>        Student s1 = new Student();<br>        Student s2 = new Student(&quot;Shivam&quot;);<br>        Student s3 = new Student(&quot;Shivam&quot;, 25);<br><br>        Console.WriteLine($&quot;{s1.Name}, {s1.Age}&quot;);<br>        Console.WriteLine($&quot;{s2.Name}, {s2.Age}&quot;);<br>        Console.WriteLine($&quot;{s3.Name}, {s3.Age}&quot;);<br>    }<br>}</pre><h3>⚡ Key Points (Interview Style)</h3><ul><li>✔ Constructors must have <strong>same name as class</strong></li><li>✔ Differentiated by <strong>number/type of parameters</strong></li><li>✔ Improves <strong>flexibility &amp; readability</strong></li><li>❌ You cannot have two constructors with <strong>same signature</strong></li></ul><h3>🧠 One-Line Answer (Say This in Interview)</h3><blockquote><em>“Yes, C# supports multiple constructors in a class using constructor overloading, where each constructor has a different parameter list.”</em></blockquote><h3>4. Abstract Class vs Interface</h3><h3>📌 Abstract Class</h3><h3>✅ Definition</h3><p>A class that <strong>cannot be instantiated</strong> and can contain both:</p><ul><li>Abstract methods (no implementation)</li><li>Concrete methods (with implementation)</li></ul><h3>🧠 Example</h3><pre>abstract class Animal<br>{<br>    public abstract void MakeSound(); // no body<br><br>    public void Sleep()<br>    {<br>        Console.WriteLine(&quot;Sleeping...&quot;);<br>    }<br>}</pre><h3>📌 Interface</h3><h3>✅ Definition</h3><p>A contract that <strong>only defines what to do</strong>, not how<br> (All methods are abstract by default — no implementation)</p><h3>🧠 Example</h3><pre>interface IAnimal<br>{<br>    void MakeSound(); // no body<br>}</pre><blockquote><em>Abstract class is used when we need shared implementation along with abstraction, while interface is used to define a contract that multiple classes can implement, supporting multiple inheritance.</em></blockquote><h3>🎯 When to Use What?</h3><h3>Use Abstract Class when:</h3><ul><li>You want <strong>common code (shared logic)</strong></li><li>There is a <strong>base relationship</strong> (is-a)</li></ul><p>👉 Example: Animal → Dog</p><h3>Use Interface when:</h3><ul><li>You want <strong>multiple inheritance</strong></li><li>You want to define <strong>capabilities</strong></li></ul><p>👉 Example:<br> ICanFly, ICanRun</p><h3>⚡ Final Thought</h3><p>I walked into that interview thinking I was overprepared.</p><p>I walked out realizing I had skipped the most important layer.</p><p>The basics.</p><p>If you’re preparing right now, don’t make the same mistake.</p><p>Because sometimes, the question that looks the easiest…<br> is the one that decides everything.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e6ffc97335b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Master DSA Cheat Sheet — PART-04: Linked List]]></title>
            <link>https://shivamthakurdev.medium.com/master-dsa-cheat-sheet-part-04-linked-list-3ceaaa5233e4?source=rss-7d0abb59c77e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ceaaa5233e4</guid>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[cheatsheet]]></category>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[linked-lists]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Shivam Thakur]]></dc:creator>
            <pubDate>Sun, 05 Apr 2026 09:47:49 GMT</pubDate>
            <atom:updated>2026-04-05T09:47:49.665Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dvO4HVZ0kBtfnvrTPWQO1w.jpeg" /></figure><p>Let’s start with the basics: what is a Linked List?</p><p>A linked list is a data structure used to store values in a chain-like form, similar to a train. At the start, we have the engine of the train, and the rest are the carrier bogies connected one after another.</p><p>In the same way, in a linked list, the structure consists of units we call nodes (like bogies), and the starting point is called the head (like the engine).</p><p>Just like in a train, if the engine is lost, the rest of the bogies lose connection. Similarly, if the head of a linked list is lost, there is a high chance that the rest of the attached nodes can also be lost. So, we need to be careful with the head.</p><h3>Structure of a Linked List</h3><p>A <strong>linked list</strong> is made of nodes, where each node has:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wlrrSaXMNVbZMBTMbajrmQ.png" /></figure><ul><li>val → stores the data</li><li>next → points to the next node</li></ul><h3>Understanding Linked List Operations (Create, Insert, Delete)</h3><h3>1. Creating a Node</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IREHcdTd05Obgg_VFRL7Pw.png" /></figure><pre>newNode = ListNode(B)</pre><p>This line creates a new node:</p><ul><li>B is the value stored inside the node</li><li>next is automatically None (no connection yet)</li></ul><p>So, every time you want to add something to the list, you first create a node like this.</p><h3>2. Inserting an Element in Linked List</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l3Cujj7MmzEZ0Ar_oBlyCA.png" /></figure><h3>Code:</h3><pre>def solve(self, A, B, C):<br>    newNode = ListNode(B)<br>if not A:<br>        return newNode<br>        <br>    if C == 0:<br>        newNode.next = A<br>        return newNode<br>curr = A<br>    i = 0<br>while curr.next and i &lt; C-1:<br>        curr = curr.next<br>        i += 1<br>newNode.next = curr.next<br>    curr.next = newNode<br>return A</pre><h3>Explanation:</h3><ul><li>A → head of linked list</li><li>B → value to insert</li><li>C → position where to insert</li></ul><h3>Case 1: If list is empty</h3><pre>if not A:<br>    return newNode</pre><ul><li>If no list exists, the new node becomes the head.</li></ul><h3>Case 2: Insert at head (position 0)</h3><pre>if C == 0:<br>    newNode.next = A<br>    return newNode</pre><ul><li>Point new node to current head</li><li>Make new node the new head</li></ul><h3>Case 3: Insert in middle or end</h3><pre>while curr.next and i &lt; C-1:<br>    curr = curr.next</pre><ul><li>Move to the (C-1)th node</li><li>Because insertion happens <strong>after it</strong></li></ul><h3>Final insertion</h3><pre>newNode.next = curr.next<br>curr.next = newNode</pre><p>Steps:</p><ol><li>New node points to next node</li><li>Previous node connects to new node</li></ol><h3>3. Deleting an Element from Linked List</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*764aWUF_o6NP0Bk3gZJ0bA.png" /></figure><h3>Code:</h3><pre>def solve(self, A, B):<br>    if B == 0:<br>        return A.next<br><br>    curr = A<br>    i = 0<br><br>    while curr and i &lt; B - 1:<br>        curr = curr.next<br>        i += 1<br><br>    if curr and curr.next:<br>        curr.next = curr.next.next<br><br>    return A</pre><h3>Explanation:</h3><ul><li>A → head</li><li>B → position to delete</li></ul><h3>Case 1: Delete head</h3><pre>if B == 0:<br>    return A.next</pre><ul><li>Simply move head to next node</li><li>First node is removed</li></ul><h3>Case 2: Move to previous node</h3><pre>while curr and i &lt; B - 1:<br>    curr = curr.next</pre><ul><li>Reach node just before the one you want to delete</li></ul><h3>Final deletion</h3><pre>curr.next = curr.next.next</pre><ul><li>Skip the node to delete</li><li>Connect previous node directly to next node</li></ul><h3>Simple Intuition</h3><p>Think of it like a train:</p><ul><li><strong>Insert</strong> → add a new bogie between two bogies</li><li><strong>Delete</strong> → remove a bogie and connect the remaining ones</li></ul><h3>Key Points to Remember</h3><ul><li>Always handle <strong>head separately</strong></li><li>Use a pointer (curr) to traverse</li><li>For insert/delete, you usually stop at <strong>previous node</strong></li><li>Always check for None to avoid errors</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ceaaa5233e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Master DSA Cheat Sheet — PART-03: Recursion]]></title>
            <link>https://shivamthakurdev.medium.com/master-dsa-cheat-sheet-part-03-recursion-05a9083172e6?source=rss-7d0abb59c77e------2</link>
            <guid isPermaLink="false">https://medium.com/p/05a9083172e6</guid>
            <dc:creator><![CDATA[Shivam Thakur]]></dc:creator>
            <pubDate>Mon, 23 Mar 2026 14:53:23 GMT</pubDate>
            <atom:updated>2026-04-15T13:58:50.172Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*2UtNxIkSEU6qHjGR.jpeg" /></figure><p>In our previous parts, we covered the basics of complexity and arrays. Today, we dive into one of the most powerful tools in a programmer’s arsenal: <strong>Recursion</strong>.</p><h3>What is Recursion?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*G3qPd0qLAKMiHF11" /></figure><p>At its core, <strong>Recursion</strong> is a programming technique where a <strong>function calls itself</strong> to solve a problem.</p><p>The philosophy is simple: if you can break a big problem down into smaller versions of the same problem (subproblems), you can solve those smaller pieces until you reach a point where the answer is obvious.</p><h3>The Anatomy of a Recursive Function</h3><p>To prevent your code from running forever (and hitting that dreaded RecursionError), every recursive function needs two specific components:</p><ol><li><strong>Base Case:</strong> The condition under which the function stops calling itself. This is the “simplest” version of the problem.</li><li><strong>Recursive Step:</strong> The part where the function calls itself with a modified argument, moving closer to the base case.</li></ol><h3>The “Hello World” of Recursion: Factorials</h3><p>The classic way to visualize this is through a Factorial calculation.</p><blockquote><strong><em>Math Logic:</em></strong><em> $n! = n \times (n-1) \times (n-2) \times \dots \times 1$</em></blockquote><blockquote><em>In recursive terms: $n! = n \times (n-1)!$</em></blockquote><h3>Python Implementation</h3><p>Python</p><pre>def factorial(n):<br>    # 1. Base Case: factorial of 0 or 1 is 1<br>    if n &lt;= 1:<br>        return 1<br>    <br>    # 2. Recursive Step: n * factorial of (n-1)<br>    return n * factorial(n - 1)</pre><pre># Example Usage:<br>print(factorial(5)) # Output: 120</pre><h3>How it Works: The Call Stack</h3><p>When you call factorial(3), the computer doesn&#39;t get the answer immediately. It &quot;stacks&quot; the calls:</p><ul><li>factorial(3) calls 3 * factorial(2)</li><li>factorial(2) calls 2 * factorial(1)</li><li>factorial(1) hits the <strong>Base Case</strong> and returns 1.</li></ul><p>Then, the stack “unwinds”:</p><ul><li>factorial(2) becomes 2 * 1 = 2</li><li>factorial(3) becomes 3 * 2 = 6</li></ul><h3>When to Use Recursion?</h3><p>While recursion is elegant, it’s not always the fastest choice due to memory overhead. Use it when:</p><ul><li>The problem has a <strong>tree-like structure</strong> (e.g., File systems, DOM trees).</li><li>You are performing <strong>DFS (Depth First Search)</strong> on graphs.</li><li>The iterative (loop) solution is overly complex and hard to read.</li></ul><h3>Cheat Sheet Summary</h3><ol><li><strong>Feature Description: Core Concept: A </strong>function calling itself.</li><li><strong>Must have a base case </strong>to avoid infinite loops.</li><li><strong>Memory uses </strong>the <strong>Stack</strong>, which can lead to “Stack Overflow” if too deep.</li><li><strong>Common Uses: Sorting</strong>(Merge/Quick Sort), Tree Traversals, Backtracking.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=05a9083172e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>