Topic Overview and Actualization

Hello, eager learners! In today's lesson, we're exploring stacks, a crucial data structure in programming. We aim to understand stacks, implement and manipulate stacks in TypeScript, and analyze their complexities. Stacks are used in various real-world applications, such as undo operations in text editors. Let's dive right in!

Introduction to Stacks

First and foremost, let's understand what a stack is. Imagine a stack of plates that you can only remove from the top. This concept exemplifies stacks, which follow a Last-In, First-Out (LIFO) structure. In a LIFO stack, the last item added is the first removed. For example, adding numbers 1, 2, and 3 in sequence will yield removal in the order: 3, 2, 1. Let's see an implementation in TypeScript, where we'll push (add), pop (remove), and peek (view the top) elements.

We start by introducing the Stack class that stores an array of items that are of a specific type. Utilizing a generic type <T> makes the stack versatile, allowing it to handle any data type, such as numbers, strings, or custom objects.

In TypeScript, arrays can work as stacks. They have the necessary built-in methods. However, let's implement each operation ourselves to understand this data structure better.

Stack Operations

Let's look at how our operations look implemented in code:

  • The push method adds a new element to the top of the stack. It utilizes the built-in push method of arrays to add the element to the end of the items array, representing the top of the stack.

  • The pop method removes the topmost element from the stack. It first checks if the stack is empty and returns "Underflow" if it is, indicating that there are no elements to remove. Otherwise, it removes and returns the top element of the stack. It returns the type union T | string for valid data or errors (in our implementation, the "Underflow" string).

  • The peek method allows us to view the topmost element without removing it from the stack. It returns the element at the last index of the items array, representing the top of the stack, or "Stack is empty" if the stack is empty.

Stack Complexity Analysis

The push, pop, and peek methods take constant time - O(1)O(1). This is because these operations are performed at the end of the array. The space complexity is proportional to the number of elements - O(n)O(n), where n is the quantity of stack elements.

Using Stack

Here is a complete stack implementation with a usage example:

Lesson Summary and Practice Announcement

Well done! You've completed your journey through stacks in TypeScript, mastering their concept, implementation, operations, and complexity analysis. Exercise sessions await you to further strengthen your TypeScript skills. So, let's set sail for some exciting hands-on practice!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal