Find the lexicographically smallest string which satisfies the given condition | 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
< ? php function smallestString ( $ N , $ A ) { $ ch = ' a ' ; $ S = " " ; if ( $ N < 1 $ A [ 0 ] != 1 ) { $ S = " - 1" ; return $ S ; } $ S . = $ ch ; $ ch ++ ; for ( $ i = 1 ; $ i < $ N ; $ i ++ ) { $ 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 ; } $ arr = array ( 1 , 1 , 2 , 3 , 3 ) ; $ n = sizeof ( $ arr ) ; echo ( smallestString ( $ n , $ arr ) ) ; ? >