If we are given n strings and their lengths and an add(string s1,string s2) function which would concatenate the string s2 with s1 and return s3. How would we optimize the cost of concatenation of all these strings into one big string.
If such a function was not given we could simply create the output string of size (n1 + n2 + …nn) and keep appending to it characters of each string. But, with this function given we’d have to traverse input string s1 to find it’s end and then start concatenating string s2 to it.
so if lengths of strings are 2, 6, 1, 3, 4 ..
add (s1, s2) traversal for length 2, op string of length 8
add (s1, s3) traversal for length (2+6) op string of length 9
add (s1, s4) traversal for length (2+6+1) op string of length 12
add (s1, s5) traversal for length (2+6+1+3) op string of length 16...and so on..
You can concat the string character by character right when you traverse it. After you append a small string to the result string, you can get hold of the pointer which is pointing to the end of the result string. So while adding next small string, use that so that you wont have to traverse all way till that position again.