Monday, August 8, 2022
HomeSoftware DevelopmentLexicographically smallest Subsequence of Array by deleting all occurrences of 1 ingredient

# Lexicographically smallest Subsequence of Array by deleting all occurrences of 1 ingredient

Given an array A[] of N integers, the duty is to seek out the lexicographically smallest subsequence of the array by deleting all of the occurrences of precisely one integer from the array.

Examples:

Enter: N = 5, A[] = {2, 4, 4, 1, 3}
Output: {2, 1, 3}
Clarification: All doable subsequences of the array
after eradicating precisely 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 amongst these is {2, 1, 3}

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

Method: To unravel the issue observe the under remark:

Commentary:

It may be noticed simply that to make a subsequence of an array lexicographically smallest, first ingredient which is bigger than its subsequent ingredient should be eliminated.

Based mostly on the above remark, the steps talked about under will be adopted to reach on the answer:

• Iterate via the array.
• At every iteration examine the present ingredient with the subsequent ingredient.
• Whether it is larger than the subsequent ingredient, break the loop and delete all of the occurrences of the present ingredient.
• Else, if the iteration completes with out breaking the loop, meaning the array is sorted in growing order. In such case, delete all of the occurrences of the final ingredient of the array.

Under is the implementation of the above strategy.

## C++

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

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

RELATED ARTICLES