avatarNaina Chaturvedi

Summary

The provided web content outlines a comprehensive guide on the data structure "Stack," covering its definition, operations, important patterns, techniques, and practical questions with solutions, along with additional resources for system design and other tech topics.

Abstract

The webpage titled "Day 14 of 30 days of Data Structures and Algorithms and System Design Simplified — Stack" delves into the concept of Stacks within the realm of data structures. It begins by defining a Stack as a linear data structure that adheres to the Last In First Out (LIFO) principle and operates with a single endpoint for insertion and deletion. The article details the primary operations of a Stack, namely push and pop, and illustrates the internal workings with diagrams and examples. It also emphasizes the significance of Stacks in solving various programming problems, such as reversing the order of elements, checking for balanced parentheses, and implementing Depth First Search (DFS). The author provides an in-depth analysis of complex Stack questions, offering solutions and explanations to reinforce understanding. Additionally, the page links to a plethora of educational resources, including system design base concepts, Python programming projects, and a curated list of coding interview questions, aiming to equip readers with a broad spectrum of knowledge in the tech domain.

Opinions

  • The author believes that understanding Stacks is crucial for tackling coding problems, particularly those encountered in technical interviews.
  • There is an emphasis on the importance of hands-on practice, as evidenced by the inclusion of daily Stack questions and the encouragement to implement solutions.
  • The article suggests that a combination of theoretical knowledge and practical application is key to mastering data structures and algorithms.
  • The author promotes the use of additional resources such as video explanations and newsletters to enhance the learning experience in tech-related fields.
  • There is a clear endorsement of the Ignito YouTube channel as a valuable tool for visual learners and those seeking to supplement their understanding of programming concepts.
  • The inclusion of a wide range of projects and resources indicates the author's opinion that continuous learning and exposure to various aspects of technology are essential for growth in the field.

Day 14 of 30 days of Data Structures and Algorithms and System Design Simplified — Stack

Pic credits : wikicommons

Welcome back peeps. Hope all’s well. In this post we will cover Stack as follows —

What and Why Stack (in 2–3 sentences)?

How does Stack work?

Important Patterns and Techniques in Stack Questions

Most Important Questions with Solutions

Complexity Analysis

Tips and Techniques to solve Stack Questions Fast.

Projects Videos —

All the projects, data structures, SQL, algorithms, system design, Data Science and ML , Data Analytics, Data Engineering, , Implemented Data Science and ML projects, Implemented Data Engineering Projects, Implemented Deep Learning Projects, Implemented Machine Learning Ops Projects, Implemented Time Series Analysis and Forecasting Projects, Implemented Applied Machine Learning Projects, Implemented Tensorflow and Keras Projects, Implemented PyTorch Projects, Implemented Scikit Learn Projects, Implemented Big Data Projects, Implemented Cloud Machine Learning Projects, Implemented Neural Networks Projects, Implemented OpenCV Projects,Complete ML Research Papers Summarized, Implemented Data Analytics projects, Implemented Data Visualization Projects, Implemented Data Mining Projects, Implemented Natural Leaning Processing Projects, MLOps and Deep Learning, Applied Machine Learning with Projects Series, PyTorch with Projects Series, Tensorflow and Keras with Projects Series, Scikit Learn Series with Projects, Time Series Analysis and Forecasting with Projects Series, ML System Design Case Studies Series videos will be published on our youtube channel ( just launched).

Subscribe today!

System Design Case Studies — In Depth

Design Instagram

Design Messenger App

Design Twitter

Design URL Shortener

Design Dropbox

Design Youtube

Design API Rate Limiter

Design Web Crawler

Design Facebook’s Newsfeed

Design Yelp

Design Uber

Design Tinder

Design Tiktok

Design Whatsapp

Most Popular System Design Questions

Mega Compilation : Solved System Design Case studies

Stack

Importance : Very High

Day 2 of data structures and algorithms covers the topics that are most important and with highest ROI.

Note : New stack questions with solutions are added every day. So keep checking this post daily.

Let’s dive in!

What is Stack?

Stack is one of the most important linear data structure in which one can stack the items in a particular fashion ( LIFO — Last in First Out).

It has one end through which you can add and remove the elements in the stack.

Pic credits : Calicoder

Examples of Stack problems —

Valid Parentheses

Min/Max Stack

Tree Traversals

Parsers

Binary Search Tree Questions etc

How does Stack work?

A stack works using two main operations push and pop. When an element is added to the stack, it is placed on the top of the stack. The element that was added last will be the first one to be removed.

There are two functions that are important in stack:

  • Push() : Add the element to the top of the stack
  • Pop() : Remove the element from the top of the stack
Pic credits : codePath

The stack pointer is a register that holds the address to the top item in the stack. It’s called the “top” of the stack.

The main Operations of stack are —

Push : Insert an element at the top of the stack

Pop: Remove the top element of the stack

Top : To return the top element of the stack without removing it

IsEmpty : To check if the stack is empty

Important Patterns and Techniques in Stack Questions

Some important patterns and techniques in stack questions include:

  1. LIFO (Last In First Out) principle: This principle is used to keep track of the order of elements in the stack and to determine which element should be removed next.
  2. Using stack to reverse order of elements: This technique is used to reverse the order of elements in an array or a string, by inserting the elements into a stack one at a time, and then removing them in reverse order.
  3. Using stack to check balanced Parentheses: This technique is used to check whether an expression contains matching parentheses, by pushing opening parentheses onto a stack and popping them off when a matching closing parenthesis is encountered.
  4. Using stack to implement Depth First Search: This technique is used to implement the Depth First Search algorithm by using a stack to keep track of the next vertex to visit.

It important to know two methods that are very important — push and pop.

You can push the element using append method and pop the element using remove method.

Patterns → Questions like below belong to Stack( not limited to):

Design Browser History

Min/Max Stacks

Jump Games

Validate Sequences

Remove Duplicates

Valid Parentheses

Min/Max Stack

Tree Traversals

Parsers

Binary Search Tree Questions etc

Most Important Questions with Solutions

Note : New stack questions with solutions are added every day. So keep checking this post daily.

Golden rule is — Learn by doing/implementing

In this we will see most important stack questions.

Valid Parentheses

Question —

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

An input string is valid if:

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

Example :

Input: s = "()[]{}"
Output : True

Solution :

Main Logic/Idea —

The main logic here is using hash map to map the close parentheses to open parentheses, append to the stack and using pop the similar match parentheses while traversing through the stack.

Main Logic

Implementation —

def isValid(self, s: str) -> bool:
        parenthesisMap  = { ")":"(", "]":"[", "}":"{" }
        ans = []
        
        for i in s:
            if i not in parenthesisMap:
                ans.append(i)
                continue
            if not ans or ans[-1] != parenthesisMap[i]:
                return False
            ans.pop()
        return not ans

Question Link

Similar Pattern —

Longest Valid Parentheses

Remove Invalid Parentheses

Check If Word Is Valid After Substitutions

Check if a Parentheses String Can Be Valid

Move Pieces to Obtain a String

Full Code Video Explanation ( In progress. Subscribe today for updates) :

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

Min Stack

Question —

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

Implement the MinStack class:

  • MinStack() initializes the stack object.
  • void push(int val) pushes the element val onto the stack.
  • void pop() removes the element on the top of the stack.
  • int top() gets the top element of the stack.
  • int getMin() retrieves the minimum element in the stack.

Example 1:

Input:["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

Output
[null,null,null,null,-3,null,0,-2]

Solution :

Main Logic/Idea —

The main logic is — take two stacks ( in one stack store values and for other store the min values) and maintain a pointer ( say top) to get the top element of the stack. Push function is to append the values in both the stacks. Pop function is to remove the top element. To get min, retrieve from the top of the minstack.

Implementation —

class MinStack:
def __init__(self):
        self.stack = []
        self.mStack = []
def push(self, val: int) -> None:
        self.stack.append(val)
        val = min( val, self.mStack[-1] if self.mStack else val)
        self.mStack.append(val)
def pop(self) -> None:
        self.stack.pop()
        self.mStack.pop()
def top(self) -> int:
        return self.stack[-1]
def getMin(self) -> int:
        return self.mStack[-1]

Question Link

Similar Pattern —

Max Stack

Full Code Video Explanation ( In progress. Subscribe today for updates) :

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

Next Greater Element I

Question —

The next greater element of some element x in an array is the first greater element that is to the right of x in the same array.

You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2.

For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2. If there is no next greater element, then the answer for this query is -1.

Return an array ans of length nums1.length such that ans[i] is the next greater element as described above.

Example :

Input: nums1 = [4,1,2], nums2 = [1,3,4,2]
Output: [-1,3,-1]

Solution :

Main Logic/Idea —

The main logic is to add the elements from num2 and see if there’s same element is nums1. If there’s an element in nums1 take its index and store it in the ans array after checking if there’s any corresponding greater element in nums2.

Implementation —

def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
        nIndx = {no:index for index,no in enumerate(nums1)}
        
        ans = [-1] * len(nums1)
        stck = []
        for i in range(len(nums2)):
            curr = nums2[i]
            while stck and curr > stck[-1]:
                val = stck.pop()
                ix = nIndx[val]
                ans[ix] = curr
            if curr in nIndx:
                stck.append(curr)
        return ans

Question Link

Similar Pattern —

Sum of Subarray Ranges

Sum of Total Strength of Wizards

Daily Temperatures

Full Code Video Explanation ( In progress. Subscribe today for updates) :

Note : New stack questions with solutions are added every day. So keep checking this post daily.

Complexity Analysis

Search an element : O(n)

Access element in the stack : O(n)

Insert element in the stack : O(1)

Remove element from the stack : O(1)

Tips and Techniques to solve Stack Questions Fast.

Few things can help you with stack related questions -

Know how recursion works.

Know the important methods/functions of stack before solving the stack questions.

Know how to move “top” pointer of the stack.

Know how to move pointers for two stacks simultaneously.

Know how hash map/hash set works.

That’s it for now. Day 6: Queue coming soon !

Let me know if you have questions in the comment section below. Subscribe/ Follow, Like/Clap as it will encourage me to write more in my free time and Stay Tuned!!

Read More —

11 most important System Design Base Concepts

1. System design basics

2. Horizontal and vertical scaling

3. Load balancing and Message queues

4. High level design and low level design, Consistent Hashing, Monolithic and Microservices architecture

5. Caching, Indexing, Proxies

6. Networking, How Browsers work, Content Network Delivery ( CDN)

7. Database Sharding, CAP Theorem, Database schema Design

8. Concurrency, API, Components + OOP + Abstraction

9. Estimation and Planning, Performance

10. Map Reduce, Patterns and Microservices

11. SQL vs NoSQL and Cloud

12. Most Popular System Design Questions

13. System Design Template — How to solve any System Design Question

14. Quick RoundUp : Solved System Design Case Studies

Some of the other best Series —

60 days of Data Science and ML Series with projects

30 Days of Natural Language Processing ( NLP) Series

30 days of Machine Learning Ops

30 days of Data Structures and Algorithms and System Design Simplified

60 Days of Deep Learning with Projects Series

30 days of Data Engineering with projects Series

Data Science and Machine Learning Research ( papers) Simplified **

100 days : Your Data Science and Machine Learning Degree Series with projects

23 Data Science Techniques You Should Know

Tech Interview Series — Curated List of coding questions

Complete System Design with most popular Questions Series

Complete Data Visualization and Pre-processing Series with projects

Complete Python Series with Projects

Complete Advanced Python Series with Projects

Kaggle Best Notebooks that will teach you the most

Complete Developers Guide to Git

Exceptional Github Repos — Part 1

Exceptional Github Repos — Part 2

All the Data Science and Machine Learning Resources

210 Machine Learning Projects

Tech Newsletter —

If you are interested, you can join my newsletter through which I send tech interview tips, techniques, patterns, hacks — Software Development, ML, Data Science, Startups and Technology projects to more than 30K readers. You can subscribe to Tech Brew :

For Python Projects —

For complete 60 days of Data Science and ML : Day 1 — Day 60 : Quick Recap of 60 days of Data Science and ML

Follow for more updates. Stay tuned and keep coding!

For other projects, tune to —

Build Machine Learning Pipelines( With Code)

Recurrent Neural Network with Keras

Clustering Geolocation Data in Python using DBSCAN and K-Means

Facial Expression Recognition using Keras

Hyperparameter Tuning with Keras Tuner

Custom Layers in Keras

Software Development
Programming
Tech
Data Science
Machine Learning
Recommended from ReadMedium
avatarAbhay Kumar
OOPs in Python

An easy guide

10 min read