Skip to content
Advertisement

Using recursion to concatenate two strings

My goal is to concatenate two strings using recursion.

The input would be str1 = (“long string”) str2 = (“yes so long”)

and the output would be: ‘lyoensg ssto rlionngg’

Assumptions are that both strings are the same length.

My code as of now is:

JavaScript

Im sure Im no where close but I am struggling with making it loop.

I am not allowed to use loops but I can use if statements

Advertisement

Answer

JavaScript

Expected output:

JavaScript

Recursive solution

You need the base case which is when the array length is 0. In that case return an empty string. In all other cases return the first element of each string concatenated with the return value of the recursive call to concat_strings_rec(). Remember to decrease the array size for the recursive calls!

Iterative solution

The iterative solution just loops through the array concatenating each character within the two strings and putting the concatenated first, second, third,… character in an array. Then use "".join() to concatenate those two character strings in the array to a complete string.

Recommendation

Don’t use the recursive solution as it just consumes more memory due to the call stack and it will be slower and since Python has a limit on the number of calls on the call stack it will fail for larger strings.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement