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
  • if s[i] is same as "?", then
    • return "1"
  • while i
  • 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
    • 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)  0 and i 

    Input

    "2??3?"
    

    Output

    21231
    Updated on: 2021-10-14T10:02:35+05:30

    418 Views

    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements