The Wayback Machine - https://web.archive.org/web/20240828113100/https://www.geeksforgeeks.org/lexicographically-smallest-string-which-is-not-a-subsequence-of-given-string/
Open In App

Lexicographically smallest string which is not a subsequence of given string

Last Updated : 01 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Medium
49.97%
18.2K

Given a string S, the task is to find the string which is lexicographically smallest and not a subsequence of the given string S.

 Examples:

Input: S = “abcdefghijklmnopqrstuvwxyz”
Output: 
aa
Explanation:
String “aa” is the lexicographically smallest string which is not present in the given string as a subsequence.

Input: S = “aaaa”
Output: 
aaab
Explanation:
String “aaa” is the lexicographically smallest string which is not present in the given string as a subsequence.

Approach: The idea is to solve the given problem is to find the frequency of the character ‘a’ in the given string (say f). If the value of f is less than the length of the string, then the answer would be the string formed by concatenating ‘a’ f+1 number of times as aaa….(f+1 times) will be the required lexicographically smallest string which is not a subsequence. Otherwise, the answer would be the string formed by concatenating ‘a’ (f-1 times) and ‘b’ at the end of the string.

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find lexicographically smallest string that
// is not a subsequence of S
string smallestNonSubsequence(string S, int N)
{
    // variable to store frequency of 'a'
    int freq = 0;
    // calculate frequency of 'a'
    for (int i = 0; i < N; i++)
        if (S[i] == 'a')
            freq++;
    // Initialize string consisting of freq number of 'a'
    string ans(freq, 'a');
    // change the last digit to 'b'
    if (freq == N)
        ans[freq - 1] = 'b';
    // add another 'a' to the string
    else
        ans += 'a';
    // return the answer string
    return ans;
}
// Driver code
int main()
{
    // Input
    string S = "abcdefghijklmnopqrstuvwxyz";
    int N = S.length();
 
    // Function call
    cout << smallestNonSubsequence(S, N) << endl;
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
public class GFG
{
 
// Function to find lexicographically smallest string that
// is not a subsequence of S
static String smallestNonSubsequence(String S, int N)
{
   
    // variable to store frequency of 'a'
    int freq = 0;
   
    // calculate frequency of 'a'
    for (int i = 0; i < N; i++)
        if (S.charAt(i) == 'a')
            freq++;
   
    // Initialize string consisting of freq number of 'a'
 String ans="";
    for(int i = 0; i < f req; i++){
        ans += 'a';
    }
   
    // change the last digit to 'b'
    if (freq == N)
       ans = ans.replace(ans.charAt(freq - 1), 'b');
   
    // add another 'a' to the string
    else
        ans += 'a';
   
    // return the answer string
    return ans;
}
 
// Driver Code
public static void main(String args[])
{
    String S = "abcdefghijklmnopqrstuvwxyz";
    int N = S.length();
 
    // Function call
    System.out.println(smallestNonSubsequence(S, N));
    }
}
 
// This code is contributed by SoumikMondal


Python3




# Python3 program for the above approach
 
# Function to find lexicographically smallest
# string that is not a subsequence of S
def smallestNonSubsequence(S, N):
     
    # Variable to store frequency of 'a'
    freq = 0
     
    # Calculate frequency of 'a'
    for i in range(N):
        if (S[i] == 'a'):
            freq += 1
             
    # Initialize string consisting
    # of freq number of 'a'
    ans = ""
    for i in range(freq):
        ans += 'a'
 
    # Change the last digit to 'b'
    if (freq == N):
        ans = ans.replace(ans[freq - 1], 'b')
         
    # Add another 'a' to the string
    else:
        ans += 'a'
         
    # Return the answer string
    return ans
 
# Driver code
if __name__ == '__main__':
     
    # Input
    S = "abcdefghijklmnopqrstuvwxyz"
    N = len(S)
 
    # Function call
    print(smallestNonSubsequence(S, N))
     
# This code is contributed by SURENDRA_GANGWAR


C#




// C# program equivalent to the above Java program
using System;
 
class GFG
{
   
  // Function to find lexicographically smallest string
  // that is not a subsequence of S
  static string SmallestNonSubsequence(string S, int N)
  {
     
    // variable to store frequency of 'a'
    int freq = 0;
 
    // calculate frequency of 'a'
    for (int i = 0; i < N; i++)
      if (S[i] == 'a')
        freq++;
 
    // Initialize string consisting of freq number of
    // 'a'
    string ans = "";
    for (int i = 0; i < freq; i++) {
      ans += 'a';
    }
 
    // change the last digit to 'b'
    if (freq == N)
      ans = ans.Replace(ans[freq - 1], 'b');
 
    // add another 'a' to the string
    else
      ans += 'a';
 
    // return the answer string
    return ans;
  }
 
  // Driver Code
  static void Main(string[] args)
  {
    string S = "abcdefghijklmnopqrstuvwxyz";
    int N = S.Length;
 
    // Function call
    Console.WriteLine(SmallestNonSubsequence(S, N));
  }
}
 
// This code is contributed by phasing17


Javascript




<script>
 
// JavaScript program for the above approach
 
// Function to find lexicographically smallest string that
// is not a subsequence of S
function smallestNonSubsequence(S,N)
{
 
    // variable to store frequency of 'a'
    let freq = 0;
     
    // calculate frequency of 'a'
    for (let i = 0; i < N; i++)
        if (S[i] == 'a')
            freq++;
             
    // Initialize string consisting of freq number of 'a'
    let ans = new Array(freq).fill('a').join('');
    // change the last digit to 'b'
    if (freq == N)
        ans[freq - 1] = 'b';
         
    // add another 'a' to the string
    else
        ans += 'a';
         
    // return the answer string
    return ans;
}
 
// Driver code
 
// Input
let S = "abcdefghijklmnopqrstuvwxyz";
let N = S.length;
 
// Function call
document.write(smallestNonSubsequence(S, N),"</br>");
 
// This code is contributed by shinjanpatra
 
</script>


Output

aa

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

 



Similar Reads

Minimum size lexicographically smallest string which is not a substring of given string
Given a string s, the task is to find the lexicographically smallest string of minimum characters that do not exist as a substring in S. Examples: Input: S = "aabacdefghijklmnopqrstuvwxyz"Output: adExplanation: All the single digit strings from [a-z] occur in the given string and in two character strings, strings {aa, ab, ac} occur but "ad" is not
7 min read
Lexicographically smallest subsequence possible by removing a character from given string
Given a string S of length N, the task is to find the lexicographically smallest subsequence of length (N - 1), i.e. by removing a single character from the given string. Examples: Input: S = "geeksforgeeks"Output: "eeksforgeeks"Explanation: Lexicographically smallest subsequence possible is "eeksforgeeks". Input: S = "zxvsjas"Output: "xvsjas"Expla
8 min read
Lexicographically smallest K-length subsequence from a given string
Given a string S of length N, the task is to find the lexicographically smallest K-length subsequence from the string S (where K &lt; N). Examples: Input: S = "bbcaab", K = 3Output: "aab" Input: S = "aabdaabc", K = 3Output: "aaa" Naive Approach: The simplest approach is to generate all possible subsequences of length K from the given string and sto
8 min read
Lexicographically smallest permutation number up to K having given array as a subsequence
Given an integer K and an array arr[] having N pairwise distinct integers in the range [1, K], the task is to find the lexicographically smallest permutation of the first K positive integers such that the given array arr[] is a subsequence of the permutation. Examples: Input: arr[] = {1, 3, 5, 7}, K = 8Output: 1 2 3 4 5 6 7 8Explanation: {1, 2, 3,
9 min read
Lexicographically shortest string of length at most K which is not a substring of given String
Given a string S, the task is to find the lexicographically shortest string of length less than or equal to K which is not a substring of the given string. If not possible, print -1. Examples: Input: S = zxabcehgf, K = 2Output: dExplanation: Lexicographically, the shortest string which is not a substring of a given string is d. Input: S = sdhaacbde
9 min read
Find the lexicographically smallest string which satisfies the given condition
Given an array, arr[] of N integers, where arr[i] represents the number of distinct characters in the prefix of length (i + 1) of a string S. The task is to find the lexicographically smallest string (if any exists) that satisfies the given prefix array. The string should be of lowercase English alphabets [a-z]. If no such string exists then print
10 min read
Lexicographically smallest string which differs from given strings at exactly K indices
Given two strings S1 and S2 of length N and a positive integer K, the task is to find the lexicographically smallest string such that it differs from the given two strings S1 and S2 at exactly K places. If there is no such string exists then print "-1". Examples: Input: N = 4, K = 3, S1 = "ccbb", S2 = "caab" Output: abcb Explanation: String "abcb"
15 min read
Lexicographically smallest String by moving one Subsequence to the end
Given a string S of size N, having lowercase alphabets, the task is to find the lexicographically minimum string after moving a subsequence to the end of the string only once. Example: Input: N = 3, S = "asa" Output: aasExplanation: The optimal subsequence is "s". Removed, and added at last. Hence the final string is 'aa' + 's' ='aas' Input: N = 7,
9 min read
Length of smallest substring of a given string which contains another string as subsequence | Set 2
Given two strings A and B, the task is to find the smallest substring of A having B as a subsequence. Examples: Input: A = "abcdefababaef", B = "abf"Output: 5Explanation:Smallest substring of A having B as subsequence is abcdef.Therefore, the required length is 5. Input: A = "abcdefababaef", B = "aef"Output: 3 Recommended: Please solve it on "PRACT
12 min read
Find length of smallest substring of a given string which contains another string as subsequence
Given two strings A and B, the task is to find the smallest substring of A having B as a subsequence. If there are multiple such substrings in A, return the substring that has the smallest starting index. Examples : Input : A = "abcedbaced" B = "bed"Output : "bced"Explanation : The substring A[2 : 5] is the shortest substring that contains the stri
15 min read
Lexicographically smallest Subsequence of Array by deleting all occurrences of one element
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:
6 min read
Lexicographically smallest string of maximum length made up of first K alphabets that does not contain any repeating substring
Given a positive integer K, the task is to find lexicographically the smallest string that can be generated by using the first K lowercase alphabets such that no substring of length at least 2 is repeated in the generated string. Examples: Input: K = 3Output: aabacbbccaExplanation:In the string "aabacbbcca", all possible substrings of length at lea
5 min read
Lexicographically smallest binary string formed by flipping bits at indices not divisible K1 or K2 such that count of 1s is always greater than 0s from left
Given a binary string S(1-based indexing) of size N, and two positive integers K1 and K2, the task is to find the lexicographically smallest string by flipping the characters at indices that are not divisible by either K1 or K2 such that the count of 1s till every possible index is always greater than the count of 0s. If it is not possible to form
8 min read
Find all words in given Sentence that are lexicographically increasing and lexicographically decreasing
Given a string representing a sentence named str of size N, the task is to find all the valid words in a sentence that are lexicographically sorted in increasing order and in decreasing order along with their counts. Note: Valid words are:- words don't containing numbers.words greater than size 1. Examples: Input: str="geeks for geeks"Output: 1 "fo
10 min read
Find the lexicographically smallest sequence which can be formed by re-arranging elements of second array
Given two arrays A and B of N integers. Reorder the elements of B in itself in such a way that the sequence formed by (A[i] + B[i]) % N after re-ordering is the smallest lexicographically. The task is to print the lexicographically smallest sequence possible. Note: The array elements are in range [0, n).Examples: Input: a[] = {0, 1, 2, 1}, b[] = {3
11 min read
Order of indices which is lexicographically smallest and sum of elements is &lt;= X
Given an array arr[] and an integer X, the task is to find the indices such that: The sum of elements on the found indices is ? XThe number of indices is maximum possible.The order of indices is lexicographically smallest i.e. {0, 0, 1} is lexicographically smaller than {1, 0, 0} Note that any index can be chosen more than once.Examples: Input: arr
9 min read
Lexicographically smallest string formed by appending a character from the first K characters of a given string
Given a string S consisting of lowercase alphabets. The task is to find the lexicographically smallest string X of the same length only that can be formed using the operation given below: In a single operation, select any one character among the at most first K characters of string S, remove it from string S and append it to string X. Apply this op
7 min read
Lexicographically smallest string possible by performing K operations on a given string
Given a string S of size N and a positive integer K, the task is to perform atmost K operations on string S to make it lexicographically smallest possible. In one operation, swap S[i] and S[j] and then change S[i] to any character, given 1 ? i &lt; j ? N. Examples: Input: S = "geek", K = 5Output: aaaaExplanation: In 1st operation: take i = 1 and j
8 min read
Lexicographically smallest string with period K possible by replacing '?'s from a given string
Given a string S consisting of N lowercase characters and character '?' and a positive integer K, the task is to replace each character '?' with some lowercase alphabets such that the given string becomes a period of K. If it is not possible to do so, then print "-1". A string is said to be a period of K if and only if the length of the string is a
9 min read
Lexicographically smallest string with given string as prefix
Given an array arr[] consisting of N strings and a string S if size M, the task is to find the lexicographically smallest string consisting of the string S as the prefix. If there doesn't exist any string starting with prefix S then print "-1". Examples: Input: arr[] = {"apple", "appe", "apl", "aapl", "appax"}, S = "app"Output: appaxExplanation:The
6 min read
Lexicographically smallest string whose hamming distance from given string is exactly K
Given a lowercase string A of length N and an integer K, find the lexicographically smallest string B of the same length as A such that hamming distance between A and B is exactly K. Examples: Input : A = "pqrs", k = 1. Output : aqrs We can differ by at most one character. So we put 'a' in the beginning to make the result lexicographically smallest
8 min read
Lexicographically smallest permutation of Array such that prefix sum till any index is not equal to K
Given an array arr[], consisting of N distinct positive integers and an integer K, the task is to find the lexicographically smallest permutation of the array, such that the sum of elements of any prefix of the output array is not equal to the K. If there exists no such permutation, then print "-1". Otherwise, print the output array. Examples: Inpu
7 min read
Lexicographically smallest permutation of {1, .. n} such that no. and position do not match
Given a positive integer n, find the lexicographically smallest permutation p of {1, 2, .. n} such that pi != i. i.e., i should not be there at i-th position where i varies from 1 to n. Examples: Input : 5 Output : 2 1 4 5 3 Consider the two permutations that follow the requirement that position and numbers should not be same. p = (2, 1, 4, 5, 3) a
7 min read
K-th lexicographically smallest unique substring of a given string
Given a string S. The task is to print the K-th lexicographically the smallest one among the different substrings of s.A substring of s is a string obtained by taking out a non-empty contiguous part in s. For example, if s = ababc, a, bab and ababc are substrings of s, while ac, z, and an empty string are not. Also, we say that substrings are diffe
5 min read
Lexicographically smallest permutation of a string with given subsequences
Given a string consisting only of two lowercase characters [Tex]x [/Tex]and [Tex]y [/Tex]and two numbers [Tex]p [/Tex]and [Tex]q [/Tex]. The task is to print the lexicographically smallest permutation of the given string such that the count of subsequences of [Tex]xy [/Tex]is [Tex]p [/Tex]and of [Tex]yx [/Tex]is [Tex]q [/Tex]. If no such string exi
9 min read
Lexicographically smallest string possible by inserting given character
Given a string S and a character C, the task is to place a character in the string in such a way that the string obtained is the lexicographically smallest string. Examples: Input: S = "acd", C = 'b'Output: "abcd"Explanation: The possible strings formed by placing the character C in string at different indices are ["bacd", "abcd", "acbd", "acdb"]Th
5 min read
Modify given string such that odd and even indices is lexicographically largest and smallest
Given a string S consisting of N lowercase alphabets, the task is to modify the given string by replacing all the characters with characters other than the current character such that the suffix string formed from odd and even indices is lexicographically largest and smallest respectively among all possible modifications of the string S. Examples:
6 min read
Lexicographically smallest permutation of [1, N] based on given Binary string
Given a binary string S of size (N - 1), the task is to find the lexicographically smallest permutation P of the first N natural numbers such that for every index i, if S[i] equals '0' then P[i + 1] must be greater than P[i] and if S[i] equals '1' then P[i + 1] must be less than P[i]. Examples: Input: N = 7, S = 100101Output: 2 1 3 5 4 7 6Explanati
6 min read
Lexicographically smallest anagram of given string in range [L, R] for Q queries
Given a string S of size N and an array queries, containing Q queries in the form of L, R. The task is to find the lexicographically smallest anagram of string from L to R for each query. Example: Input: S = "bbaacd"queries[]={{1, 3}, {2, 5}}Output:aabaacd Input: S="bbdfaaacaed"queries[]={{0, 4}, {4, 8}}Output:abbdfaaaac Approach: This question can
7 min read
Kth lexicographically smallest distinct String from given Array of Strings
Given an array arr having N strings and an integer K, the task is to find the lexicographically smallest Kth distinct string. Print an empty string if no such string exists. Example: Input: arr[]={"aa", "aa", "bb", "cc", "dd", "cc"}, K = 2Output: ddExplanation: Distinct strings are: "bb", "dd". 2nd smallest string among these is "dd" Input: arr[]={
4 min read