Skip to content
Related Articles

Related Articles

Lexicographically smallest Subsequence of Array by deleting all occurrences of one element

View Discussion
Improve Article
Save Article
  • Last Updated : 05 Aug, 2022

Given an array A[] of N integers, the task is to find the lexicographically smallest subsequence of the array by deleting all the occurrences of exactly one integer from the array.

Examples:

Input: N = 5, A[] = {2, 4, 4, 1, 3}
Output: {2, 1, 3}
Explanation: All possible subsequences of the array 
after removing exactly one integer are : 
On deleting 2: {4, 4, 1, 3}
On deleting 4: {2, 1, 3}
On deleting 1: {2, 4, 4, 3}
On deleting 3: {2, 4, 4, 1}
Lexicographically smallest among these is {2, 1, 3}

Input: N = 6, A[] = {1, 1, 1, 1, 1, 1}
Output: {}

 

Approach: To solve the problem follow the below observation:

Observation:

It can be observed easily that to make a subsequence of an array lexicographically smallest, first element which is greater than its next element must be removed. 

Based on the above observation, the steps mentioned below can be followed to arrive at the solution:

  • Iterate through the array.
  • At each iteration compare the current element with the next element.
  • If it is greater than the next element, break the loop and delete all the occurrences of the current element.
  • Else, if the iteration completes without breaking the loop, that means the array is sorted in increasing order. In such case, delete all the occurrences of the last element of the array.

Below is the implementation of the above approach.

C++




// C++ code for the above approach
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to print Lexicographically
// smallest subsequence  of the array by
// deleting all the occurrences of exactly
// one integer from the array
void printSmallestSubsequence(int N, int A[])
{
  
    // Variable to store the integer to be
    // deleted
    int target = A[N - 1];
  
    // Iterate through the array
    for (int i = 0; i < N - 1; i++) {
  
        // If current element is greater
        // than the next element set that
        // element equal to target and
        // break the loop
        if (A[i] > A[i + 1]) {
            target = A[i];
            break;
        }
    }
  
    // Print rest of the array without
    // including the target element
    for (int i = 0; i < N; i++) {
        if (A[i] != target) {
            cout << A[i] << " ";
        }
    }
}
  
// Driver Code
int main()
{
    int N = 5;
    int A[] = { 2, 4, 4, 1, 3 };
  
    // Function Call
    printSmallestSubsequence(N, A);
    return 0;
}

Output

2 1 3 

Time Complexity: O(N)
Auxiliary Space: O(1)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!