One of the most common operations on strings is appending or concatenation. Appending to the end of a string when the string is stored in the traditional manner (i.e. an array of characters) would take a minimum of O(n) time (where n is the length of the original string).
We can reduce time taken by append using Ropes Data Structure.
A Rope is a binary tree structure where each node except the leaf nodes, contains the number of characters present to the left of that node. Leaf nodes contain the actual string broken into substrings (size of these substrings can be decided by the user).
Consider the image below.
The image shows how the string is stored in memory. Each leaf node contains substrings of the original string and all other nodes contain the number of characters present to the left of that node. The idea behind storing the number of characters to the left is to minimise the cost of finding the character present at i-th position.
1. Ropes drastically cut down the cost of appending two strings.
2. Unlike arrays, ropes do not require large contiguous memory allocations.
3. Ropes do not require O(n) additional memory to perform operations like insertion/deletion/searching.
4. In case a user wants to undo the last concatenation made, he can do so in O(1) time by just removing the root node of the tree.
1. The complexity of source code increases.
2. Greater chances of bugs.
3. Extra memory required to store parent nodes.
4. Time to access i-th character increases.
Now let’s look at a situation that explains why Ropes are a good substitute to monolithic string arrays.
Given two strings a and b. Concatenate them in a third string c.
Input : a = "This is ", b = "an apple" Output : "This is an apple" Input : a = "This is ", b = "geeksforgeeks" Output : "This is geeksforgeeks"
Method 1 (Naive method)
We create a string c to store concatenated string. We first traverse a and copy all characters of a to c. Then we copy all characters of b to c.