Introduction to the Lesson

Welcome to our deep dive into the practical application of Stack data structures for solving algorithmically complex problems. Today, we will explore how a Stack, a Last-In-First-Out (LIFO) data structure, can come in handy for solving seemingly difficult computational challenges. We will focus on two problems that you can face during the technical interviews or in the real-work coding!

Problem 1: Previous Value Finder
Problem 1: Efficient Approach Explanation

Instead of the naive, brute-force approach, a more elegant and efficient solution would involve the use of Stacks. A Stack would allow us to track only relevant numbers, discarding the ones that won't contribute to the solution. This ensures higher accuracy in our solutions and optimizes computational resources.

Problem 1: Solution Building

Let's dissect our solution to understand each step better:

We start off by initializing an empty Stack and a result list with -1.

result = [-1]
stack = []

This -1 in the result list serves as a placeholder for the first element, as it has no preceding elements.

Next, we loop through our list of numbers. For every number, a while loop keeps popping items from the stack until we find a number smaller than the current one or until the stack is empty.

for num in numbers:
    while stack and stack[-1] >= num:
        stack.pop()

At this point, if our stack is empty, it means there are no previous smaller elements, so we add -1 to the result list. If the stack is not empty, we add the top element of the stack (i.e., the previous smaller number) to our result list.

result.append(stack[-1] if stack else -1)  

After this, we add the current number to our stack.

stack.append(num)

We then proceed to the next number and repeat the process.

Finally, as the first element of the result list was just an initial placeholder and not part of our actual solution, we return the result list from the second element to the end.

return result[1:]

And just like that, we have an efficient solution to our first problem! Here is the full code:

def findSmallerPreceeding(numbers):
    result = [-1]
    stack = []
    for num in numbers:
        while stack and stack[-1] >= num:
            stack.pop()
        result.append(stack[-1] if stack else -1)
        stack.append(num)
    return result[1:]
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