Popping off on Stacks!

The beginning of my CS journey was a mix of frustration and wonder. I can pinpoint when my interest really took hold: data structures. The simplest of operations performed with various data structures had me in awe the first time I saw them. This was specifically prevalent with stacks, so that’s what we’ll be chatting a bit about today.

What’s a stack?

How does this ‘stack’ up in code?

I found the easiest way to visualize a stack in code was to use Python using a list since the code seems to be pretty straightforward to read. There are many different ways to implement a stack like using a linked list or various libraries like deque or queue! I’d encourage taking a peek at the many different possibilities in your language of choice.

Regardless of the implementation, most stacks all share a few operations in common:

  • push(item) — Adds ‘item’ element to the top of the stack
  • pop() — Deletes the top element of the stack
  • top() or peek() — Returns the element at the top of the stack
  • empty() — Lets us know whether or not our stack is empty

Method credit => https://www.geeksforgeeks.org/stack-in-python/

There can be a few other useful methods, but these cover the basics.

Code example I created in replit

What if I’m a visual learner?

Visualization I made on Google Jamboard

Where would I use this in my ‘stack’ of everyday problems?!

Another code example of mine on replit

How the heck does it know I’m missing parentheses, and how does it figure it out?

One of the most common forms of stack knowledge flexing comes in the form of a ‘parentheses validation’ problem. Let’s say I give you a text file and ask you whether or not the parentheses all have a match, and there are no outliers. How can we get our computer to figure it out? This gave me a ‘stack’ of headaches prior to learning about our data structure of the day.

If you’d like to try to figure it out without any spoilers, here’s this exact problem on leet code!

If you want to see the stack in action, check out this video explanation of the solution! (No affiliation, I just thought the drawing was super helpful)

Let’s pop this stack

Citations:

Leetcode Solution:https://youtu.be/8xqZgLYaIpY?t=618

Utilized Google Jamboard and replit for visuals and code examples

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store