allizwell.jobsdoor360.in

Previous Smaller Element

Data Structures and Algorithms / Stacks and Queues / Previous Smaller Element

Previous Smaller Element

Previous Smaller Element is an important Stack problem in which we find the nearest element smaller than the current element on its left side. We use a Stack to solve this problem efficiently. This problem helps us understand Monotonic Stacks and prepares us for advanced problems such as Stock Span and Largest Rectangle in Histogram.

1. What Is the Previous Smaller Element?

For every element in an array, the Previous Smaller Element is the first element located to its left that is strictly smaller than the current element.

If no smaller element exists on the left side, the answer is usually -1.

Example

Array = [4, 5, 2, 10, 8]

Find the previous smaller element for every value:

  • For 4, no element exists on its left, so the answer is -1.
  • For 5, the previous smaller element is 4.
  • For 2, no smaller element exists on its left, so the answer is -1.
  • For 10, the previous smaller element is 2.
  • For 8, the previous smaller element is 2.

Input: [4, 5, 2, 10, 8]
Output: [-1, 4, -1, 2, 2]

2. Understanding the Problem

The important words in this problem are:

  • Previous: Search only toward the left side of the current element.
  • Smaller: The required value must be strictly smaller.
  • Nearest: Find the first valid smaller element while moving left.
Important: The previous smaller element is not necessarily the immediately adjacent element. It is the nearest element on the left whose value is strictly smaller.

3. Brute Force Approach

The simplest approach uses two nested loops. For every element, we move toward the left and search for the first smaller element.

Algorithm

  1. Traverse the array from left to right.
  2. For every element at index i, start checking from index i - 1.
  3. Move toward the beginning of the array.
  4. If an element smaller than the current element is found, store it.
  5. Stop searching for that element.
  6. If no smaller element is found, store -1.

C++ Code

#include <iostream>
#include <vector>
using namespace std;

vector<int> previousSmaller(vector<int>& arr) {

    int n = arr.size();

    vector<int> ans(n, -1);

    for (int i = 0; i < n; i++) {

        for (int j = i - 1; j >= 0; j--) {

            if (arr[j] < arr[i]) {

                ans[i] = arr[j];

                break;
            }
        }
    }

    return ans;
}

int main() {

    vector<int> arr = {4, 5, 2, 10, 8};

    vector<int> ans = previousSmaller(arr);

    for (int x : ans) {
        cout << x << " ";
    }

    return 0;
}

Output

-1 4 -1 2 2

Complexity

  • Time Complexity: O(n²) in the worst case.
  • Auxiliary Space: O(1), excluding the output array.
  • Output Space: O(n).

4. Optimized Approach Using Stack

We can improve the solution using a Stack. Instead of checking all previous elements for every position, we maintain a stack containing useful candidates for the previous smaller element.

We traverse the array from left to right because we are searching for elements on the left side.

Algorithm

  1. Create an empty stack and an answer array initialized with -1.
  2. Traverse the array from left to right.
  3. While the stack is not empty and its top is greater than or equal to the current element, pop the stack.
  4. If the stack is not empty, its top is the previous smaller element.
  5. If the stack is empty, the answer remains -1.
  6. Push the current element into the stack.
  7. Continue until all elements are processed.
Key Condition: st.top() >= arr[i] We remove greater elements and equal elements because the required previous element must be strictly smaller.

5. Step-by-Step Dry Run

Consider the array:

Array = [4, 5, 2, 10, 8]

We process the elements from left to right.

Current Element Stack Before Processing (Top First) Previous Smaller Stack After Push (Top First)
4 Empty -1 4
5 4 4 5, 4
2 5, 4 -1 2
10 2 2 10, 2
8 10, 2 2 8, 2

Final Answer

Previous Smaller: [-1, 4, -1, 2, 2]

6. Detailed Stack Operations

Processing Element 4

The stack is empty. Therefore, there is no previous smaller element. Store -1 and push 4.

Stack:

TOP
 |
[4]

Answer = -1

Processing Element 5

The top element is 4. Since 4 is smaller than 5, it is the previous smaller element. Push 5.

Stack:

TOP
 |
[5]
[4]

Answer = 4

Processing Element 2

The top element is 5, which is greater than 2, so remove it. The next top is 4, which is also greater than 2, so remove it. The stack becomes empty.

Before:

TOP
 |
[5]
[4]

Pop 5
Pop 4

After pushing 2:

TOP
 |
[2]

Answer = -1

Processing Element 10

The top element is 2, which is smaller than 10. Therefore, the previous smaller element is 2.

Stack before:

TOP
 |
[2]

After pushing 10:

TOP
 |
[10]
[2]

Answer = 2

Processing Element 8

The top element is 10, which is greater than 8. Remove it. Now the top is 2, which is smaller than 8.

Before:

TOP
 |
[10]
[2]

Pop 10

After pushing 8:

TOP
 |
[8]
[2]

Answer = 2

7. Optimized C++ Implementation

#include <iostream>
#include <vector>
#include <stack>
using namespace std;

vector<int> previousSmaller(vector<int>& arr) {

    int n = arr.size();

    vector<int> ans(n, -1);

    stack<int> st;

    for (int i = 0; i < n; i++) {

        // Remove elements that are not smaller
        while (!st.empty() && st.top() >= arr[i]) {
            st.pop();
        }

        // Remaining top is the previous smaller element
        if (!st.empty()) {
            ans[i] = st.top();
        }

        // Current element becomes a candidate
        st.push(arr[i]);
    }

    return ans;
}

int main() {

    vector<int> arr = {4, 5, 2, 10, 8};

    vector<int> ans = previousSmaller(arr);

    cout << "Previous Smaller Elements: ";

    for (int x : ans) {
        cout << x << " ";
    }

    return 0;
}

Output

Previous Smaller Elements: -1 4 -1 2 2

8. Previous Smaller Element Using Indices

Sometimes a problem asks for the index of the previous smaller element instead of its value. In that case, we store indices in the stack rather than values.

C++ Code

#include <iostream>
#include <vector>
#include <stack>
using namespace std;

vector<int> previousSmallerIndex(vector<int>& arr) {

    int n = arr.size();

    vector<int> ans(n, -1);

    stack<int> st;

    for (int i = 0; i < n; i++) {

        while (!st.empty() && arr[st.top()] >= arr[i]) {
            st.pop();
        }

        if (!st.empty()) {
            ans[i] = st.top();
        }

        st.push(i);
    }

    return ans;
}

int main() {

    vector<int> arr = {4, 5, 2, 10, 8};

    vector<int> ans = previousSmallerIndex(arr);

    for (int x : ans) {
        cout << x << " ";
    }

    return 0;
}

Output

-1 0 -1 2 2

For example, the previous smaller element for 10 is 2, and its index is 2.

9. Previous Smaller vs Next Smaller Element

Both problems use a similar Stack technique, but they differ in the direction of traversal.

Feature Previous Smaller Next Smaller
Search Direction Left side Right side
Traversal Left to right Right to left
Pop Condition Top >= Current Top >= Current
Answer Nearest smaller on left Nearest smaller on right

10. Important Edge Cases

Input Array Previous Smaller Elements Explanation
[1, 2, 3, 4] [-1, 1, 2, 3] Every new element has a smaller element immediately before it.
[4, 3, 2, 1] [-1, -1, -1, -1] No element has a smaller value on its left.
[5, 5, 5] [-1, -1, -1] Equal values are not smaller.
[2] [-1] Only one element exists.
[2, 1, 3] [-1, -1, 1] 1 is the previous smaller element for 3.
[] [] Empty input produces an empty answer.

11. Why Is the Optimized Solution O(n)?

The solution contains a for loop and a while loop, but its overall time complexity is O(n), not O(n²).

Each element is:

  • Pushed into the stack exactly once.
  • Popped from the stack at most once.

Across the complete traversal, there are at most n push operations and n pop operations. Therefore, the total work is proportional to n.

12. Time and Space Complexity

Approach Time Complexity Auxiliary Space
Brute Force O(n²) O(1), excluding output
Stack Approach O(n) O(n)

The answer array requires O(n) space. The optimized approach additionally uses a stack that can store up to n elements.

13. Applications

  • Stock Span Problem: Previous greater elements help determine how many consecutive previous days had lower or equal prices.
  • Histogram Problems: Previous smaller boundaries help calculate the maximum rectangle area.
  • Monotonic Stack Problems: The same technique appears in many nearest-smaller and nearest-greater problems.
  • Array Processing: Helps identify useful boundaries around each element.
  • Competitive Programming: Frequently used in efficient range and array problems.

14. Common Mistakes

  • Searching on the right instead of the left.
  • Traversing from right to left for the previous smaller element problem.
  • Using the wrong comparison condition.
  • Not removing equal elements when strictly smaller is required.
  • Accessing the stack top without checking whether the stack is empty.
  • Forgetting to push the current element after finding its answer.
  • Confusing the nearest smaller element with the minimum element in the entire left portion.
  • Returning an index when the question asks for a value.

15. Interview Questions

  1. What is the Previous Smaller Element problem?
  2. Why do we use a Stack to solve this problem?
  3. Why do we traverse from left to right?
  4. Why do we pop elements greater than or equal to the current element?
  5. What happens when the stack becomes empty?
  6. What is the time complexity of the optimized solution?
  7. Why is the solution O(n) even though it contains a while loop?
  8. How can we return the index of the previous smaller element?
  9. What is the difference between Previous Smaller and Next Smaller Element?
  10. How is this technique useful in the Largest Rectangle in Histogram problem?

16. Practice Problems

  1. Find the previous smaller element for every element in an array.
  2. Find the index of the previous smaller element.
  3. Find the next smaller element for every element.
  4. Find the previous greater element for every element.
  5. Find the next greater element for every element.
  6. Solve the Stock Span Problem using a Stack.
  7. Find the largest rectangle in a histogram.
  8. Find the nearest smaller value on both sides of every array element.

17. Summary

  • Previous Smaller Element finds the nearest strictly smaller value on the left side.
  • If no smaller element exists, the answer is -1.
  • The brute force approach takes O(n²) time.
  • The optimized approach uses a Stack.
  • Traverse the array from left to right.
  • Remove elements greater than or equal to the current element.
  • The remaining stack top is the previous smaller element.
  • The optimized time complexity is O(n).
  • The auxiliary space complexity is O(n).
Interview Tip: For Previous Smaller Element, traverse from left to right and remove all stack elements greater than or equal to the current value. The remaining top element is the nearest strictly smaller element.
Scroll to Top