Skip to main content

Codility National Coding Week Sep-2021 : String transformation solution in Swift

In this post Swift 5.0 solution given for National Coding Week Sep-2021 challenge. Given a string S of letters 'a' and/or 'b', replaces some consecutive sequence "abb" in S by "baa".

Example,  S = "ababb" then  "ababb" → "abbaa" → "baaaa".

Working solution :



    public func solution(_ S : inout String) -> String {


      var hasFound = true

      var res = Array(S)

      // 1

      while hasFound && res.count > 2 {

        hasFound = false

        //2

        for index in 0..<res.count-2 {

          // 3

          if res[index] == "a" && res[index+1] == "b" && res[index+2] == "b" {

            hasFound = true

            res[index] = "b"

            res[index+1] = "a"

            res[index+2] = "a"

            break;

          }

        }

      }

      

      return String(res)

    }


    print(solution("ababb")) // prints "baaaa"



  1. Repeat step 2 until all the transformations completed. Also guard condition for minimum 3 characters.
  2. Compare every character & it's next 2 positions with 'a', 'b', 'b' respectively.
  3. If matched, replace the characters with 'b', 'a', 'a'. 

Read complete challenge description from  https://app.codility.com/programmers/challenges/national_coding_week_2021/

Thanks for reading till end. Please comment if you find useful or better solutions.

Popular posts from this blog