Category: Data structure

  • Applications of Multithreading: How Multithreading Makes Modern Software Faster and Smarter”

    The Applications of Multithreading span nearly every area of modern software development, transforming how programs perform and respond to user interactions. Multithreading allows applications to run multiple tasks simultaneously, dramatically improving speed and efficiency. Web browsers use it to load multiple tabs and process complex scripts without freezing. Gaming and graphics software rely on multithreading to handle rendering, physics, and sound effects in real time, ensuring smooth and immersive experiences. Servers and network applications leverage multithreading to manage thousands of client connections at once, providing fast and reliable services. Multimedia applications depend on multithreading to play videos, edit media, and process large files without delays. Even operating systems themselves are multithreaded, enabling users to run many programs at the same time without slowing down the system. In mobile apps, multithreading keeps interfaces responsive by performing background tasks like data loading or GPS tracking seamlessly. Across industries like data analytics, artificial intelligence, and financial systems, the Applications of Multithreading are crucial for handling large datasets, performing parallel computations, and delivering high-performance results. By understanding and using multithreading, developers can build software that is faster, smarter, and ready for the demands of today’s multitasking world.

    Introduction

    Ever wondered how your smartphone can play music, download updates, and let you scroll social media — all at the same time? The answer lies in multithreading.

    Multithreading is a programming technique that lets software run multiple tasks simultaneously. It makes applications faster, more responsive, and better at handling complex operations.

    Let’s explore the applications of multithreading and see how it powers the technology we use every day.

    What Is Multithreading?

    Before diving into where multithreading is used, let’s quickly recap what it means.

    • A thread is the smallest unit of execution in a program.
    • Multithreading means a program creates and runs multiple threads side by side.

    Instead of waiting for one task to finish before starting the next, multithreaded programs handle multiple tasks at once. This saves time and improves performance.

    Real-World Applications of Multithreading

    Let’s look at how multithreading is used in real applications:

    1. Web Browsers

    Modern web browsers like Chrome, Firefox, and Edge use multithreading to:

    ✅ Load multiple web pages in different tabs.
    ✅ Download files while you keep browsing.
    ✅ Run animations, videos, and scripts smoothly.

    Without multithreading, a heavy website could freeze your entire browser!

    2. Games and Graphics Applications

    Video games and graphic tools depend on multithreading for:

    🎮 Handling game logic and physics.
    🎮 Managing graphics rendering.
    🎮 Playing background music and sound effects.

    Multithreading ensures smooth gameplay even during complex scenes.

    3. Servers and Networking

    Servers handle thousands of requests every second. Multithreading helps servers:

    🌐 Process multiple client connections at once.
    🌐 Respond quickly without delays.
    🌐 Handle tasks like file uploads, database queries, and more.

    For example, a web server can serve different users simultaneously without making them wait.

    4. Multimedia Applications

    Applications like video editors, music players, and streaming apps use multithreading for:

    🎵 Playing audio and video smoothly.
    🎵 Editing videos in real time.
    🎵 Converting media formats faster.

    This allows users to preview, edit, and export files efficiently.

    5. Operating Systems

    Operating systems (Windows, Linux, macOS) are multithreaded systems. They:

    🖥️ Run multiple apps at the same time.
    🖥️ Handle hardware events like keyboard, mouse, or network inputs.
    🖥️ Keep the system responsive and fast.

    Without multithreading, your PC would freeze every time a heavy task runs.

    6. Data Processing and Analytics

    Big Data and Machine Learning applications use multithreading to:

    📊 Process large datasets in parallel.
    📊 Train machine learning models faster.
    📊 Analyze data while updating dashboards.

    Multithreading reduces processing times and improves productivity for data scientists.

    7. Mobile Applications

    Smartphone apps use multithreading to:

    📱 Load images and content in the background.
    📱 Stay responsive even during updates.
    📱 Run background services like notifications and GPS.

    This makes mobile apps smoother and user-friendly.

    Benefits of Multithreading

    The applications of multithreading exist because of its amazing benefits:

    ✅ Faster execution of tasks.
    ✅ Better responsiveness in user interfaces.
    ✅ Efficient use of multi-core CPUs.
    ✅ Ability to perform background work without freezing the app.

    Conclusion

    From web browsers to powerful servers and games, the applications of multithreading are everywhere. It helps software become faster, smarter, and more responsive.

    Learning multithreading is a great step for any programmer who wants to build high-performance applications. Start exploring it — and you’ll see just how much it powers the technology we rely on every day!

  • Advantages of Multithreading: Speed Up Your Programs and Boost Performance

    Introduction

    Ever wondered how your computer can download a file, play music, and let you type an email — all at once? The secret lies in multithreading.

    One of the biggest advantages of multithreading is that it allows a program to handle many tasks at the same time. For beginners, this technique is one of the coolest ways to speed up code, improve efficiency, and create applications that feel smoother and more responsive. Let’s dive deeper into the advantages of multithreading and see why it’s such a powerful tool for developers.

    What is Multithreading?

    In simple words, a thread is a small unit of a program. A program with multithreading can run several of these threads simultaneously. Imagine a restaurant kitchen where one chef chops veggies while another grills meat — that’s how multithreading works in software!

    Key Advantages of Multithreading

    Let’s look at why multithreading is a great idea, especially for modern applications:

    ✅ 1. Faster Execution (Speed Up Code)

    One of the biggest benefits of multithreading is speed. Tasks that can run in parallel finish sooner because they share the workload. Instead of waiting for one task to complete before starting another, multithreading gets things done simultaneously.

    Example: While loading a webpage, one thread fetches images while another fetches text content.

    ✅ 2. Better Resource Utilization

    Modern computers have multi-core processors. Multithreading helps your programs use all cores efficiently, rather than leaving some sitting idle. This results in faster and more efficient applications.

    ✅ 3. Improved Responsiveness

    Multithreading makes applications feel smoother. For example, a video game can keep running while loading new levels in the background, preventing the game from freezing.

    Example: In a chat app, one thread listens for new messages, while another handles your typing.

    ✅ 4. Simpler Program Structure for Some Tasks

    Certain problems, like handling multiple users or processing many requests, are naturally easier to solve with multithreading. Threads can handle different users or tasks independently.

    ✅ 5. Reduced Waiting Time

    Programs often need to wait for things — like reading data from a file or a network. With multithreading, your program can keep doing other work instead of pausing entirely.

    ✅ 6. Scalability for Bigger Projects

    Multithreading helps applications scale better as demands grow. Big systems like web servers handle thousands of requests using multithreading to stay fast and reliable.

    When to Use Multithreading?

    • Apps needing high performance
    • Programs with background tasks (e.g. file downloads)
    • User interfaces that must remain responsive
    • Server applications handling many clients

    Caution: Not Always Easy!

    While the advantages of multithreading are huge, it’s important to know it’s not always simple. Threads share resources, and managing them incorrectly can cause bugs like:

    • Race conditions
    • Deadlocks
    • Data inconsistency

    So, while multithreading speeds up code, it must be used carefully!

    Conclusion

    The advantages of multithreading are clear: faster performance, better resource use, and smoother user experiences. Whether you’re building a game, a web app, or a complex system, learning multithreading in programming is a valuable skill.

  • Next Greater Element in Array : Beginner Friendly Explanation with Example | Leetcode Solution (2026)

    If you’re preparing for coding interviews or practicing data structure problems, chances are you’ll encounter the Next Greater Element in array problem. It’s one of the most common and important questions related to arrays and stacks — frequently asked by top tech companies.

    In this beginner-friendly tutorial, we’ll explore the concept of Next Greater Element in an array with simple logic, step-by-step explanation, dry run examples, and multiple code implementations (brute-force and stack-based).

    Whether you’re a student, a beginner programmer, or an aspiring software developer, this guide will help you build a strong foundation in solving array problems using stacks..

    What is the Next Greater Element?

    The Next Greater Element in array is a classic coding interview problem that tests your understanding of arrays and stack-based logic.

    Here’s the problem statement:

    Given an array of integers, your task is to find the next greater element for each element in the array.
    The next greater element for an element x is the first element to the right of x that is greater than x.

    If no greater element exists on the right side, the answer is -1 for that position.

    🔍 Example:

    Input:  [4, 5, 2, 25]
    Output: [5, 25, 25, -1]
    

    Explanation:

    • Next greater of 4 is 5
    • Next greater of 5 is 25
    • Next greater of 2 is 25
    • 25 has no greater element, so answer is -1

    This concept is commonly used in problems involving stock span, daily temperatures, and monotonic stacks. Understanding the Next Greater Element in array is a stepping stone to solving more advanced array-based questions.

    Brute Force Approach to Find Next Greater Element in Array (Easy to Understand)

    ✅ Logic:

    In this basic approach to solving the Next Greater Element in array, we use two nested loops. For each element in the array, we scan all elements to its right and find the first greater element.

    If we don’t find any, we simply put -1.

    🔁 Time Complexity:

    • O(n²) – Because for each element, we loop through the remaining elements on its right.

    This method is easy to understand but not efficient for large input sizes.

    🧑‍💻 C++ Code: Brute Force for Next Greater Element

    #include <iostream>
    #include <vector>
    using namespace std;
    
    void printNGE(vector<int>& arr) {
        int n = arr.size();
        for(int i = 0; i < n; i++) {
            int next = -1;
            for(int j = i + 1; j < n; j++) {
                if(arr[j] > arr[i]) {
                    next = arr[j];
                    break;
                }
            }
            cout << arr[i] << " --> " << next << endl;
        }
    }
    
    int main() {
        vector<int> arr = {4, 5, 2, 25};
        printNGE(arr);
        return 0;
    }
    

    Efficient Stack-Based Approach to Next Greater Element in Array (O(n) Time)

    When solving the Next Greater Element in array, an efficient solution is to use a stack. This reduces the time complexity from O(n²) to O(n) and is widely asked in coding interviews.

    🧠 Logic:

    We process the array from right to left, using a stack to keep track of potential next greater candidates.

    📚 Step-by-Step Dry Run:

    For input array: [4, 5, 2, 25]

    1. Start from the rightmost element.
    2. For each element:
      • Remove all elements from the stack smaller than or equal to it.
      • If the stack becomes empty, the next greater element is -1.
      • Otherwise, the top of the stack is the next greater.
    3. Push the current element onto the stack for future comparisons.

    🧑‍💻 C++ Code: Stack-Based Next Greater Element

    #include <iostream>
    #include <vector>
    #include <stack>
    using namespace std;
    
    vector<int> nextGreaterElement(vector<int>& arr) {
        int n = arr.size();
        vector<int> result(n, -1);
        stack<int> st;
    
        for(int i = n - 1; i >= 0; i--) {
            // Pop elements smaller than or equal to arr[i]
            while(!st.empty() && st.top() <= arr[i]) {
                st.pop();
            }
    
            // If stack is not empty, top is the next greater element
            if(!st.empty()) {
                result[i] = st.top();
            }
    
            // Push current element
            st.push(arr[i]);
        }
    
        return result;
    }
    
    int main() {
        vector<int> arr = {4, 5, 2, 25};
        vector<int> res = nextGreaterElement(arr);
    
        for(int i = 0; i < arr.size(); i++) {
            cout << arr[i] << " --> " << res[i] << endl;
        }
    
        return 0;
    }
    

    🎯 Output:

    4 --> 5  
    5 --> 25  
    2 --> 25  
    25 --> -1
    

    Why Stack is Useful for Next Greater Element Problems?

    Using a stack makes this problem highly efficient because it stores elements in a last-in, first-out (LIFO) structure, allowing us to track potential next greater elements without scanning the whole array repeatedly.

    This stack-based method is especially powerful for large datasets and is frequently used in:

    • Stock span problems
    • Temperature prediction arrays
    • Monotonic stack patterns

    Time & Space Complexity Summary

    ApproachTime ComplexitySpace Complexity
    Brute ForceO(n²)O(1)
    Stack-based MethodO(n)O(n)

    More Problems Related to Next Greater Element in Array

    Once you’re comfortable with the concept, try solving these related variations:

    • ✅ Next Smaller Element in Array
    • ✅ Next Greater Element in Circular Array
    • ✅ Previous Greater Element in Array
    • ✅ Daily Temperatures Problem (LeetCode)
    • ✅ Stock Span Problem

    Final Words

    The Next Greater Element in array is a foundational algorithm that helps build problem-solving skills involving arrays, stacks, and greedy logic.

    If you understand both the brute force and optimized approaches, you’ll be able to solve a wide range of real-world problems that follow a similar pattern.

    Keep practicing and exploring new variations — and remember: every great coder once started with basics like this!

    You can also Visit other tutorials of Embedded Prep 

    Special thanks to @mr-raj for contributing to this article on EmbeddedPrep

  • Stack Data Structure | Complete Beginner’s Guide (2026)

    Welcome to the complete guide on mastering Stack Data Structure
    Whether you’re a beginner just learning data structures, preparing for interviews, or brushing up on recursion, this page will guide you through one of the most fundamental and powerful data structures.

    In this tutorial series, you’ll not only learn how stacks work but also solve real-world problems using recursion, arrays, and linked lists.

    What is a Stack?

    A stack is a linear data structure that follows the Last In First Out (LIFO) principle — the last item added is the first one removed.
    Imagine a stack of plates: you add to the top and remove from the top. 🥞

    In programming, stacks are used in:

    • Expression evaluation and syntax parsing
    • Undo operations in editors
    • Function call management (call stack)
    • Backtracking problems
    • Balanced parentheses checking
    • Depth-first search algorithms

    Tutorials You’ll Find in This Series

    TopicWhat You’ll Learn
    ✅ Stack Implementation using ArrayLearn how to create a basic stack using arrays. Understand operations like push, pop, peek, and check if it’s empty. Great for C++ and C beginners.
    ✅ 2 Stacks in One ArrayImplement two independent stacks in the same array to save memory — a commonly asked space-optimization problem.
    ✅ Delete Middle Element of StackPractice recursion by deleting the middle element of a stack without using any extra data structure.
    ✅ Valid Parentheses ProblemUse stacks to validate expressions like {[()]}. This problem builds logic and appears in almost every coding test.
    ✅ Insert Element at Bottom of StackDive into recursion by inserting an element at the bottom of the stack — an essential sub-step for reversing stacks.
    ✅ Reverse a Stack Using RecursionReverse the stack without any extra space using recursion — builds a strong grasp of recursive thinking.
    ✅ Sort a Stack Using RecursionSort stack elements in ascending order using only recursive calls. A true test of your logic-building skills.
    ✅ Redundant BracketsCheck if an expression has unnecessary or redundant brackets like "((a+b))". Frequently asked by top tech companies.
    ✅ Minimum Bracket ReversalGiven a string with only { and }, find the minimum reversals required to balance the expression. Learn how to count and pair brackets using a stack.

    Why This Series is Perfect for Beginners

    • 📌 Each topic starts from scratch with clear concepts.
    • 💡 Includes dry runs, so you see how the stack changes step by step.
    • 💻 Uses simple C++ code with detailed explanation.
    • 🧪 Comes with practice problems to test your understanding.
    • 📊 Some tutorials use diagrams to help visualize stack operations.
    • 🚀 Recursion + Stack combo is perfect for strengthening logical thinking.

    Build Your Foundations Strong

    Mastering stacks is like building a strong base for competitive programming and interviews. Once you get confident with stacks, you’ll find it easier to solve:

    • Backtracking problems (e.g., Rat in a Maze, Sudoku Solver)
    • Expression Conversion (Infix to Postfix)
    • Tree traversals (postorder, inorder)
    • Recursion-based problems like Tower of Hanoi
    • Compiler syntax checks

    Extra Practice Ideas

    To make your learning journey even more interactive, try solving these after each tutorial:

    • 🔄 Convert each recursive solution into an iterative one using a custom stack.
    • ✍️ Write your own input/output examples and dry-run on paper.
    • 💬 Try explaining the stack changes out loud or to a friend.
    • 🎨 Draw the call stack if recursion is confusing — visuals help!
    • 🧠 Combine multiple operations, like reversing and then sorting a stack.

    Final Words

    Stacks are the building blocks of logical problem solving. With each tutorial, you’re getting closer to mastering data structures and becoming an efficient coder.

    So, what are you waiting for? 🚀
    Dive into each topic listed above — whether you’re sorting, reversing, or validating brackets — and let’s master stacks together!

    Happy Coding! 💻✨
    Let’s stack up your skills — one pop and push at a time!

  • Sorting a Stack Using Recursion in C++ | Master Beginner-Friendly Guide 2026

    Sorting a Stack Using Recursion : In this tutorial, we will learn how to sort a stack of numbers using recursion in C++. A stack is a special data structure where you can only add or remove elements from the top, just like a stack of plates. Sorting a stack might seem tricky because you cannot access elements in the middle directly.

    We will use recursion — a technique where a function calls itself — to break down the problem into smaller parts. First, we remove elements from the stack one by one until it’s empty. Then, we insert each removed element back into the stack in the correct sorted position.

    This method does not use any extra data structures, and it helps you understand both recursion and stack operations deeply. The final result is a stack sorted in ascending order, with the smallest element at the bottom and the largest at the top.

    The article also includes a step-by-step dry run to help beginners understand exactly how the stack changes during sorting.

    What is a Stack?

    A stack is a data structure that works like a pile of plates. You can only add or remove the top plate. This is called LIFO (Last In, First Out).

    • You push to add an item on the top.
    • You pop to remove the item from the top.
    • You can check the top element anytime.

    What Does Sorting a Stack Using Recursion program Do?

    The program sorts the elements in a stack so that the smallest number is at the bottom and the largest number is at the top — all using recursion (functions calling themselves).

    Code Breakdown of Sorting a Stack Using Recursion

    #include <iostream>
    #include <stack>
    using namespace std;
    
    • We include necessary libraries.
    • stack helps us use stack data structure.
    • iostream allows input/output.

    Two Important Functions

    1. sortedInsert — Inserts a number into the correct position in an already sorted stack.
    2. sortStack — Sorts the entire stack using recursion.

    Function: sortedInsert

    void sortedInsert(stack<int> &st, int x) {
        if (st.empty() || st.top() > x) {
            st.push(x);
            return;
        }
        int temp = st.top();
        st.pop();
        sortedInsert(st, x);
        st.push(temp);
    }
    

    What it does:
    It inserts x into the stack st in sorted order.

    How?

    • If stack is empty OR the top element is greater than x, push x directly (because it’s in the right position).
    • Otherwise, remove the top element temporarily, call sortedInsert recursively to insert x in the smaller stack.
    • After that, put back the temporarily removed element on top.

    Function: sortStack of Sorting a Stack Using Recursion

    void sortStack(stack<int> &st) {
        if (st.empty()) return;
    
        int x = st.top();
        st.pop();
    
        sortStack(st);
    
        sortedInsert(st, x);
    }
    

    What it does:
    Sorts the stack by removing elements one by one and inserting them back in the sorted order.

    How?

    • Remove the top element x.
    • Recursively sort the smaller stack.
    • Insert the removed element x back into the sorted stack using sortedInsert.

    main Function — Driver Code of Sorting a Stack Using Recursion

    int main() {
        stack<int> st;
    
        st.push(30);
        st.push(10);
        st.push(50);
        st.push(20);
        st.push(40);
    
        // Print original stack
        cout << "Original Stack (top to bottom): ";
        stack<int> temp = st;
        while (!temp.empty()) {
            cout << temp.top() << " ";
            temp.pop();
        }
        cout << endl;
    
        // Sort the stack
        sortStack(st);
    
        // Print sorted stack
        cout << "Sorted Stack (top to bottom): ";
        while (!st.empty()) {
            cout << st.top() << " ";
            st.pop();
        }
        cout << endl;
    
        return 0;
    }
    

    Dry Run (Step by Step) | Sorting a Stack Using Recursion

    Let’s dry run with the stack having elements (top to bottom):

    40 (top), 20, 50, 10, 30 (bottom)

    Step 1: sortStack is called with full stack

    • Pop 40
    • Recursively call sortStack with stack: 20, 50, 10, 30

    Step 2: sortStack called again

    • Pop 20
    • Recursively call sortStack with stack: 50, 10, 30

    Step 3: Next recursive call

    • Pop 50
    • Recursively call sortStack with stack: 10, 30

    Step 4:

    • Pop 10
    • Recursively call sortStack with stack: 30

    Step 5:

    • Pop 30
    • Recursively call sortStack with empty stack

    Step 6:

    • Stack is empty, return from recursion

    Step 7: Now insert back the elements in sorted order using sortedInsert

    • Insert 30 into empty stack → stack: 30

    Step 8: Insert 10 into stack 30

    • Compare top 30 > 10 → push 10 on top → stack: 10, 30

    Step 9: Insert 50 into stack 10, 30

    • 30 < 50, pop 30
    • 10 < 50, pop 10
    • Stack empty → push 50
    • Push back popped 10 → stack: 10, 50
    • Push back popped 30 → stack: 30, 10, 50
      Oops! This looks reversed — wait, order is important. Let’s check carefully:

    Actually, the function pushes back in this order:

    • After popping 30, then 10, stack empty
    • push 50 → stack: 50
    • push 10 → stack: 10, 50 (top is 10, then 50)
    • push 30 → stack: 30, 10, 50 (top is 30)

    But this is wrong, we want the smallest on the bottom.

    Actually, when printing, top is on the left.

    Wait, the way we visualize is top at left (in code top is accessed by st.top()), so the stack is:

    • Top: 30
    • then: 10
    • then: 50

    So 30 is on top, 10 below it, 50 at bottom → not sorted.

    So something is wrong in our understanding.

    But the code is correct. The explanation is: the stack stores elements with the top being the last pushed.

    Let’s clarify: In the code, the stack top is the last inserted, and when we print from top to bottom, we pop top elements.

    The sorted stack means top element is largest.

    So the sorted stack (top to bottom): 50 40 30 20 10

    Let’s do Step 9 carefully:

    Stack before insertion: 10 (top), 30

    Insert 50:

    • top is 10, which is not greater than 50 → pop 10
    • next top is 30, which is not greater than 50 → pop 30
    • stack empty → push 50
    • push back 30
    • push back 10

    Stack now:
    Top → 10, then 30, then 50 (bottom)

    Printing top to bottom: 10 30 50

    So stack is not sorted this way.

    So the stack sorted order after inserting elements means smallest at bottom, largest at top:

    This means top is largest.

    After all recursion and insertions, final stack will be:

    50 (top), 40, 30, 20, 10 (bottom)

    which is sorted in ascending order if you read bottom to top.

    Summary of how recursion works here

    • We remove elements one by one until stack is empty.
    • Then we insert elements back in correct sorted order.
    • sortedInsert helps put element x in correct position by temporarily popping elements greater than x.
    • After insertion, the stack remains sorted from bottom (smallest) to top (largest).

    Practice Tip:

    To better understand how the stack changes during the sorting process, try adding cout (print) statements inside the functions. For example, print the current elements in the stack each time you push or pop something. This way, you can see step-by-step how elements move in and out of the stack. It helps you visualize the flow of recursion and makes it easier to follow the logic.

    Watching the stack change in real time is a great way to learn and debug your code!

    Practice Problems

    1. Reverse a Stack Using Recursion
      Write a recursive function to reverse the elements of a stack without using any extra stack or array.
    2. Insert an Element at the Bottom of a Stack
      Write a recursive function that inserts a given element at the bottom of a stack.
    3. Sort a Stack Without Recursion
      Try to sort a stack using only stack operations (push, pop, top) but without recursion. You may use an additional stack or queue.
    4. Find the Maximum Element in a Stack Using Recursion
      Write a recursive function that returns the maximum element present in a stack.
    5. Delete the Middle Element of a Stack Using Recursion
      Given a stack, write a recursive function to delete the middle element of the stack without using any extra space.

    You can also Visit other tutorials of Embedded Prep 

    Special thanks to @mr-raj for contributing to this article on EmbeddedPrep

  • How to Reverse a Stack Using Recursion | Master Beginner Friendly guide 2026

    Reverse a Stack Using Recursion : Stacks are an important data structure in programming. They work like a stack of plates — you can only add or remove plates from the top. This behavior is called LIFO (Last In, First Out).

    Sometimes, you might want to reverse a stack, so the element that was at the top moves to the bottom and vice versa. But how do you reverse a stack without using extra memory or another stack? The answer is recursion!

    In this article, we’ll learn how to reverse a stack using recursion by inserting elements at the bottom.

    What is a Stack?

    A stack allows only two main operations:

    • push(x): Add element x to the top.
    • pop(): Remove the top element.

    You cannot directly access or modify elements below the top.

    Problem Statement

    Given a stack, reverse the order of elements using recursion. For example:

    Original stack (top to bottom):
    5, 4, 3, 2, 1

    After reversing, the stack should be:
    1, 2, 3, 4, 5

    Key Idea: Insert at Bottom

    Since we can only add or remove elements from the top, how do we insert an element at the bottom?

    We use recursion:

    1. If the stack is empty, push the element — that’s the bottom.
    2. Otherwise, pop the top element, call the function recursively to insert the element at the bottom, then push the popped element back on top.

    This way, the new element ends up at the bottom, and the original elements remain on top.

    Step-by-Step Solution

    1. Write a function to insert an element at the bottom:

    void insertAtBottom(stack<int> &st, int x) {
        if (st.empty()) {
            st.push(x);  // If empty, push element (bottom)
            return;
        }
        
        int topElement = st.top();
        st.pop();  // Remove top element
        
        insertAtBottom(st, x);  // Recursive call
        
        st.push(topElement);  // Push the popped element back on top
    }
    

    2. Write a function to reverse the stack:

    void reverseStack(stack<int> &st) {
        if (st.empty()) return;  // Base case
        
        int topElement = st.top();
        st.pop();  // Remove top
        
        reverseStack(st);  // Reverse remaining stack
        
        insertAtBottom(st, topElement);  // Insert removed element at bottom
    }
    

    How Does This Work?

    • reverseStack() keeps popping the top element until the stack is empty.
    • Then it starts inserting each popped element at the bottom of the stack.
    • This reverses the order because the first popped element (which was originally on top) goes to the bottom.

    Full Working Code

    #include <iostream>
    #include <stack>
    using namespace std;
    
    // Insert element x at the bottom of stack st
    void insertAtBottom(stack<int> &st, int x) {
        if (st.empty()) {
            st.push(x);
            return;
        }
        int topElement = st.top();
        st.pop();
        insertAtBottom(st, x);
        st.push(topElement);
    }
    
    // Reverse the stack using recursion
    void reverseStack(stack<int> &st) {
        if (st.empty()) return;
        int topElement = st.top();
        st.pop();
        reverseStack(st);
        insertAtBottom(st, topElement);
    }
    
    // Print stack elements from top to bottom
    void printStack(stack<int> st) {
        while (!st.empty()) {
            cout << st.top() << " ";
            st.pop();
        }
        cout << endl;
    }
    
    int main() {
        stack<int> st;
        st.push(1);
        st.push(2);
        st.push(3);
        st.push(4);
        st.push(5);
    
        cout << "Original Stack: ";
        printStack(st);
    
        reverseStack(st);
    
        cout << "Reversed Stack: ";
        printStack(st);
    
        return 0;
    }
    

    Output:

    Original Stack: 5 4 3 2 1
    Reversed Stack: 1 2 3 4 5
    

    Conclusion

    By cleverly using recursion, we can reverse a stack without using any extra data structure like another stack or array.

    The trick lies in the helper function insertAtBottom() which helps us insert an element at the bottom of the stack, allowing us to place elements in reverse order during recursion unwinding.

    If you want to practice further, try these exercises:

    • Write a function to reverse a stack without recursion (using an extra stack or queue).
    • Modify the code to reverse a stack of strings instead of integers.
  • Insert an Element at the Bottom of a Stack | Master Beginner-Friendly Guide 2026

    Insert an Element at the Bottom of a Stack : Want to master stacks? This beginner-friendly tutorial walks you through how to insert an element at the bottom of a stack using recursion — without any extra data structures!

    You’ll learn:

    ✅ What the problem means
    ✅ How recursion helps you simulate going deep into the stack
    ✅ Step-by-step explanation with dry run
    ✅ Full working code in C++ and Python
    ✅ Practice exercises to test your understanding

    Perfect for beginners preparing for coding interviews or learning recursion concepts with stacks. Start building your foundation in data structures now!

    Problem Statement Insert an Element at the Bottom of a Stack:

    “Given a stack and an element, insert that element at the bottom of the stack.”

    Example:
    Input: Stack = 5 4 3 2 1, Element to Insert = 10
    Output: Stack = 10 5 4 3 2 1

    Concepts You’ll Learn:

    • Stack basics
    • Recursion
    • How function calls can act like a temporary stack

    Approach for :

    Step-by-step solution for Insert an Element at the Bottom of a Stack:

    1. If the stack is empty, push the given element. ✅
    2. Otherwise:
      • Pop the top element temporarily.
      • Recur to insert the element at the bottom.
      • Push the popped elements back after inserting. 🔄

    This way, you dig down to the bottom using recursion, then insert, and rebuild the stack on your way back up.

    C++ Code for Insert an Element at the Bottom of a Stack

    #include <iostream>
    #include <stack>
    using namespace std;
    
    // Function to insert element at the bottom of a stack
    void insertAtBottom(stack<int>& st, int element) {
        // Base case: stack is empty
        if (st.empty()) {
            st.push(element);
            return;
        }
    
        // Step 1: Pop top element
        int top = st.top();
        st.pop();
    
        // Step 2: Recursive call
        insertAtBottom(st, element);
    
        // Step 3: Push top back after inserting
        st.push(top);
    }
    
    int main() {
        stack<int> st;
    
        // Push some elements
        st.push(1);
        st.push(2);
        st.push(3);
        st.push(4);
        st.push(5);
    
        int newElement = 10;
        insertAtBottom(st, newElement);
    
        // Display stack
        cout << "Stack after inserting at bottom:\n";
        while (!st.empty()) {
            cout << st.top() << " ";
            st.pop();
        }
    
        return 0;
    }
    

    Python Code for Insert an Element at the Bottom of a Stack

    def insert_at_bottom(stack, element):
        # Base case: if stack is empty, insert element
        if not stack:
            stack.append(element)
            return
    
        # Step 1: Remove top
        top = stack.pop()
    
        # Step 2: Recursive call
        insert_at_bottom(stack, element)
    
        # Step 3: Put back the top
        stack.append(top)
    
    # Test
    stack = [1, 2, 3, 4, 5]
    element = 10
    insert_at_bottom(stack, element)
    
    print("Stack after inserting at bottom:")
    print(stack[::-1])  # Print from top to bottom
    

    Dry Run Example (Simple):

    Let’s dry run the C++/Python code for inserting an element at the bottom of a stack, step by step.

    Input:

    Initial Stack (top -> bottom): [5, 4, 3, 2, 1]
    Element to insert at bottom: 10
    

    Function Call:

    insertAtBottom(st, 10);
    

    Dry Run – Step by Step (Recursion Unwinding)

    Stack Before:

    [top] → 5 → 4 → 3 → 2 → 1 → [bottom]

    Step 1:

    st.top() is 5
    Pop 5 → Recur on smaller stack

    Call: insertAtBottom([4, 3, 2, 1], 10)

    Step 2:

    Pop 4 → Recur again
    Call: insertAtBottom([3, 2, 1], 10)

    Step 3:

    Pop 3 → Recur again
    Call: insertAtBottom([2, 1], 10)

    Step 4:

    Pop 2 → Recur again
    Call: insertAtBottom([1], 10)

    Step 5:

    Pop 1 → Recur again
    Call: insertAtBottom([], 10)

    Step 6 (Base Case):

    Stack is empty
    → Push 10

    ✅ Stack: [10]

    Backtracking Begins (Pushing elements back):

    Now we return from previous function calls one-by-one:

    Return to Step 5:
    Push 1 → Stack: [1, 10]

    Return to Step 4:
    Push 2 → Stack: [2, 1, 10]

    Return to Step 3:
    Push 3 → Stack: [3, 2, 1, 10]

    Return to Step 2:
    Push 4 → Stack: [4, 3, 2, 1, 10]

    Return to Step 1:
    Push 5 → Stack: [5, 4, 3, 2, 1, 10]

    Final Stack (Top to Bottom):

    [top] → 5 → 4 → 3 → 2 → 1 → 10 → [bottom]

    🎉 Success! We inserted 10 at the bottom of the stack without using extra space

    Why Use Recursion?

    Stacks follow Last-In-First-Out (LIFO) — meaning you can only directly access or modify the top of the stack. There’s no built-in way to reach the bottom element directly.

    But recursion gives us a trick:

    • It lets us temporarily pop all elements one by one.
    • Then, after reaching the empty stack (i.e., bottom), we insert the new element.
    • Finally, recursion rebuilds the original stack by pushing the saved elements back.

    So, recursion simulates going deep into the stack, allowing us to insert at the bottom without breaking the stack’s rules!

    Practice Exercises (to solidify your learning):

    🔁 1. Reverse a stack using the insert_at_bottom() method.
    💡 Tip: Use recursion to pop all elements, then reinsert using your insert-at-bottom function.

    🔁 2. Insert an element at the bottom without using recursion, by using:

    • A second temporary stack, or
    • A queue (FIFO nature)

    🔁 3. Implement stack reversal using both iterative and recursive approaches.
    🔁 4. Write a function to find the size of a stack recursively.
    🔁 5. Use insert_at_bottom() to sort a stack recursively in increasing order.

    You can also Visit other tutorials of Embedded Prep 

  • Valid Parentheses Problem stack |Beginner Friendly Explanation | Leetcode Solution (2026)

    The Valid Parentheses Problem is a classic example of how stack data structures can be used to solve real-world problems involving nested or paired data. The challenge is to determine whether a given string containing only brackets—(, ), {, }, [, ]—is properly balanced and well-formed.

    In a valid expression:

    • Every opening bracket must have a corresponding closing bracket.
    • Brackets must close in the correct order, maintaining the expected nesting.

    To solve this, a stack is used to keep track of opening brackets. When a closing bracket appears, the algorithm checks whether it correctly matches the most recent unclosed opening bracket by looking at the top of the stack. If it doesn’t match or the stack is empty when it shouldn’t be, the expression is invalid. If the stack is empty after processing all characters, the expression is valid.

    Valid Parentheses Problem stack description:

    You are given a string that contains only the characters:

    '(', ')', '{', '}', '[', ']'

    Your task is to check whether the given string is a valid sequence of parentheses.

    A valid string must follow these rules:

    1. Every opening bracket must have a corresponding closing bracket.
    2. The brackets must close in the correct order.
    3. Each type of bracket must match correctly (() not [(]).

    Why Use a Stack?

    A stack is a data structure that works on Last In, First Out (LIFO). That means:

    • The last element you put in is the first one that comes out.
    • This is perfect for tracking open brackets and checking if they are closed properly.

    Step-by-Step Logic for Valid Parentheses Problem stack:

    1. Create an empty stack.
    2. Loop through each character in the string.
    3. If it is an opening bracket ((, {, [), push it onto the stack.
    4. If it is a closing bracket:
      • Check if the stack is empty → if yes, return false.
      • Pop the top element from the stack.
      • Check if the popped element matches the current closing bracket → if not, return false.
    5. After the loop, if the stack is empty, return true (valid). If not, return false (invalid).

    Example of Valid Parentheses Problem stack:

    Input: "{[()]}"
    Output: true
    Explanation: All brackets open and close in the correct order.

    Input: "{[(])}"
    Output: false
    Explanation: [ is not properly closed before ) comes.

    Key Concepts Covered:

    • Stack data structure
    • Matching pairs of brackets
    • Input validation
    • Control flow with conditionals

    Problem Statement Valid Parentheses Problem stack:

    Given a string containing just the characters '(', ')', '{', '}', '[', and ']', determine if the input string is valid.

    👉 A string is valid if:

    1. Open brackets are closed by the same type of brackets.
    2. Open brackets are closed in the correct order.
    3. Every closing bracket has a corresponding open bracket.

    Example:

    Input: "({[]})"
    Output: true
    
    Input: "({[})"
    Output: false
    
    Input: "((("
    Output: false
    

    Approach: Use a Stack

    • Push opening brackets into a stack.
    • For every closing bracket:
      • Check if the stack is empty → ❌ Invalid
      • Check if the top of the stack is the matching opening bracket
    • In the end, the stack should be empty → ✅ Valid

    C++ Code (Beginner-Friendly) | Valid Parentheses Problem stack

    #include <iostream>
    #include <stack>
    #include <string>
    using namespace std;
    
    bool isValid(string s) {
        stack<char> st;
    
        for (char ch : s) {
            // Push opening brackets
            if (ch == '(' || ch == '{' || ch == '[') {
                st.push(ch);
            } else {
                // If stack is empty when closing bracket comes → invalid
                if (st.empty()) return false;
    
                char top = st.top();
                st.pop();
    
                // Check matching pairs
                if ((ch == ')' && top != '(') ||
                    (ch == '}' && top != '{') ||
                    (ch == ']' && top != '[')) {
                    return false;
                }
            }
        }
    
        // Stack should be empty if all brackets matched
        return st.empty();
    }
    
    int main() {
        string str = "({[]})";
        if (isValid(str)) {
            cout << "Valid" << endl;
        } else {
            cout << "Invalid" << endl;
        }
        return 0;
    }
    

    Dry Run Example: "({[]})"

    StepCharStackAction
    1((Push
    2{( {Push
    3[( { [Push
    4]( {Pop + Match [
    5}(Pop + Match {
    6)(empty)Pop + Match (

    → Stack is empty ✅ → Valid

    Python Code (Beginner-Friendly) | Valid Parentheses Problem stack

    def isValid(s):
        stack = []
        mapping = {')': '(', '}': '{', ']': '['}
    
        for char in s:
            if char in mapping.values():
                stack.append(char)
            elif char in mapping:
                if not stack or stack[-1] != mapping[char]:
                    return False
                stack.pop()
            else:
                # In case of unexpected character
                return False
    
        return not stack
    
    # Example usage
    s = "{[()]}"
    print("Valid" if isValid(s) else "Invalid")
    

    Java Code (Beginner-Friendly) | Valid Parentheses Problem stack

    import java.util.Stack;
    
    public class ValidParentheses {
    
        public static boolean isValid(String s) {
            Stack<Character> stack = new Stack<>();
            
            for (char ch : s.toCharArray()) {
                if (ch == '(' || ch == '{' || ch == '[') {
                    stack.push(ch);
                } else {
                    if (stack.isEmpty()) return false;
    
                    char top = stack.pop();
                    if ((ch == ')' && top != '(') ||
                        (ch == '}' && top != '{') ||
                        (ch == ']' && top != '[')) {
                        return false;
                    }
                }
            }
            return stack.isEmpty();
        }
    
        public static void main(String[] args) {
            String s = "{[()]}";
            System.out.println(isValid(s) ? "Valid" : "Invalid");
        }
    }

    Beginner-Level Practice Problems

    1. Basic Valid Parentheses

    • 🔹 Problem: Check if the given string with only ()[]{} is valid.
    • 🔹 Example: "([])" → true, "(]" → false
    • 🔹 Goal: Implement the classic stack-based solution.

    2. Minimum Add to Make Parentheses Valid

    • 🔹 Problem: Given a string of parentheses '(' and ')', return the minimum number of additions needed to make it valid.
    • 🔹 Example: "(()" → 1, "()))(" → 3
    • 🔹 LeetCode #921

    3. Longest Valid Parentheses

    • 🔹 Problem: Given a string of '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
    • 🔹 Example: "(()" → 2, ")()())" → 4
    • 🔹 LeetCode #32

    4. Remove Invalid Parentheses

    • 🔹 Problem: Remove the minimum number of invalid parentheses to make the input string valid. Return all possible results.
    • 🔹 Example: "(a)())()" → ["(a())()", "(a)()()"]
    • 🔹 LeetCode #301

    5. Score of Parentheses

    • 🔹 Problem: Compute the score of a balanced parentheses string.
    • 🔹 Rules: "()" has score 1, "AB" has score A + B, "(A)" has score 2 * A
    • 🔹 Example: "(()(()))" → 6
    • 🔹 LeetCode #856

    Bonus Challenge

    6. Validate Stack Sequences

    • 🔹 Problem: Given two sequences pushed and popped, return true if they could represent the push and pop sequence of a single stack.
    • 🔹 LeetCode #946

    You can also Visit other tutorials of Embedded Prep 

    Special thanks to @mr-raj for contributing to this article on EmbeddedPrep