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

Given 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 need to find the lexicographically smallest string that satisfies the given prefix array. All characters will be lowercase English alphabets [a-z]. If no such string exists, return -1.

For example, if A = [1,1,2,3,4], the output will be "aabcd" because prefix[0] has 1 distinct character, prefix[1] has 1 distinct character, prefix[2] has 2 distinct characters, prefix[3] has 3 distinct characters, and prefix[4] has 4 distinct characters, and this string is lexicographically smallest.

Algorithm

To solve this problem, we follow these steps ?

  • Initialize variables: n = size of A, character = 'a', string = empty string

  • Validate first element: if n < 1 or A[0] ? 1, return -1

  • Add first character 'a' to string and move to next character

  • For each remaining position i from 1 to n:

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

    • If difference > 1 or difference < 0 or A[i] > 26, return -1

    • If difference = 0, append 'a' (reuse existing character)

    • Otherwise, append current character and move to next

  • Return the constructed string

Example

Let us see the implementation to get better understanding ?

def get_smallest_string(A):
    n = len(A)
    character = 'a'
    string = ""
    
    # Validate first element
    if (n < 1 or A[0] != 1):
        return -1
    
    # Add first character
    string += str(character)
    character = chr(ord(character) + 1)
    
    # Process remaining elements
    for i in range(1, n):
        difference = A[i] - A[i - 1]
        
        # Invalid conditions
        if (difference > 1 or difference < 0 or A[i] > 26):
            return -1
        # Same number of distinct characters
        elif (difference == 0):
            string += 'a'
        # Need one more distinct character
        else:
            string += character
            character = chr(ord(character) + 1)
    
    return string

# Test the function
A = [1, 1, 2, 3, 4]
print("Input array:", A)
print("Result:", get_smallest_string(A))
Input array: [1, 1, 2, 3, 4]
Result: aabcd

How It Works

The algorithm works by maintaining the current available character and building the string character by character. When the distinct character count remains the same, we use 'a' to ensure lexicographical minimality. When it increases by 1, we introduce the next available character.

Edge Cases

# Test edge cases
test_cases = [
    [1, 2, 2, 3],  # Valid case
    [2, 2, 3],     # Invalid: doesn't start with 1
    [1, 1, 3],     # Invalid: jump from 1 to 3
    [1, 0, 1]      # Invalid: decreasing count
]

for i, case in enumerate(test_cases):
    result = get_smallest_string(case)
    print(f"Case {i+1}: {case} ? {result}")
Case 1: [1, 2, 2, 3] ? abac
Case 2: [2, 2, 3] ? -1
Case 3: [1, 1, 3] ? -1
Case 4: [1, 0, 1] ? -1

Conclusion

This algorithm constructs the lexicographically smallest string by greedily using 'a' when possible and introducing new characters only when the distinct count increases. The time complexity is O(n) and space complexity is O(1) excluding the output string.

Updated on: 2026-03-25T09:29:24+05:30

506 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements