Syntax error Find the lexicographically smallest string which satisfies the given condition in Python

Find the lexicographically smallest string which satisfies the given condition in Python



Suppose we have an array A of n numbers, where A[i] indicates the number of distinct characters in the prefix of length (i + 1) of a string s, we have to find the lexicographically smallest string that satisfies the given prefix array. All characters will be lowercase English alphabets [a-z]. If there is no such string then return -1.

So, if the input is like A = [1,1,2,3,4], then the output will be aabcd as prefix[0] has 1 distinct character, prefix[1] has 1 distinct character, prefix[2] has 2 distinct characters, prefix[3] has 3 distinct characters, prefix[4] has 4 distinct characters and the string is smallest.

To solve this, we will follow these steps −

  • n := size of A

  • character := 'a'

  • string := blank string

  • if n < 1 or A[0] is not 1, then

    • return -1

  • string := string concatenate character

  • character := next character of this current character

  • for i in range 1 to n, do

    • difference := A[i] - A[i - 1]

    • if difference > 1 or difference < 0 or A[i] > 26, then

      • return -1

    • otherwise when difference is same as 0, then

      • string := string concatenate 'a'

    • otherwise,

      • string := string concatenate character

      • character := next character of this current character

  • return string

Example 

Let us see the following implementation to get better understanding −

 Live Demo

def get_smallest_string(A):
   n = len(A)
   character = 'a'
   string = ""
   if (n < 1 or A[0] != 1):
      return -1
   string += str(character)
   character = chr(ord(character) + 1)
   for i in range(1, n):
      difference = A[i] - A[i - 1]
      if (difference > 1 or difference < 0 or A[i] > 26):
         return -1
      elif (difference == 0):
         string += 'a'
      else:
         string += character
         character = chr(ord(character) + 1)
return string

A = [1, 1, 2, 3, 4]
print(get_smallest_string(A))

Input

[1, 1, 2, 3, 4]

Output

aabcd
Updated on: 2020-08-20T07:44:51+05:30

456 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements