Showing posts with label DSA. Show all posts

DSA Day 90: Traversing and Printing a Linked List

📅 Date: August 15, 2026

🧠 Mood: The Navigator 🧭

🔥 Topic: DSA Day 90: Traversing and Printing a Linked List

🔦 Lighting Up the Dark Memory

For the past two days, we have been blindly pushing nodes into heap memory. We know the pushFront and pushBack logic is solid, but without visual confirmation, debugging a data structure is practically impossible. As an engineering student, I've learned that if you can't output it to the console, it essentially doesn't exist.

Today, we wrote the traversal logic to Print the Linked List. In a standard array, printing is as simple as running a for loop with an index counter i. But Linked Lists don't have indexes. They are connected by memory addresses. To read them, we have to physically hop from one node to the next.


🛑 The Golden Rule of Traversal

There is exactly one catastrophic mistake you can make when traversing a linked list: Moving the Head Pointer.

1. The Temporary Explorer

If you write head = head->next to iterate through your list, you permanently lose the start of your chain. The memory before it becomes orphaned. Instead, you must create a temporary pointer that acts as a scout. You set this temp pointer to the head, and then move that pointer forward.

2. Knowing When to Stop

How do you know you've reached the end? The very last node (the Tail) points to NULL. So, your while loop must continue running strictly under the condition that temp != NULL.


💻 The C++ Traversal Implementation

void printList() {
    // 1. Create a scout pointer starting at the head
    Node* temp = head;

    // Edge Case: Empty List
    if (head == NULL) {
        cout << "Linked List is empty!" << endl;
        return;
    }

    // 2. Traverse until you hit the end (NULL)
    while (temp != NULL) {
        // Print the data inside the current node
        cout << temp->data << " -> ";
        
        // 3. Move the scout pointer to the next node
        temp = temp->next;
    }
    
    // Visually terminate the chain
    cout << "NULL" << endl;
}

Performance Breakdown: Because we have to visit every single node exactly one time to print its data, this operation inherently runs in $O(N)$ Time Complexity. We only create one extra pointer (temp), so the Space Complexity is $O(1)$.


🎯 Full Visibility

Finally, we can actually see the structure we've been building in memory. With Push Front, Push Back, and Print fully operational, the basics are covered. Tomorrow, we level up the difficulty by inserting a node straight into the middle of the chain.

DSA Day 89: Push Back in Linked List

📅 Date: August 14, 2026

🧠 Mood: The Optimizer ⚡

🔥 Topic: DSA Day 89: Push Back in Linked List

🚄 The Power of the Tail Pointer

On the train back to Thane today, I was thinking about how inefficient standard arrays can be when appending data if they run out of pre-allocated capacity. They have to copy everything to a new, larger block of memory. Linked Lists completely bypass this issue.

Today's syllabus video covered Push Back (inserting a node at the very end of the list). This is where the tail pointer we defined in our manager class a few days ago proves its absolute worth. Without a tail pointer, finding the end of the list would require traversing every single node from the head, resulting in an $O(N)$ time complexity. With the tail pointer, we skip the travel and do it instantly.


🔌 Wiring the End of the Chain

The logic for pushing to the back is incredibly straightforward, but just like pushFront, the order of pointer manipulation is critical.

Step 1: The New Node

Create the new node dynamically in heap memory. By default, its next pointer is initialized to NULL, which is perfect since it will be the new end of the list.

Step 2: Connect the Old Tail

Take the current tail of the list and update its next pointer. Instead of pointing to NULL, it must now point to our newly created node.

Step 3: Shift the Tail

Finally, update the class's tail pointer to point at the new node, officially crowning it the new end of the chain.


💻 The C++ Implementation

void pushBack(int val) {
    // 1. Dynamically allocate new node
    Node* newNode = new Node(val);

    // Edge Case: If the list is completely empty
    if (head == NULL) {
        head = tail = newNode;
        return;
    }

    // 2. Link the current tail to the new node
    tail->next = newNode;

    // 3. Shift the tail pointer to the new node
    tail = newNode;
}

Performance Breakdown: Because we maintained a tail pointer, there is no loop traversing the elements. The entire insertion is resolved with three simple pointer updates, yielding a perfect $O(1)$ Time Complexity and $O(1)$ Space Complexity.


🎯 Data Loaded

We can now inject data instantly into both the front and the back of our Linked List. However, right now, we are just blindly throwing nodes into the void of memory. Tomorrow, we write the logic to traverse the list and actually print our data to the console.

DSA Day 88: Push Front in Linked List

📅 Date: August 13, 2026

🧠 Mood: The Memory Allocator 💾

🔥 Topic: DSA Day 88: Push Front in Linked List

🔗 The First Link in the Chain

Sitting in the TCET labs today, it was time to finally breathe life into the LinkedList manager class we built yesterday. An empty list is just a couple of null pointers. To actually store data, we need to dynamically allocate memory and wire it up.

The first operation on the syllabus is Push Front—inserting a brand new node at the very beginning of the list. In a standard Array, pushing to the front is an absolute nightmare. You have to shift every single existing element one step to the right, resulting in a brutal $O(N)$ time complexity. But in a Linked List, because we are just swapping pointers around, it happens instantly.


⚙️ The 3-Step Wiring Process

Pointer manipulation in C++ is unforgiving. If you do these steps out of order, you will overwrite your head pointer and permanently lose access to the rest of your data in memory (a severe memory leak).

Step 1: Create the Node

First, use the new keyword to dynamically allocate memory on the heap for the new node.
Node* newNode = new Node(val);

Step 2: Secure the Chain

Before touching the head pointer, make the newNode->next point to the current head. This ensures the new node is securely holding onto the existing list.

Step 3: Update the Head

Now that the list is secure, safely update the main head pointer to point at your newly created node.


💻 The C++ Implementation

void pushFront(int val) {
    // 1. Dynamically allocate new node
    Node* newNode = new Node(val);

    // Edge Case: If the list is completely empty
    if (head == NULL) {
        head = tail = newNode;
        return;
    }

    // 2. Link the new node to the current head
    newNode->next = head;

    // 3. Shift the head pointer to the new node
    head = newNode;
}

Performance Breakdown: Because there are no loops and we are strictly reassigning pointers, this entire function executes in $O(1)$ Constant Time and requires $O(1)$ Auxiliary Space. This is the exact reason Linked Lists exist.


🎯 One Side Down

We can now inject data instantly into the front of the list. The next logical step is to utilize that tail pointer we set up to push data to the back of the list just as efficiently.

DSA Day 87: Linked List Implementation in C++

📅 Date: August 12, 2026

🧠 Mood: The Architect 🏗️

🔥 Topic: DSA Day 87: Linked List Implementation in C++

🛠️ Building the Manager

Yesterday, we created the blueprint for a single Node. But a single node floating in the vast ocean of RAM is useless. To make it a true data structure, we need a system to track, manage, and link these nodes together.

Today's focus was writing the actual Linked List Implementation. Instead of manually creating nodes in the main() function and loosely pointing them at each other (which is a recipe for memory leaks), we encapsulate the entire logic inside a dedicated LinkedList class.


🧭 Tracking the Ends

To successfully manage a Linked List, the controlling class only needs to remember two specific memory addresses. If you lose these, you lose the entire list.

1. The Head Pointer

This is the entry point. It points to the very first node in the sequence. If head == NULL, it means the list is completely empty. You can never let the head pointer get lost, otherwise the entire chain becomes orphaned in memory.

2. The Tail Pointer (Optimization)

Technically, you only need the Head. But tracking the Tail (the last node) is a massive optimization. If you don't track the tail, adding a new element to the end of the list takes $O(N)$ time because you have to traverse the whole chain. By tracking the tail, adding to the end becomes an instant $O(1)$ operation.


💻 The Class Architecture

#include <iostream>
using namespace std;

// 1. The Node Blueprint (From Yesterday)
class Node {
public:
    int data;
    Node* next;

    Node(int val) {
        data = val;
        next = NULL;
    }
};

// 2. The Linked List Manager Class
class LinkedList {
private:
    Node* head;
    Node* tail;

public:
    // Constructor initializes an empty list
    LinkedList() {
        head = NULL;
        tail = NULL;
    }
    
    // Methods (Push, Pop, Print) will go here...
};

int main() {
    // Instantiating the object
    LinkedList myList(); 
    
    return 0;
}

🎯 Ready for Data

The scaffolding is officially up. We have our node structure and our manager class initialized with null pointers. Next up: writing the functions to dynamically allocate memory and push data into the front of the list.

DSA Day 86: Introduction to Linked Lists

📅 Date: August 11, 2026

🧠 Mood: The Explorer 🧭

🔥 Topic: DSA Day 86: Introduction to Linked Lists

⛓️ Breaking the Contiguous Memory Limit

Up until now in my IT Engineering journey, every data collection I have worked with—whether standard Arrays or dynamic Vectors—relied on contiguous memory. If you want to store 5 integers, the operating system finds a single, unbroken block of memory to fit them all side-by-side.

But what happens when your RAM is fragmented? What if you need to frequently insert elements right in the middle of a massive dataset? Arrays require shifting thousands of elements, giving you a brutal $O(N)$ time complexity. Today, we step into a completely new paradigm to solve this: Linked Lists.


🧠 What is a Linked List?

A Linked List is a linear data structure, but unlike arrays, its elements are not stored in contiguous memory locations. Instead, the elements are scattered all over the RAM, connected to each other using pointers.

The Anatomy of a Node

The fundamental building block of a Linked List is called a Node. You can think of a Node as a container that holds exactly two pieces of information:

  • Data: The actual value you want to store (an integer, string, object, etc.).
  • Next Pointer: The memory address (reference) of the very next Node in the sequence.

The Head and The Tail

To access a Linked List, we only need to know where it starts. This starting node is called the Head. The very last node in the list points to NULL, indicating the end of the chain. This node is known as the Tail.


💻 Defining a Node in C++

Because standard C++ does not have a built-in primitive for a Linked List node, we have to create a custom blueprint using a class or struct. Here is the raw architecture:

#include <iostream>
using namespace std;

// Blueprint for a Linked List Node
class Node {
public:
    int data;       // The actual value
    Node* next;     // Pointer to the next node

    // Constructor to initialize a new Node
    Node(int val) {
        data = val;
        next = NULL;
    }
};

🎯 The Setup is Complete

Right now, this is just a blueprint. A single node floating in memory isn't a list yet. The real challenge comes next: dynamically allocating memory and linking these nodes together to form a chain.

DSA Day 85: The Final Complexity Bosses

📅 Date: July 17, 2026

🧠 Mood: The Finisher 🏁

🔥 Topic: DSA Day 85: The Final Complexity Bosses

🛡️ Closing the Chapter

Due to a slight shift in my schedule, today marks Day 85 of the grind. This is it. The absolute final two questions of the Time & Space Complexity assignment. If you can analyze these without getting tricked by the loop conditions, you are officially ready to move on to advanced Data Structures.

No more theory. Let's break down the brutal truth of how these two specific algorithms scale in a production environment.


1️⃣ The Square Root Trap

int floorSqrt(int x) {
    if (x == 0 || x == 1) return x;
    int i = 1, result = 1;
    
    while (result <= x) {
        i++;
        result = i * i;
    }
    return i - 1;
}

At first glance, a while loop makes you think of $O(N)$ or maybe $O(\log N)$ if it's dividing. But look closely at the updating condition: result = i * i.

  • The Execution: The loop continues as long as result <= x, which is mathematically identical to $i^2 \le x$.
  • The Math: If we solve for $i$, the loop terminates the moment $i > \sqrt{x}$. Therefore, the total number of iterations the loop will perform is exactly proportional to the square root of $x$.
  • Time Complexity: $O(\sqrt{x})$ (or $O(\sqrt{N})$). This is a massive optimization over $O(N)$. If $x = 1,000,000$, a linear loop takes a million steps, but this loop finishes in just $1,000$ steps.
  • Space Complexity: $O(1)$ Constant Space. We only declare two basic integer variables (i and result). No extra arrays or data structures are created regardless of how large $x$ gets.

2️⃣ The Dependent Inner Loop

int a = 0;
for (int i = 0; i < n; ++i) {
    for (int j = n; j > i; --j) {
        a = a + i + j;
    }
}

This is a classic variation of the $O(N^2)$ trap. The inner loop's termination condition depends directly on the outer loop's variable (j > i). Let's map the iterations:

  • When i = 0, the inner loop runs from $n$ down to $1$ ($n$ times).
  • When i = 1, the inner loop runs from $n$ down to $2$ ($n - 1$ times).
  • When i = n - 1, the inner loop runs from $n$ down to $n$ ($1$ time).

The Final Calculation

The total number of operations is the sum: $n + (n-1) + (n-2) + \dots + 1$.

Mathematically, this evaluates to $\frac{n(n+1)}{2}$, which expands to $\frac{n^2}{2} + \frac{n}{2}$. As always, we drop the constants and the lower-order terms.

Time Complexity: $O(N^2)$ Quadratic Time.
Space Complexity: $O(1)$ Constant Space (only integer trackers are used).


🎯 Module Complete

That is it. The Time and Space Complexity module is 100% finished. No more theory, no more abstract math. It is time to get back to writing raw, optimized algorithms.

DSA Day 84: Cracking the Complexity Assignment

📅 Date: July 16, 2026

🧠 Mood: The Problem Solver 🛠️

🔥 Topic: DSA Day 84: Cracking the Complexity Assignment

🧩 Passing the Acid Test

Reading theory about Big O Notation is one thing, but applying it to raw code snippets is the ultimate acid test. Interviewers love to throw nested loops with weird increment conditions on the whiteboard to see if you actually understand how the math scales.

Today, I sat down and tackled the final three assignment questions for the Time & Space Complexity module. No compilers. No execution timers. Just raw static analysis. Here is the exact breakdown of the logic required to solve them.


1️⃣ Analyzing Nested Independent Loops

int i, j, k = 0;
for (i = n / 2; i <= n; i++) {
    for (j = 2; j <= n; j = j * 2) {
        k = k + n / 2;
    }
}

To find the Time Complexity here, we must evaluate the loops from the outside in.

  • The Outer Loop: It starts at $N/2$ and increments by $1$ until it reaches $N$. The total number of iterations is $N - N/2 = N/2$. In Big O Notation, we drop the constants (the division by 2), leaving us with $O(N)$.
  • The Inner Loop: It starts at $2$ and multiplies by $2$ every step (j = j * 2). Because it grows exponentially, it reaches $N$ in a logarithmic number of steps. This gives us $O(\log N)$.
  • The Conclusion: Since the inner loop executes completely for every single iteration of the outer loop, we multiply them together: $O(N) \times O(\log N)$.

Correct Answer: B. $O(N \log N)$


2️⃣ The Logarithmic Base Trap

for(int i=0; i

This is a brilliantly tricky question. At first glance, you see i++ in the loop header and assume it is linear $O(N)$. But look at the loop body: i *= k. Let's trace the execution:

  • Iteration 1: i = 0. The body makes it 0 * k = 0. Then the loop header increments it: i++ makes it $1$.
  • Iteration 2: i = 1. The body makes it 1 * k = k. The loop header increments it: i++ makes it $k+1$.
  • Iteration 3: i = k+1. The body makes it (k+1) * k = k^2 + k. The header increments it.

The variable i is growing by powers of $k$ ($k^1, k^2, k^3...$). The number of iterations required for $k^x$ to reach $N$ is exactly $\log_k N$. Because the growth factor is $k$, the base of the logarithm is $k$.

Correct Answer: C. $O(\log_k N)$


3️⃣ The "Always" Fallacy

The Statement

"Algorithm A and B have a worst-case running time of O(n) and O(logn), respectively. Therefore, algorithm B always runs faster than algorithm A."

The keyword that destroys this statement is "always".

Big O Notation represents asymptotic behavior—how the algorithm performs as the input size $N$ approaches infinity. It intentionally ignores constant factors.

Imagine Algorithm B has a massive constant overhead: $10,000 \log N$. And Algorithm A is highly optimized: $2N$. If the input size is incredibly small (e.g., $N = 2$), Algorithm A will easily execute faster than Algorithm B. $O(\log N)$ only dominates $O(N)$ when the input scales up to large numbers.

Correct Answer: B. False


🎯 The Final Word

Knocking out these assignments proves that the logic is finally sticking. The days of blindly guessing an algorithm's efficiency are over. Time to close the book on Time and Space Complexity and prepare for the next data structure.

DSA Day 83: Technical Interview Strategy & Coding Approach

📅 Date: July 14, 2026

🧠 Mood: The Strategist ♟️

🔥 Topic: DSA Day 83: Technical Interview Strategy & Coding Approach

🎯 How to Survive the Whiteboard

If you jump straight into writing C++ code the moment an interviewer gives you a problem, you will fail. The most valuable video in today's curriculum wasn't about math; it was a pure strategic guide titled "How to approach Coding Qs?".

Technical interviews evaluate your thought process, not just your syntax.


🗺️ The 4-Step Interview Framework

  1. Clarify: Never assume. Ask about edge cases. "Can the array be empty?" "Are there negative numbers?"
  2. The Brute Force: Verbally explain the naive $O(N^2)$ approach first. It proves you can at least solve the problem, and gives you a baseline to improve upon.
  3. Optimize: Use Data Structures (like Hash Maps) or Algorithms (like Binary Search) to reduce the time complexity. State the new Big O notation out loud.
  4. Code & Dry Run: Only write code once the logic is agreed upon. Afterward, manually trace a small test case through your variables to catch off-by-one errors.

DSA Day 82: Merge Sort Analysis & Master's Theorem

📅 Date: July 13, 2026

🧠 Mood: The Logician 🧩

🔥 Topic: DSA Day 82: Merge Sort Analysis & Master's Theorem

📚 Decoding the Divide and Conquer

A few weeks ago, I wrote about Merge Sort. I knew it was fast, but today I actually had to prove *why* it's fast mathematically. The syllabus handed me a PDF on Master's Theorem, which is a direct formula used to calculate the time complexity of Divide and Conquer algorithms without drawing massive trees.


✂️ The $O(N \log N)$ Proof

Merge Sort does two things: it divides the array in half, and then it merges them.

Step-by-Step Breakdown

  • The Division: Halving an array down to single elements takes $O(\log N)$ steps.
  • The Merge: At each of those levels, the algorithm must touch every single element to merge them back together in sorted order. Touching every element takes $O(N)$ time.
  • The Result: You multiply the work done per level by the number of levels: $O(N \log N)$.

This makes Merge Sort exponentially faster than Bubble Sort's $O(N^2)$ and is the exact reason it is highly favored in large-scale system processing. We also analyzed the optimized Power Function today, confirming its brilliant $O(\log N)$ performance.

DSA Day 81: Fibonacci & Exponential Time Complexity

📅 Date: July 12, 2026

🧠 Mood: The Mathematician 📐

🔥 Topic: DSA Day 81: Fibonacci & Exponential Time Complexity

📉 The Nightmare of $O(2^N)$

Yesterday's linear recursion was forgiving. Today, I analyzed the Recursive Nth Fibonacci function, and it perfectly demonstrated why bad recursive code can completely freeze a modern processor.

The standard formula for Fibonacci is $F(N) = F(N-1) + F(N-2)$. Unlike a factorial which makes one call per level, this function branches into *two* calls at every single level.


🌳 The Branching Tree

If you draw out the execution tree for $F(5)$, it doesn't look like a straight line. It looks like a massive, expanding pyramid.

  • Level 0: 1 call
  • Level 1: 2 calls
  • Level 2: 4 calls
  • Level 3: 8 calls

The number of operations doubles at every step. This results in an Exponential Time Complexity of $O(2^N)$. This is horrific for performance. Trying to calculate $F(50)$ recursively will take your computer hours, if not days, to process. This is the exact reason Dynamic Programming exists—a topic I'll conquer later on the roadmap.

DSA Day 80: Breaking the Hiatus & Recursion Time Complexity

📅 Date: July 11, 2026

🧠 Mood: The Comeback 🔄

🔥 Topic: DSA Day 80: Breaking the Hiatus & Recursion Time Complexity

🔋 Rebooting the System

There is no point in sugar-coating it: I haven't written a line of code in the last 10 days. Between the daily commute, college burnout, and sheer mental exhaustion from the first half of this module, I needed a hard reset. But consistency isn't about never falling off; it's about getting back on. Today, we return to the grind with Time & Space Complexity (Part 2).

Analyzing standard for loops is easy. But how do you calculate the time complexity of a function that calls itself? Recursion Time Complexity is notorious for confusing junior developers because you can't just count the loops. You have to map the call stack.


🔄 The Linear Recursion Trap

We started with two classic algorithmic problems: Recursive Sum of N Numbers and Recursive Factorial of N. Both of these follow the exact same execution pattern.

Calculating the Call Stack

To find the time complexity of a recursive function, you use a simple formula:

Total Time = (Number of Recursive Calls) $\times$ (Time taken per call)

In a factorial function (e.g., $5! = 5 \times 4!$), calculating the multiplication takes $O(1)$ constant time. But to get from $N$ down to the base case of $1$, the function must push exactly $N$ frames onto the call stack. Therefore, the time complexity is strictly $O(N)$. Furthermore, because it holds $N$ frames in memory simultaneously, its Space Complexity is also $O(N)$.

DSA Day 79: The Logarithmic Leap $O(\log N)$

📅 Date: July 1, 2026

🧠 Mood: The Hacker 💻

🔥 Topic: DSA Day 79: The Logarithmic Leap $O(\log N)$

✂️ Halving the Search Space

We wrap up Part 1 of Time and Space Complexity with the holy grail of algorithmic optimization: Logarithmic Time Complexity.

To truly understand this, I had to review some high school mathematics. In Computer Science, when we say $\log$, we are almost always talking about Base 2 ($\log_2$). If $2^3 = 8$, then $\log_2(8) = 3$. It essentially answers the question: "How many times can I divide this number by 2 before I reach 1?"


⚡ Binary Search vs. Linear Search

This math directly translates into Binary Search.

The Power of $O(\log N)$

If you are searching for a specific number in a sorted array of 1,000,000 elements using a standard loop ($O(N)$), it could take up to 1,000,000 checks.

If you use Binary Search ($O(\log N)$), you cut the array in half every single step.
Step 1: 500,000 left.
Step 2: 250,000 left.
By step 20, you have narrowed it down to 1 element.

Going from 1 million operations to just 20 operations is why massive tech companies obsess over logarithmic algorithms. Understanding the difference between Linear and Logarithmic scaling is the absolute baseline requirement for clearing technical interviews. Module complete.

DSA Day 78: Nested Loops & Quadratic Traps

📅 Date: June 30, 2026

🧠 Mood: The Debugger 🐞

🔥 Topic: DSA Day 78: Nested Loops & Quadratic Traps

🔍 Theory Meets Execution

The theory is over. Today was entirely dedicated to analyzing actual code blocks. The curriculum provided three brutal practice sets specifically designed to trick you into calculating the wrong time complexity.

A standard for loop traversing an array is $O(N)$. That is basic. But the true test of a developer is analyzing nested loops, particularly when looking at classic algorithms like Bubble Sort.


⚠️ The $O(N^2)$ Trap

In Bubble Sort, you have an outer loop running $N$ times, and an inner loop running $N - i$ times.

Mathematical Breakdown

The total number of operations isn't exactly $N \times N$. It is mathematically the sum of the first $N$ natural numbers: $\frac{N(N-1)}{2}$.

If we expand this, we get $\frac{N^2}{2} - \frac{N}{2}$. Applying the rules of Big O Notation from Day 1, we drop the constants (the division by 2) and drop the lower-order term ($N$). The final, absolute worst-case time complexity is $O(N^2)$.

Quadratic time complexity is a performance killer. If an input size grows from 1,000 to 10,000, an $O(N)$ algorithm takes 10 times longer. An $O(N^2)$ algorithm takes 100 times longer. Recognizing this trap in your code is the first step toward optimizing it.

DSA Day 77: Space Complexity & Alternate Notations

📅 Date: June 29, 2026

🧠 Mood: The Optimizer ⚙️

🔥 Topic: DSA Day 77: Space Complexity & Alternate Notations

💾 Real Estate in RAM

During my commute from Thane to Kandivali for college lectures, I usually review the notes from the previous day. Big O Notation for time execution made sense. But today, the curriculum shifted from processor ticks to RAM allocation. We tackled Space Complexity.

Time is money, but memory is real estate. Space complexity measures the total amount of extra memory an algorithm requires to run as a function of the input size.


📐 Beyond the Worst Case

While Big O is the industry standard for worst-case scenarios, the curriculum introduced two other asymptotic notations that interviewers sometimes use to test your deep understanding:

  • Omega Notation (Ω): This represents the Best Case scenario. If you are searching an array for a number and find it on the very first try, that is $\Omega(1)$. It's good to know, but rarely useful for guaranteeing system stability.
  • Theta Notation (Θ): This represents the Average Case or tight bound. It means the algorithm scales at this exact rate from both the upper and lower bounds.

The Auxiliary Space Trap

When calculating Space Complexity, you do not count the memory taken by the input array itself. You only count the extra memory (Auxiliary Space) your code creates. If you pass an array of size $N$ into a function, and your function creates a single integer variable to keep track of a sum, your space complexity is $O(1)$ constant time. If your function duplicates the array, it becomes $O(N)$ linear space.

DSA Day 76: Time Complexity & Big O Notation

📅 Date: June 28, 2026

🧠 Mood: The Analyst 📈

🔥 Topic: DSA Day 76: Time Complexity & Big O Notation

⏱️ The Ultimate Metric of Scaling

If you go to the gym and lift weights without tracking your progressive overload, you are just wasting energy. The exact same rule applies to software engineering. Writing a loop that processes 10 items is easy. But what happens when that same loop has to process 10 million items? Today, the DSA curriculum hit the most critical topic for interviews: Time Complexity and Big O Notation.

Time complexity is not about measuring the execution time in seconds. A modern processor will execute bad code fast if the input is small. Time complexity is a mathematical model that describes how the runtime of your code scales as the input size ($N$) grows towards infinity.


📏 Understanding Big O Notation

In the industry, we only care about the worst-case scenario. That is what Big O Notation represents. It is the absolute maximum limit of time your code will take to execute.

1. Constant Time: O(1)

This is the holy grail. Whether your array has 10 elements or 10 billion elements, accessing arr[5] takes the exact same amount of time. The operation does not scale with the input.

2. The Golden Rule: Drop the Constants

If you have a function that loops through an array twice, the math formula might look like $O(2N)$. In Big O Notation, we drop the constants. As $N$ approaches infinity, the multiplier '2' becomes irrelevant. The final time complexity is strictly evaluated as $O(N)$. We also drop lower-order terms. An equation of $O(N^2 + N + 5)$ is simplified immediately to just $O(N^2)$.

DSA Day 72: Boyer-Moore Voting Algorithm (LeetCode 169)

📅 Date: June 23, 2026

🧠 Mood: The Evaluator 🗳️

🔥 Topic: DSA Day 72: Boyer-Moore Voting Algorithm (LeetCode 169)

📉 The Brutal Efficiency of Space Optimization

After finishing the Divide and Conquer module, I wanted to jump straight into standard tracking problems. I opened LeetCode and hit **Problem 169: Majority Element**. The requirement looks trivial: find the element that appears more than $\lfloor N/2 \rfloor$ times in an array.

If you ask a beginner, they will instantly suggest using a Hash Map. Count the frequency of every element, iterate through the map, and return the one with the highest frequency. It runs in $O(N)$ time, which passes the time constraints. But using a Hash Map takes $O(N)$ auxiliary space. When an interviewer says, **"Optimize it to $O(1)$ space without sorting,"** most people freeze. That is where the Boyer-Moore Voting Algorithm comes into play. It is a masterclass in pure, mathematical logic.


⚔️ The Concept of Battle and Cancellation

The intuition behind this algorithm is a ruthless battle of elimination. Imagine a room full of people belonging to different political factions. If two people from different factions pair up and knock each other out of the room, who will be left at the end?

Because the majority element appears **more than half the time**, its total headcount is greater than all the other factions combined. Even if every single minority element teams up to eliminate a majority element, the majority faction will still have survivors left standing at the end.

[Image of Boyer-Moore voting algorithm state machine flow chart tracking candidate and count status]

1. The Candidate Setup

We maintain two variables: a candidate and a count. We start iterating through the array. If the count drops to 0, it means the previous candidate was completely neutralized. We immediately select the current element as our new candidate.

2. The Vote Counter

For every element we cross, if it matches our current candidate, we increment the count (faction grows stronger). If it doesn't match, we decrement the count (one-on-one elimination). Because the true majority element occupies more than half the array space, it is guaranteed to be the final candidate standing.


💻 The C++ Implementation

#include <iostream>
#include <vector>
using namespace std;

int majorityElement(vector<int>& nums) {
    int candidate = 0;
    int count = 0;

    for (int num : nums) {
        // Step 1: If count is 0, pick a new candidate
        if (count == 0) {
            candidate = num;
        }

        // Step 2: Increment or decrement count
        if (num == candidate) {
            count++;
        } else {
            count--;
        }
    }

    // Note: The problem guarantees that a majority element always exists.
    // Otherwise, a second pass would be needed to verify the candidate.
    return candidate;
}

int main() {
    vector<int> nums = {2, 2, 1, 1, 1, 2, 2};
    int ans = majorityElement(nums);
    
    cout << "The Majority Element is: " << ans << endl;
    // Output: 2
    return 0;
}

By avoiding maps and sorting routines, this code operates at absolute peak efficiency: **Time Complexity is $O(N)$** and **Space Complexity is $O(1)$**. This is the exact kind of answer that satisfies strict algorithmic interviews.


🎯 Takeaway

Boyer-Moore is a beautiful reminder that smart mathematical shortcuts can completely eliminate memory overhead. Tomorrow, we move further down our tracking track to handle sliding windows and two-pointer tracking optimization frameworks.

DSA Day 71: Rotated Sorted Array (Revisited via D&C)

📅 Date: June 22, 2026

🧠 Mood: The Veteran 🎖️

🔥 Topic: DSA Day 71: Rotated Sorted Array (Revisited via D&C)

🔄 A Blast from the Past

Looking at today's curriculum, I actually smiled. Search in Rotated Sorted Array.

If you scroll back through my blog, I tackled this exact problem over two months ago on April 5th (Day 61). Back then, I solved it using an iterative while loop and standard Binary Search mechanics. It worked perfectly, and it's still a valid solution. But solving a problem iteratively versus solving it recursively requires a completely different mental model.

Today, on the train from Thane, I rewrote the solution from scratch using pure Divide and Conquer recursion. No loops. Just shrinking the search space via the Call Stack.


🔍 The Recursive "One Sorted Half" Rule

The fundamental logic hasn't changed since April: No matter where you rotate a sorted array, at least one half of it relative to the 'mid' point will always be perfectly sorted.

Instead of manually updating start = mid + 1 in a loop, we simply pass the new boundaries directly into the next recursive function call.


💻 The Recursive C++ Implementation

#include <iostream>
#include <vector>
using namespace std;

int searchRotated(vector<int>& arr, int tar, int si, int ei) {
    // BASE CASE: Not found
    if (si > ei) return -1;

    int mid = si + (ei - si) / 2;

    // BASE CASE: Found the target
    if (arr[mid] == tar) return mid;

    // CASE 1: Left line is completely sorted
    if (arr[si] <= arr[mid]) {
        if (arr[si] <= tar && tar <= arr[mid]) {
            // Target is securely inside the left sorted line
            return searchRotated(arr, tar, si, mid - 1);
        } else {
            // Target is somewhere on the right side
            return searchRotated(arr, tar, mid + 1, ei);
        }
    } 
    // CASE 2: Right line is completely sorted
    else {
        if (arr[mid] <= tar && tar <= arr[ei]) {
            // Target is securely inside the right sorted line
            return searchRotated(arr, tar, mid + 1, ei);
        } else {
            // Target is somewhere on the left side
            return searchRotated(arr, tar, si, mid - 1);
        }
    }
}

int main() {
    vector<int> arr = {4, 5, 6, 7, 0, 1, 2};
    int target = 0;
    
    int result = searchRotated(arr, target, 0, arr.size() - 1);
    cout << "Target found at index: " << result << endl;
    return 0;
}

🎯 Divide & Conquer: Cleared

Seeing how the same logic transforms from iterative to recursive proves that algorithms are just tools. It’s the logic that matters. The Divide & Conquer module is officially done. Tomorrow, we push deeper into the syllabus.

DSA Day 70: Quick Sort & The Worst-Case Trap

📅 Date: June 21, 2026

🧠 Mood: The Optimizer ⚡

🔥 Topic: DSA Day 70: Quick Sort & The Worst-Case Trap

⚡ Fixing the Memory Leak

Yesterday's Merge Sort algorithm annoyed me. Creating a temporary array at every single level of the recursion tree feels incredibly inefficient. In embedded systems or massive databases, you can't just duplicate data on a whim.

Today's algorithm, Quick Sort, fixes this. It is an "in-place" sorting algorithm, meaning it takes $O(1)$ extra space. It uses the same Divide & Conquer philosophy, but instead of merging at the end, it does the heavy lifting before the recursion by selecting a "Pivot" element.


🎯 The Pivot and Partition

The logic is entirely based on picking a standard (the pivot) and bullying the rest of the array into submission based on that standard.

1. The Partition Step

We usually pick the last element as the Pivot. We then iterate through the array. If an element is smaller than the pivot, we throw it to the left. If it's larger, we throw it to the right. Finally, we lock the Pivot into its exact, correct, permanent position in the array.

2. The $O(N^2)$ Trap

Here is the brutal truth interviewers will grill you on: Quick Sort is faster than Merge Sort on average, BUT its worst-case scenario is horrific. If you run Quick Sort on an array that is already sorted (ascending or descending), the pivot logic fails completely. It doesn't divide the array in half; it divides it by 1. The time complexity degrades to a catastrophic $O(N^2)$.


💻 The C++ Implementation

#include <iostream>
#include <vector>
using namespace std;

int partition(vector<int>& arr, int si, int ei) {
    int pivot = arr[ei]; // Choosing last element as pivot
    int i = si - 1;      // To make space for elements smaller than pivot

    for (int j = si; j < ei; j++) {
        if (arr[j] <= pivot) {
            i++;
            swap(arr[i], arr[j]); // Throw smaller element to the left
        }
    }
    // Lock the pivot in its correct position
    i++;
    swap(arr[i], arr[ei]);
    return i; // Return pivot index
}

void quickSort(vector<int>& arr, int si, int ei) {
    if (si >= ei) return;

    // Partition array and get pivot index
    int pIdx = partition(arr, si, ei);

    // Recursively sort left and right of the pivot
    quickSort(arr, si, pIdx - 1);
    quickSort(arr, pIdx + 1, ei);
}

int main() {
    vector<int> arr = {6, 3, 9, 8, 2, 5};
    quickSort(arr, 0, arr.size() - 1);
    
    cout << "Sorted Array: ";
    for(int val : arr) cout << val << " "; 
    return 0;
}

🎯 The Verdict

Quick Sort is the default sorting algorithm built into most programming languages (like C++'s std::sort) because of its memory efficiency and average-case speed. Tomorrow, we finish this module by revisiting an old enemy: The Rotated Sorted Array.

DSA Day 69: Divide & Conquer (Merge Sort)

📅 Date: June 20, 2026

🧠 Mood: The Surgeon 🔪

🔥 Topic: DSA Day 69: Divide & Conquer (Merge Sort)

✂️ Recursion on Steroids

The assignment questions from yesterday's combinatorics module completely fried my brain. But there is no rest on the weekends if you want to clear technical rounds. Today, the curriculum shifted from abstract recursion into a formal algorithm design paradigm: Divide and Conquer.

If you've ever tried to sort a massive array using Bubble Sort or Insertion Sort, you know it's a disaster. Those algorithms take $O(N^2)$ time. If you pass them a million records, your server will freeze. Divide & Conquer fixes this by slashing the array in half, sorting the tiny pieces, and stitching them back together. The first algorithm on the list is the legendary Merge Sort.


🔪 The Divide and The Merge

Merge Sort is conceptually brutally simple, but coding the "Merge" step is an index-tracking nightmare.

1. The Divide Step (Trivial)

You calculate the mid point and recursively call Merge Sort on the left half and the right half. You keep slicing the array until you are left with individual chunks of size 1. A single element is technically already sorted.

2. The Merge Step (The Headache)

Now you have two sorted sub-arrays. You need to combine them into one sorted array. You use two pointers (one for each sub-array) and a temporary array. You compare the elements, pick the smaller one, shove it into the temp array, and move the pointer. Once done, you copy the temp array back into the original array.


💻 The C++ Implementation

This algorithm guarantees $O(N \log N)$ time complexity. But here is the brutal truth: It is a memory hog. Because we have to create that temporary array during the merge step, it takes $O(N)$ extra space. In a system with tight RAM limits, Merge Sort will crash your application.

#include <iostream>
#include <vector>
using namespace std;

// The Conquer Step
void merge(vector<int>& arr, int si, int mid, int ei) {
    vector<int> temp;
    int i = si;      // iterator for left part
    int j = mid + 1; // iterator for right part

    // Compare and push the smaller element
    while (i <= mid && j <= ei) {
        if (arr[i] < arr[j]) temp.push_back(arr[i++]);
        else temp.push_back(arr[j++]);
    }

    // Push remaining elements of left part
    while (i <= mid) temp.push_back(arr[i++]);
    
    // Push remaining elements of right part
    while (j <= ei) temp.push_back(arr[j++]);

    // Copy temp array back to original array
    for (int k = 0, idx = si; k < temp.size(); k++, idx++) {
        arr[idx] = temp[k];
    }
}

// The Divide Step
void mergeSort(vector<int>& arr, int si, int ei) {
    if (si >= ei) return; // Base case

    int mid = si + (ei - si) / 2;
    mergeSort(arr, si, mid);       // Sort left
    mergeSort(arr, mid + 1, ei);   // Sort right
    merge(arr, si, mid, ei);       // Merge them
}

int main() {
    vector<int> arr = {6, 3, 9, 5, 2, 8};
    mergeSort(arr, 0, arr.size() - 1);
    
    cout << "Sorted Array: ";
    for(int val : arr) cout << val << " "; 
    // Output: 2 3 5 6 8 9
    return 0;
}

🎯 The Next Evolution

Merge Sort is fast, but the memory overhead is unacceptable for certain systems. Tomorrow, we look at its aggressive, highly-optimized cousin: Quick Sort, which completely eliminates the need for extra memory.

DSA Day 68: Combinatorics (Friends & Binary Strings)

📅 Date: June 19, 2026

🧠 Mood: The Combinator 🎲

🔥 Topic: DSA Day 68: Combinatorics (Friends & Binary Strings)

🎲 The Weekend Final Boss

It's Friday. The urge to shut the laptop, hit the gym in Thane, and start the weekend is incredibly high. But there are two topics left in "Recursion Part 2" that deal with generating combinations based on strict constraints.

The first is the Friends Pairing Problem: Given $N$ friends, each friend can either remain single or pair up with one other person. How many total ways can they be arranged? The second is generating all possible Binary Strings of size $N$ without any consecutive 1s. Both require building massive, branching recursive trees. I grabbed a pen, forced myself to dry-run the logic, and knocked them out.


🔗 Constraints and Choices

Let's look at the Binary String problem, because it visually demonstrates how a single constraint prunes a recursive tree. We need to generate strings of length $N$ using only '0' and '1', but '1' cannot sit next to another '1'.

Case 1: Previous char was '0'

If the last character we placed was a '0', we have total freedom. We can branch off and place a '0' for the next step, OR we can place a '1'. Both paths are valid.

Case 2: Previous char was '1'

If the last character was a '1', our choices are severely restricted by the rule. We CANNOT place another '1'. We are forced to place a '0'. The branch that would have placed a '1' is completely pruned from the tree.


💻 The C++ Implementation

#include <iostream>
#include <string>
using namespace std;

// n = remaining length, lastPlace = the last character we added
void printBinStrings(int n, int lastPlace, string str) {
    // 1. BASE CASE
    if (n == 0) {
        cout << str << endl;
        return;
    }

    // 2. RECURSIVE CHOICES
    // We can ALWAYS append a '0'
    printBinStrings(n - 1, 0, str + "0");
    
    // We can ONLY append a '1' if the last place was NOT '1'
    if (lastPlace == 0) {
        printBinStrings(n - 1, 1, str + "1");
    }
}

int main() {
    int stringLength = 3;
    cout << "Valid binary strings of length " << stringLength << ":" << endl;
    
    // We pass 0 as the initial lastPlace to give the first choice maximum freedom
    printBinStrings(stringLength, 0, "");
    
    return 0;
}

🎯 Module Complete

The "Recursion Part 2" module is officially done. The syllabus lists a PDF of Assignment Questions next, which means my weekend is going to be spent struggling with blank screens and compiler errors. Time to log off and rest the brain.