Select Page

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

Kashish Kumar
Published: August 5, 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++

 ` ` `#include ``using` `namespace` `std;`` ` `void` `printSmallestSubsequence(``int` `N, ``int` `A[])``{`` ` `    ``    ``    ``int` `target = A[N - 1];`` ` `    ``    ``for` `(``int` `i = 0; i < N - 1; i++) {`` ` `        ``        ``        ``        ``        ``if` `(A[i] > A[i + 1]) {``            ``target = A[i];``            ``break``;``        ``}``    ``}`` ` `    ``    ``    ``for` `(``int` `i = 0; i < N; i++) {``        ``if` `(A[i] != target) {``            ``cout << A[i] << ``" "``;``        ``}``    ``}``}`` ` `int` `main()``{``    ``int` `N = 5;``    ``int` `A[] = { 2, 4, 4, 1, 3 };`` ` `    ``    ``printSmallestSubsequence(N, A);``    ``return` `0;``}`

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

Source: www.geeksforgeeks.org