Welcome to this comprehensive lesson on Data Structures and Algorithms! In this tutorial, we will delve into the concept of the "Previous Smaller Element" (PSE), a vital algorithmic concept useful in various real-world scenarios.
The Previous Smaller Element of an element x in a list is the first element to the left of x (if any) that is smaller than x. This concept is crucial in sorting algorithms, stack operations, and problem-solving techniques.
š” Pro Tip: The PSE can help us find the next smaller element in a sorted array, which is an essential problem in competitive programming.
Let's consider a simple array:
[10, 4, 3, 7, 2, 5]
In this array, the PSE for each element is as follows:
To find the PSE of an element, we will traverse the array from left to right, keeping track of the current element and its PSE. Here's a step-by-step guide:
def find_pses(arr):
n = len(arr)
pses = [0]*n # Initialize an array to store PSEs
stack = []
for i in range(n):
while stack and arr[stack[-1]] > arr[i]:
pses[stack.pop()] = arr[i]
stack.append(i)
while stack:
pses[stack.pop()] = -1
return pses
arr = [10, 4, 3, 7, 2, 5]
print(find_pses(arr)) # Output: [0, 3, -1, 4, 3, -1]In this example, we used a stack to keep track of the current element and its PSE efficiently. The find_pses() function returns the PSE array for the given input array.
Now that you've learned the basics of the Previous Smaller Element, it's time to test your knowledge!
Given the array [12, 7, 5, 8, 10, 11, 4, 3], what are the Previous Smaller Elements for each element?