We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.

This is the solution that I eventually came up with and it still times out on test case 10. Interestingly, a simple for loop which prints out the characters of the strings also times out on that case and is about twice as long in execution on test case 9.
On my local machine, I get stack overflow way before the execution time problem.
Any suggestions?

Common source of long execution is the complexity of + operator (or append method) for strings. It's of Appending two strings, one of length N, other of M, is of complexity O(N+M). Here it's repeatitive addition, so it can be of quadratic complexity.

Sorry, I meant the onbe that you posted. Here is my version:
def Mingle(P:List[Char],Q:List[Char]):List[Char] = {
if(P.isEmpty)return List()
return P.head :: Q.head :: Mingle(P.tail,Q.tail)
}

def main(args: Array[String]) {
val P = readLine().toList
val Q = readLine().toList
println(Mingle(P,Q).mkString)
}

## String Mingling

You are viewing a single comment's thread. Return to all comments →

This is the solution that I eventually came up with and it still times out on test case 10. Interestingly, a simple for loop which prints out the characters of the strings also times out on that case and is about twice as long in execution on test case 9. On my local machine, I get stack overflow way before the execution time problem. Any suggestions?

Hi @blowkj, sorry can't find your solution.

Common source of long execution is the complexity of

`+`

operator (orappendmethod) for strings. It's of Appending two strings, one of lengthN, other ofM, is of complexity`O(N+M)`

. Here it's repeatitive addition, so it can be of quadratic complexity.Sorry, I meant the onbe that you posted. Here is my version: def Mingle(P:List[Char],Q:List[Char]):List[Char] = { if(P.isEmpty)return List() return P.head :: Q.head :: Mingle(P.tail,Q.tail) }

Note that I don't use the + operator. Thanks,

OK, got it now. Googling on tail recursion helped.