Stack & Queue Problems Master List šŸŽÆ

beginner
19 min

Stack & Queue Problems Master List šŸŽÆ

Welcome to our comprehensive guide on Stack and Queue problems! šŸ“

In this lesson, we'll dive deep into these essential data structures, learn their real-world applications, and solve various problems to strengthen your understanding. Let's get started!

What are Stacks and Queues? šŸ’”

Stacks

A Stack is a Linear data structure that follows the LIFO (Last In, First Out) principle. It's like a pile of books where the last book you put is the first one you take out.

python
# Python Stack Example from collections import deque stack = deque() stack.append(1) # Add element to the end stack.append(2) # Add element to the end stack.popleft() # Remove and return the first element (last one added)

Queues

A Queue is a Linear data structure that follows the FIFO (First In, First Out) principle. It's like a line at a grocery store, where the first person in line is the first to be served.

python
# Python Queue Example from collections import deque queue = deque() queue.append(1) # Add element to the end queue.append(2) # Add element to the end queue.popleft() # Remove and return the first element (first one added)

Problems šŸ“

Stack Problems

  1. Next Greater Element Given an array, find the next greater element for each element. If there is no next greater element, consider the next greater element as -1.

    python
    def nextGreaterElement(arr, n): stack, res = [], [-1] * n for i in range(n): while stack and stack[-1] < arr[i]: stack.pop() if stack: res[stack[-1]] = arr[i] stack.append(arr[i]) return res

Queue Problems

  1. Sliding Window Maximum Given an array and a sliding window (k), find the maximum element in every contiguous subarray of size 'k'.

    python
    def maxSlidingWindow(arr, k): deque, res = deque(), [] for i in range(len(arr)): while deque and deque[-1] < arr[i]: deque.pop() deque.append(arr[i]) if i >= k - 1: res.append(deque[0]) if deque[0] == arr[i - k + 1]: deque.popleft() return res
Quick Quiz
Question 1 of 1

What is the main difference between a Stack and a Queue?

With these problems, you'll get hands-on experience with Stacks and Queues, making it easier to understand their practical applications. Happy coding! šŸ’»šŸš€