Program to form smallest number where no two adjacent digits are same in Python


Suppose we have a string s with four possible characters "1", "2", "3" and "?". We can place any one of "1", "2" and "3", in the place of "?". We have to find the smallest possible number that we can make such that no two adjacent digits are same.

So, if the input is like s = "2??3?", then the output will be 21231

To solve this, we will follow these steps −

  • i := 0
  • s := a list of elements from s
  • if size of s < 2, then
    • if s[i] is same as "?", then
      • return "1"
  • while i < size of s, do
    • if s[i] is same as "?", then
      • if i is same as 0, then
        • s[i] := "1" when s[i + 1] is not "1" otherwise "2"
      • otherwise when i > 0 and i <= size of s - 2, then
        • if s[i - 1] is same as "1", then
          • if s[i + 1] is same as "2", then
            • s[i] := "3"
          • otherwise,
            • s[i] := "2"
        • otherwise when s[i - 1] is same as "2", then
          • if s[i + 1] is same as "2", then
            • s[i] := "3"
          • otherwise,
            • s[i] := "1"
        • otherwise when s[i - 1] is same as "3", then
          • if s[i + 1] is same as "2", then
            • s[i] := "2"
          • otherwise,
            • s[i] := "1"
      • otherwise,
        • s[i] := "1" when s[i - 1] is not "1" otherwise "2"
    • i := i + 1
  • join items of s into a string and return

Example

Let us see the following implementation to get better understanding −

def solve(s):
   i = 0
   s = list(s)
   if len(s) < 2:
      if s[i] == "?":
         return "1"
   while i < len(s):
      if s[i] == "?":
         if i == 0:
            s[i] = "1" if s[i + 1] != "1" else "2"
         elif i > 0 and i <= len(s) - 2:
            if s[i - 1] == "1":
               if s[i + 1] == "2":
                  s[i] = "3"
               else:
                  s[i] = "2"
            elif s[i - 1] == "2":
               if s[i + 1] == "1":
                  s[i] = "3"
               else:
                  s[i] = "1"
            elif s[i - 1] == "3":
               if s[i + 1] == "1":
                  s[i] = "2"
               else:
                  s[i] = "1"
         else:
            s[i] = "1" if s[i - 1] != "1" else "2"
      i += 1
   return "".join(s)

s = "2??3?"
print(solve(s))

Input

"2??3?"

Output

21231

Updated on: 14-Oct-2021

252 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements