Find the lexicographically smallest string which satisfies the given condition | C ++ implementation of the approach ; Function to return the required string ; First character will always be ' a ' ; To store the resultant string ; Since length of the string should be greater than 0 and first element of array should be 1 ; Check one by one all element of given prefix array ; If the difference between any two consecutive elements of the prefix array is greater than 1 then there will be no such string possible that satisfies the given array Also , string cannot have more than 26 distinct characters ; If difference is 0 then the ( i + 1 ) th character will be same as the ith character ; If difference is 1 then the ( i + 1 ) th character will be different from the ith character ; Return the resultant string ; Driver code
#include <iostream> NEW_LINE using namespace std ; string smallestString ( int N , int A [ ] ) { char ch = ' a ' ; string S = " " ; if ( N < 1 A [ 0 ] != 1 ) { S = " - 1" ; return S ; } S += ch ; ch ++ ; for ( int i = 1 ; i < N ; i ++ ) { int diff = A [ i ] - A [ i - 1 ] ; if ( diff > 1 diff < 0 A [ i ] > 26 ) { S = " - 1" ; return S ; } else if ( diff == 0 ) S += ' a ' ; else { S += ch ; ch ++ ; } } return S ; } int main ( ) { int arr [ ] = { 1 , 1 , 2 , 3 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << smallestString ( n , arr ) ; return 0 ; }