Python Coding Test Course, Stack and Queue

Table of Contents

  1. 1. Introduction
  2. 2. Stack
  3. 3. Queue
  4. 4. Problem Description
  5. 5. Solution Process
  6. 6. Conclusion

1. Introduction

Two of the most fundamental data structures in learning programming are stacks and queues. These data structures have their own consistent operating principles and are frequently used in various algorithm problems. In this article, we will explain the concepts of stacks and queues and discuss algorithm problems that can be solved using them.

2. Stack

A stack is a data structure with a Last In First Out (LIFO) structure. The most recently inserted data is the first to be removed. The main operations of a stack include:

  • push(item): Adds item to the top of the stack.
  • pop(): Removes and returns the item at the top of the stack.
  • peek(): Returns the item at the top of the stack without removing it.
  • is_empty(): Returns True if the stack is empty, otherwise returns False.

3. Queue

A queue is a data structure with a First In First Out (FIFO) structure. The first data inserted is the first to be removed. The main operations of a queue are as follows:

  • enqueue(item): Adds item to the end of the queue.
  • dequeue(): Removes and returns the item at the front of the queue.
  • peek(): Returns the item at the front of the queue without removing it.
  • is_empty(): Returns True if the queue is empty, otherwise returns False.

4. Problem Description

The problem we will solve this time is Validating Parentheses using Stacks and Queues. The problem is as follows:

Write a function to check if a given string consisting only of parentheses is valid. A valid parentheses expression is one where all opened parentheses are closed correctly and each closing parenthesis matches an opened parenthesis.

Input

The input will be a single string consisting of the following parentheses:

  • ‘(‘
  • ‘)’
  • ‘{‘
  • ‘}’
  • ‘[‘
  • ‘]’

Output

Return True if all parentheses are correctly closed, otherwise return False.

5. Solution Process

To solve this problem, we will use a stack. We will process each character of the input string, adding opened parentheses to the stack and checking for matching opened parentheses when closing parentheses appear. The following is the process of solving the problem:

Step 1: Initialize the Stack

We initialize an empty list to use as a stack to traverse each character of the string.

Step 2: Set Up Parentheses Mapping

We create a dictionary to define the relationship between opened and closed parentheses.

Step 3: Traverse the String

We traverse the string character by character, adding opened parentheses to the stack. If a closing parenthesis appears, we check for matching with the top element of the stack.

Step 4: Check Stack Status

After traversing the string, if there are no contents left in the stack, it indicates that all parentheses are correctly closed.

Python Code Implementation


def is_valid_parentheses(s: str) -> bool:
    stack = []
    mapping = {")": "(", "}": "{", "]": "["}
    
    for char in s:
        if char in mapping:  # In case of a closing parenthesis
            top_element = stack.pop() if stack else '#'  # Pop from the stack
            if mapping[char] != top_element:  # Check mapping
                return False
        else:  # In case of an opening parenthesis
            stack.append(char)  # Add to the stack
    
    return not stack  # If the stack is empty, return True, otherwise return False
    

Step-by-Step Explanation

Now, let’s delve into each step in more detail.

Stack Initialization

We initialize the stack as an empty list with “stack = []“. The stack is used to check if the parentheses are opened and closed in the correct order.

Setting Up Parentheses Mapping

We define the mapping of each closing parenthesis to its corresponding opening parenthesis by creating a dictionary: “mapping = {“)”: “(“, “}”: “{“, “]”: “[“}“. This mapping is used for comparison when encountering closing parentheses.

Traversing the String

We use a for loop to traverse the string character by character. If the character is a closing parenthesis, we pop an element from the stack and compare it with the mapped opening parenthesis. If there is no match, it is invalid, and we return False. If the character is an opening parenthesis, we add it to the stack.

Checking Stack Status

If the stack is empty after complete traversal, it indicates that all opened parentheses are matched correctly. Thus, return not stack returns True if the stack is empty, otherwise it returns False.

6. Conclusion

In this tutorial, we first examined the basic concepts of stacks and queues, and then discussed the process of solving the parentheses validation problem using a stack. Stacks, with their LIFO structure, are useful in various algorithm problems, and understanding and utilizing them is very important for preparing for coding tests.

Queues are also important data structures that operate in a FIFO manner and can be applied to many problems. Stacks and queues form the basis for solving coding problems, and a good understanding of these data structures is often required. Based on the content discussed in this article, I hope you practice by solving more problems to build your skills.