VOOZH about

URL: https://www.geeksforgeeks.org/dsa/delete-array-elements-which-are-smaller-than-next-or-become-smaller/

⇱ Delete K Elements which are Smaller than Next or Become Smaller - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Delete K Elements which are Smaller than Next or Become Smaller

Last Updated : 28 May, 2026

Given an array arr[] and an integer k. The task is to delete k elements which are smaller than next element (i.e., we delete arr[i] if arr[i] < arr[i+1]) or become smaller than next because next element is deleted.

Note: The deletion operation should start from left to right.

Example:

Input : arr[] = [20, 10, 25, 30, 40], k = 2
Output : 25 30 40
Explanation : First we delete 10 because it follows arr[i] < arr[i+1]. Then we delete 20 because 25 is moved next to it and it also starts following the condition.

Input : arr[] = [3, 100, 1], k = 1
Output : 100 1
Explanation : arr[0] < arr[1] means 3 is less than 100, so delete 3

Input: arr[] = [23, 45, 11, 77, 18], k = 3
Output : 77 18
Explanation : We delete 23, 45 and 11 as they follow the condition arr[i] < arr[i+1]

Using Stack - O(n) time and O(n) space

The idea is to use a stack to keep track of elements we want to retain while iterating through the input array. For each element, we compare it with the top of the stack. If the current element is greater than the stack's top element and we still have deletions available, we pop elements from the stack until this condition is no longer met.

Step by step approach:

  1. Create an empty stack to store elements.
  2. Iterate through each element in the input array.
  3. While the stack is not empty, current element > stack top, and k > 0, pop from stack and decrement k.
  4. Push the current element onto the stack.
  5. Convert the final stack to the result array (reversed since stack is LIFO).

Output
25 30 40 

Space Optimized - O(n) time and O(n) space

The idea for the single array approach is essentially the same, but we can directly use a vector as our answer array instead of a stack. Since we're building our result directly in the correct order, we don't need the extra step of transferring and reversing elements at the end, making this approach more efficient and cleaner.


Output
25 30 40 
Comment