VOOZH about

URL: https://www.geeksforgeeks.org/dsa/lexicographically-smallest-string-with-unique-adjacent-characters/

⇱ Lexicographically smallest String with unique adjacent characters - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Lexicographically smallest String with unique adjacent characters

Last Updated : 17 Apr, 2024

Given a string consisting of 'a', 'b', 'c', or '?', you are required to replace the question marks '?' in the string. The goal is to find a replacement that adheres to the following conditions:

  • The string can only contain 'a', 'b', and 'c'.
  • No two consecutive characters in the string can be the same.
  • The first and last characters of the string cannot be identical.
  • If there are multiple valid solutions, choose the lexicographically smallest string.

Examples:

Input: S = "aba?ca?"
Output: "ababcab"
Explanation: first '?' was replaced by 'b' as 'a' and 'c' are adjacent to that , and last '?' can be replaced by 'b' and 'c' but 'b' comes first lexicographically.

Input: S = "ba?"
Output: "bac"
Explanation: '?' was replaced by 'c' as 'a' is adjacent and 'b' is the starting of the string and '?' is the ending of the string.

Approach: The basic way to solve the problem is as follows:

  • The approach is to iterate over the string S and whenever we encounter a '?' we will check the previous and next occurring char and replace the '?' accordingly.
  • First, we try to first replace it with 'a', then 'b', and then 'c' as follows
    • if adjacent char's are not 'a' then we can replace it with 'a'.
    • else if adjacent char's are not 'b' then we can replace it with 'b'.
    • else if adjacent char's are not 'c' then we can replace it with 'c'.

Below is the implementation of the above idea.


Output
ababcab

Time Complexity: O(N), where N is the length of the string.
Auxiliary Space: O(1).

Comment
Article Tags: