VOOZH about

URL: https://www.geeksforgeeks.org/dsa/merge-two-strings-chunks-given-size/

⇱ Merge two strings in chunks of given size - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Merge two strings in chunks of given size

Last Updated : 17 Nov, 2022

Given two strings 'a' and 'b' and a number k, our aim is to merge the strings into a string s such that it contains groups of k characters from the strings alternately in the final string.

Examples: 

Input: a = "durability", 
 b = "essence
 k = 3
Output: duressabienclitey

Input: a = "determination"
 b = "stance"
 k = 3
Output: detstaermnceination


In the second example we chose groups of three characters from determination and stance alternately to make the string. But when the string stance was completely used then we added the remaining string of determination as it is.

The approach of this problem is to alternately add groups of characters of both the strings until one of the string is finished. Then we simply have to add the remaining portion of the leftover string to the answer as it is.  

Implementation:


Output
detstaermnceination

Time Complexity: O(|a|+|b|).
Auxiliary Space: O(|a|+|b|), where |a| and |b| are the length of string a and b respectively.

Comment
Article Tags:
Article Tags: