703465. Delete Array Elements

Easy

Here is a detailed Markdown blog post for the "Delete Array Elements" problem:

Delete Array Elements

Summary

Given an array, delete all elements which are smaller than their next element or become smaller in the future. This problem can be solved using a stack data structure and iterating through the array once.

Detailed Explanation

To solve this problem, we will iterate through the array from left to right. For each element, we check if it is smaller than its next element or will become smaller in the future (i.e., there are elements greater than it that come after it). If either condition is true, we delete the current element.

Here's a step-by-step breakdown of the solution:

  1. Initialize an empty stack.
  2. Iterate through the array from left to right.
  3. For each element, check if it is smaller than its next element or will become smaller in the future (i.e., there are elements greater than it that come after it).
  4. If either condition is true, pop the current element from the stack and move on to the next one.
  5. Continue this process until you have processed all elements in the array.

Here's an ASCII art diagram illustrating the algorithm:

[1]  -> [2]
|       |
V       V
[2]  -> [3]
|       |
V       V
[3]

In this example, we start with the first element [1]. Since it is not smaller than its next element or will become smaller in the future, we push it onto the stack.

Next, we process the second element [2]. Since it is not smaller than its next element or will become smaller in the future, we push it onto the stack as well.

Finally, we process the third element [3]. Since it is larger than its previous element and there are no elements greater than it that come after it, we pop the second element from the stack and move on to the next one. The resulting array would be [1], [3].

Time complexity: O(n), where n is the size of the input array. Space complexity: O(1), since we only use a constant amount of space to store the stack.

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.Stack;

public class DeleteArrayElements {
    public static void deleteSmaller(int[] arr) {
        Stack<Integer> stack = new Stack<>();
        for (int i : arr) {
            while (!stack.isEmpty() && stack.peek() < i) {
                stack.pop();
            }
            stack.push(i);
        }
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.