The Wayback Machine - https://web.archive.org/web/20240910224834/https://www.geeksforgeeks.org/ropes-data-structure-fast-string-concatenation/
Open In App

Ropes Data Structure (Fast String Concatenation)

Last Updated : 17 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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. 
 

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.
 

Vector_Rope_example.svg

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.
Advantages 
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.
Disadvantages 
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[].
Examples: 
 

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[]. 
Implementation: 

C++




// Simple C++ program to concatenate two strings
#include <iostream>
using namespace std;
 
// Function that concatenates strings a[0..n1-1]
// and b[0..n2-1] and stores the result in c[]
void concatenate(char a[], char b[], char c[],
                              int n1, int n2)
{
    // Copy characters of A[] to C[]
    int i;
    for (i=0; i<n1; i++)
        c[i] = a[i];
 
    // Copy characters of B[]
    for (int j=0; j<n2; j++)
        c[i++] = b[j];
 
    c[i] = '\0';
}
 
 
// Driver code
int main()
{
    char a[] =  "Hi This is geeksforgeeks. ";
    int n1 = sizeof(a)/sizeof(a[0]);
 
    char b[] =  "You are welcome here.";
    int n2 = sizeof(b)/sizeof(b[0]);
 
    // Concatenate a[] and b[] and store result
    // in c[]
    char c[n1 + n2 - 1];
    concatenate(a, b, c, n1, n2);
    for (int i=0; i<n1+n2-1; i++)
        cout << c[i];
 
    return 0;
}


Java




//Java program to concatenate two strings
 
class GFG {
 
    // Function that concatenates strings a[0..n1-1]
    // and b[0..n2-1] and stores the result in c[]
    static void concatenate(char a[], char b[], char c[],
            int n1, int n2) {
        // Copy characters of A[] to C[]
        int i;
        for (i = 0; i < n1; i++) {
            c[i] = a[i];
        }
 
        // Copy characters of B[]
        for (int j = 0; j < n2; j++) {
            c[i++] = b[j];
        }
 
    }
 
    // Driver code
    public static void main(String[] args) {
        char a[] = "Hi This is geeksforgeeks. ".toCharArray();
        int n1 = a.length;
 
        char b[] = "You are welcome here.".toCharArray();
        int n2 = b.length;
 
        // Concatenate a[] and b[] and store result
        // in c[]
        char c[] = new char[n1 + n2];
        concatenate(a, b, c, n1, n2);
        for (int i = 0; i < n1 + n2 - 1; i++) {
            System.out.print(c[i]);
        }
 
    }
}
// This code is contributed by PrinciRaj1992


Python3




# Python3 program to concatenate two strings
 
# Function that concatenates strings a[0..n1-1]
# and b[0..n2-1] and stores the result in c[]
def concatenate(a, b, c, n1, n2):
 
    # Copy characters of A[] to C[]
    i = -1
    for i in range(n1):
        c[i] = a[i]
 
    # Copy characters of B[]
    for j in range(n2):
        c[i] = b[j]
        i += 1
 
# Driver Code
if __name__ == "__main__":
    a = "Hi This is geeksforgeeks. "
    n1 = len(a)
 
    b = "You are welcome here."
    n2 = len(b)
 
    a = list(a)
    b = list(b)
 
    # Concatenate a[] and b[] and
    # store result in c[]
    c = [0] * (n1 + n2 - 1)
 
    concatenate(a, b, c, n1, n2)
 
    for i in c:
        print(i, end = "")
 
# This code is contributed by
# sanjeev2552


C#




// C# program to concatenate two strings
using System;
 
public class GFG {
  
    // Function that concatenates strings a[0..n1-1]
    // and b[0..n2-1] and stores the result in c[]
    static void concatenate(char []a, char []b, char []c,
            int n1, int n2) {
        // Copy characters of A[] to C[]
        int i;
        for (i = 0; i < n1; i++) {
            c[i] = a[i];
        }
  
        // Copy characters of B[]
        for (int j = 0; j < n2; j++) {
            c[i++] = b[j];
        }
  
    }
  
    // Driver code
    public static void Main() {
        char []a = "Hi This is geeksforgeeks. ".ToCharArray();
        int n1 = a.Length;
  
        char []b = "You are welcome here.".ToCharArray();
        int n2 = b.Length;
  
        // Concatenate a[] and b[] and store result
        // in c[]
        char []c = new char[n1 + n2];
        concatenate(a, b, c, n1, n2);
        for (int i = 0; i < n1 + n2 - 1; i++) {
            Console.Write(c[i]);
        }
  
    }
}
/*This code is contributed by PrinciRaj1992*/


Javascript




// Function that concatenates strings a[0..n1-1]
// and b[0..n2-1] and stores the result in c[]
function concatenate(a, b, c, n1, n2) {
    // Copy characters of A[] to C[]
    let i;
    for (i=0; i<n1; i++)
        c[i] = a[i];
 
    // Copy characters of B[]
    for (let j=0; j<n2; j++)
        c[i++] = b[j];
 
    c[i] = '\0';
}
 
 
// Driver code
function main() {
    let a =  "Hi This is geeksforgeeks. ";
    let n1 = a.length;
 
    let b =  "You are welcome here.";
    let n2 = b.length;
 
    // Concatenate a[] and b[] and store result
    // in c[]
    let c = Array(n1 + n2 - 1);
    concatenate(a, b, c, n1, n2);
    for (let i=0; i<n1+n2-1; i++)
        console.log(c[i]);
 
    return 0;
}
main();


Output: 
 

Hi This is geeksforgeeks. You are welcome here

Time complexity : O(max(n1, n2))
Auxiliary Space: O(n1 + n2)
 

Now let’s try to solve the same problem using Ropes.
 

Method 2 (Rope structure method)

This rope structure can be utilized to concatenate two strings in constant time. 
1. Create a new root node (that stores the root of the new concatenated string) 
2. Mark the left child of this node, the root of the string that appears first. 
3. Mark the right child of this node, the root of the string that appears second.
And that’s it. Since this method only requires to make a new node, it’s complexity is O(1).
Consider the image below (Image source : https://en.wikipedia.org/wiki/Rope_(data_structure))
 

Vector_Rope_concat.svg

 Implementation:

CPP




// C++ program to concatenate two strings using
// rope data structure.
#include <bits/stdc++.h>
using namespace std;
 
// Maximum no. of characters to be put in leaf nodes
const int LEAF_LEN = 2;
 
// Rope structure
class Rope
{
public:
    Rope *left, *right, *parent;
    char *str;
    int lCount;
};
 
// Function that creates a Rope structure.
// node --> Reference to pointer of current root node
//   l  --> Left index of current substring (initially 0)
//   r  --> Right index of current substring (initially n-1)
//   par --> Parent of current node (Initially NULL)
void createRopeStructure(Rope *&node;, Rope *par,
                         char a[], int l, int r)
{
    Rope *tmp = new Rope();
    tmp->left = tmp->right = NULL;
  
    // We put half nodes in left subtree
    tmp->parent = par;
  
    // If string length is more
    if ((r-l) > LEAF_LEN)
    {
        tmp->str = NULL;
        tmp->lCount = (r-l)/2;
        node = tmp;
        int m = (l + r)/2;
        createRopeStructure(node->left, node, a, l, m);
        createRopeStructure(node->right, node, a, m+1, r);
    }
    else
    {
        node = tmp;
        tmp->lCount = (r-l);
        int j = 0;
        tmp->str = new char[LEAF_LEN];
        for (int i=l; i<=r; i++)
            tmp->str[j++] = a[i];
    }
}
 
// Function that prints the string (leaf nodes)
void printstring(Rope *r)
{
    if (r==NULL)
        return;
    if (r->left==NULL && r->right==NULL)
        cout << r->str;
    printstring(r->left);
    printstring(r->right);
}
 
// Function that efficiently concatenates two strings
// with roots root1 and root2 respectively. n1 is size of
// string represented by root1.
// root3 is going to store root of concatenated Rope.
void concatenate(Rope *&root3;, Rope *root1, Rope *root2, int n1)
{
    // Create a new Rope node, and make root1
    // and root2 as children of tmp.
    Rope *tmp = new Rope();
    tmp->parent = NULL;
    tmp->left = root1;
    tmp->right = root2;
    root1->parent = root2->parent = tmp;
    tmp->lCount = n1;
 
    // Make string of tmp empty and update
    // reference r
    tmp->str = NULL;
    root3 = tmp;
}
 
// Driver code
int main()
{
    // Create a Rope tree for first string
    Rope *root1 = NULL;
    char a[] =  "Hi This is geeksforgeeks. ";
    int n1 = sizeof(a)/sizeof(a[0]);
    createRopeStructure(root1, NULL, a, 0, n1-1);
 
    // Create a Rope tree for second string
    Rope *root2 = NULL;
    char b[] =  "You are welcome here.";
    int n2 = sizeof(b)/sizeof(b[0]);
    createRopeStructure(root2, NULL, b, 0, n2-1);
 
    // Concatenate the two strings in root3.
    Rope *root3 = NULL;
    concatenate(root3, root1, root2, n1);
 
    // Print the new concatenated string
    printstring(root3);
    cout << endl;
    return 0;
}


Java




import java.util.ArrayList;
// Rope structure
class Rope {
    Rope left;
    Rope right;
    Rope parent;
    ArrayList<Character> str;
    int lCount;
 
    Rope()
    {
        this.left = null;
        this.right = null;
        this.parent = null;
        this.str = new ArrayList<Character>();
        this.lCount = 0;
    }
}
 
class Main {
    // Maximum no. of characters to be put in leaf nodes
    static final int LEAF_LEN = 2;
    // Function that creates a Rope structure.
    // node --> Reference to pointer of current root node
    //   l  --> Left index of current substring (initially
    //   0) r  --> Right index of current substring
    //   (initially n-1) par --> Parent of current node
    //   (Initially NULL)
    static Rope createRopeStructure(Rope node, Rope par,
                                    String a, int l, int r)
    {
        Rope tmp = new Rope();
        tmp.left = tmp.right = null;
        // We put half nodes in left subtree
        tmp.parent = par;
 
        if ((r - l) > LEAF_LEN) {
            tmp.str = null;
            tmp.lCount = (int)Math.floor((r - l) / 2);
            node = tmp;
            int m = (int)Math.floor((l + r) / 2);
            node.left = createRopeStructure(node.left, node,
                                            a, l, m);
            node.right = createRopeStructure(
                node.right, node, a, m + 1, r);
        }
        else {
            node = tmp;
            tmp.lCount = (r - l);
            int j = 0;
            for (int i = l; i <= r; i++) {
                tmp.str.add(a.charAt(i));
            }
        }
 
        return node;
    }
    // Function that prints the string (leaf nodes)
    static void printstring(Rope r)
    {
        if (r == null) {
            return;
        }
        if (r.left == null && r.right == null) {
            for (char c : r.str) {
                System.out.print(c);
            }
        }
        printstring(r.left);
        printstring(r.right);
    }
    // Function that efficiently concatenates two strings
    // with roots root1 and root2 respectively. n1 is size
    // of string represented by root1. root3 is going to
    // store root of concatenated Rope.
    static Rope concatenate(Rope root3, Rope root1,
                            Rope root2, int n1)
    {
        // Create a new Rope node, and make root1
        // and root2 as children of tmp.
        Rope tmp = new Rope();
        tmp.left = root1;
        tmp.right = root2;
        root1.parent = tmp;
        root2.parent = tmp;
        tmp.lCount = n1;
        // Make string of tmp empty and update
        // reference r
        tmp.str = null;
        root3 = tmp;
 
        return root3;
    }
    // Driver code
    public static void main(String[] args)
    {
        // Create a Rope tree for first string
        Rope root1 = null;
        String a = "Hi This is geeksforgeeks. ";
        int n1 = a.length();
        root1 = createRopeStructure(root1, null, a, 0,
                                    n1 - 1);
        // Create a Rope tree for second string
        Rope root2 = null;
        String b = "You are welcome here.";
        int n2 = b.length();
        root2 = createRopeStructure(root2, null, b, 0,
                                    n2 - 1);
 
        // Concatenate the two strings in root3.
        Rope root3 = null;
        root3 = concatenate(root3, root1, root2, n1);
        // Print the new concatenated string
        printstring(root3);
    }
}


Python3




# Python program to concatenate two strings using
# rope data structure.
 
# Maximum no. of characters to be put in leaf nodes
LEAF_LEN = 2
 
# Rope structure
class Rope:
 
    def __init__(self):
        self.left = None
        self.right = None
        self.parent = None
        self.str = [0]*(LEAF_LEN + 1)
        self.lCount = 0
 
# Function that creates a Rope structure.
# node --> Reference to pointer of current root node
# l  --> Left index of current substring (initially 0)
# r  --> Right index of current substring (initially n-1)
# par --> Parent of current node (Initially NULL)
def createRopeStructure(node, par, a, l, r):
 
    tmp = Rope()
    tmp.left = tmp.right = None
  
    # We put half nodes in left subtree
    tmp.parent = par
  
    # If string length is more
    if (r-l) > LEAF_LEN:
 
        tmp.str = None
        tmp.lCount = (r-l) // 2
        node = tmp
        m = (l + r) // 2
        createRopeStructure(node.left, node, a, l, m)
        createRopeStructure(node.right, node, a, m+1, r)
    else:
         
        node = tmp
        tmp.lCount = (r-l)
        j = 0
        for i in range(l, r+1):
            print(a[i],end = "")
            tmp.str[j] = a[i]
            j = j + 1
        print(end = "")
     
    return node
 
# Function that prints the string (leaf nodes)
def printstring(r):
 
    if r==None:
        return
     
    if r.left==None and r.right==None:
        # console.log(r.str);  
        pass
 
    printstring(r.left)
    printstring(r.right)
 
# Function that efficiently concatenates two strings
# with roots root1 and root2 respectively. n1 is size of
# string represented by root1.
# root3 is going to store root of concatenated Rope.
def concatenate(root3, root1, root2, n1):
     
    # Create a new Rope node, and make root1
    # and root2 as children of tmp.
    tmp = Rope()
    tmp.left = root1
    tmp.right = root2
    root1.parent = tmp
    root2.parent = tmp
    tmp.lCount = n1
 
    # Make string of tmp empty and update
    # reference r
    tmp.str = None
    root3 = tmp
     
    return root3
 
# Driver code
# Create a Rope tree for first string
root1 = None
a =  "Hi This is geeksforgeeks. "
n1 = len(a)
root1 = createRopeStructure(root1, None, a, 0, n1-1)
 
# Create a Rope tree for second string
root2 = None
b =  "You are welcome here."
n2 = len(b)
root2 = createRopeStructure(root2, None, b, 0, n2-1)
 
# Concatenate the two strings in root3.
root3 = None
root3 = concatenate(root3, root1, root2, n1)
 
# Print the new concatenated string
printstring(root3)
print()
 
# The code is contributed by Nidhi goel.


Javascript




// javascript program to concatenate two strings using
// rope data structure.
 
// Maximum no. of characters to be put in leaf nodes
const LEAF_LEN = 2;
 
// Rope structure
class Rope
{
    constructor(){
        this.left = null;
        this.right = null;
        this.parent = null;
        this.str = new Array();
        this.lCount = 0;
    }
}
 
// Function that creates a Rope structure.
// node --> Reference to pointer of current root node
//   l  --> Left index of current substring (initially 0)
//   r  --> Right index of current substring (initially n-1)
//   par --> Parent of current node (Initially NULL)
function createRopeStructure(node, par, a, l, r)
{
    let tmp = new Rope();
    tmp.left = tmp.right = null;
  
    // We put half nodes in left subtree
    tmp.parent = par;
  
    // If string length is more
    if ((r-l) > LEAF_LEN)
    {
        tmp.str = null;
        tmp.lCount = Math.floor((r-l)/2);
        node = tmp;
        let m = Math.floor((l + r)/2);
        createRopeStructure(node.left, node, a, l, m);
        createRopeStructure(node.right, node, a, m+1, r);
    }
    else
    {
        node = tmp;
        tmp.lCount = (r-l);
        let j = 0;
        // tmp.str = new Array(LEAF_LEN);
        for (let i=l; i<=r; i++){
            document.write(a[i]);
            tmp.str[j++] = a[i];
        }
        document.write("\n");
    }
     
    return node;
}
 
// Function that prints the string (leaf nodes)
function printstring(r)
{
    if (r==null)
        return;
    if (r.left==null && r.right==null){
        // console.log(r.str);       
    }
 
    printstring(r.left);
    printstring(r.right);
}
 
// Function that efficiently concatenates two strings
// with roots root1 and root2 respectively. n1 is size of
// string represented by root1.
// root3 is going to store root of concatenated Rope.
function concatenate(root3, root1, root2, n1)
{
    // Create a new Rope node, and make root1
    // and root2 as children of tmp.
    let tmp = new Rope();
    tmp.left = root1;
    tmp.right = root2;
    root1.parent = tmp;
    root2.parent = tmp;
    tmp.lCount = n1;
 
    // Make string of tmp empty and update
    // reference r
    tmp.str = null;
    root3 = tmp;
     
    return root3;
}
 
// Driver code
// Create a Rope tree for first string
let root1 = null;
let a =  "Hi This is geeksforgeeks. ";
let n1 = a.length;
root1 = createRopeStructure(root1, null, a, 0, n1-1);
 
// Create a Rope tree for second string
let root2 = null;
let b =  "You are welcome here.";
let n2 = b.length;
root2 = createRopeStructure(root2, null, b, 0, n2-1);
 
// Concatenate the two strings in root3.
let root3 = null;
root3 = concatenate(root3, root1, root2, n1);
 
// Print the new concatenated string
printstring(root3);
console.log();
 
// The code is contributed by Nidhi goel.


C#




using System;
using System.Collections.Generic;
 
// Rope structure
class Rope
{
    public Rope left;
    public Rope right;
    public Rope parent;
    public List<char> str;
    public int lCount;
 
    public Rope()
    {
        this.left = null;
        this.right = null;
        this.parent = null;
        this.str = new List<char>();
        this.lCount = 0;
    }
}
 
class MainClass
{
    // Maximum no. of characters to be put in leaf nodes
    static readonly int LEAF_LEN = 2;
 
    // Function that creates a Rope structure.
    // node --> Reference to pointer of current root node
    //   l  --> Left index of current substring (initially
    //   0) r  --> Right index of current substring
    //   (initially n-1) par --> Parent of current node
    //   (Initially NULL)
    static Rope CreateRopeStructure(ref Rope node, Rope par, string a, int l, int r)
    {
        Rope tmp = new Rope();
        tmp.left = tmp.right = null;
        // We put half nodes in left subtree
        tmp.parent = par;
 
        if ((r - l) > LEAF_LEN)
        {
            tmp.str = null;
            tmp.lCount = (int)Math.Floor((r - l) / 2.0);
            node = tmp;
            int m = (int)Math.Floor((l + r) / 2.0);
            node.left = CreateRopeStructure(ref node.left, node, a, l, m);
            node.right = CreateRopeStructure(ref node.right, node, a, m + 1, r);
        }
        else
        {
            node = tmp;
            tmp.lCount = (r - l);
            for (int i = l; i <= r; i++)
            {
                tmp.str.Add(a[i]);
            }
        }
 
        return node;
    }
 
    // Function that prints the string (leaf nodes)
    static void PrintString(Rope r)
    {
        if (r == null)
        {
            return;
        }
        if (r.left == null && r.right == null)
        {
            foreach (char c in r.str)
            {
                Console.Write(c);
            }
        }
        PrintString(r.left);
        PrintString(r.right);
    }
 
    // Function that efficiently concatenates two strings
    // with roots root1 and root2 respectively. n1 is size
    // of string represented by root1. root3 is going to
    // store root of concatenated Rope.
    static Rope Concatenate(Rope root3, Rope root1, Rope root2, int n1)
    {
        // Create a new Rope node, and make root1
        // and root2 as children of tmp.
        Rope tmp = new Rope();
        tmp.left = root1;
        tmp.right = root2;
        root1.parent = tmp;
        root2.parent = tmp;
        tmp.lCount = n1;
        // Make string of tmp empty and update
        // reference r
        tmp.str = null;
        root3 = tmp;
 
        return root3;
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        // Create a Rope tree for first string
        Rope root1 = null;
        string a = "Hi This is geeksforgeeks. ";
        int n1 = a.Length;
        root1 = CreateRopeStructure(ref root1, null, a, 0, n1 - 1);
        // Create a Rope tree for second string
        Rope root2 = null;
        String b = "You are welcome here.";
        int n2 = b.Length;
        root2 = CreateRopeStructure(ref root2, null, b, 0,
                                    n2 - 1);
         // Concatenate the two strings in root3.
        Rope root3 = null;
        root3 = Concatenate(root3, root1, root2, n1);
        // Print the new concatenated string
        PrintString(root3);
         
    }
}


Output: 
 

Hi This is geeksforgeeks. You are welcome here.

Time Complexity: O(1) 
Auxiliary Space: O(1)

 



Similar Reads

Maximum length of all possible K equal length ropes generated by cutting N ropes
Given an array arr[] consisting of N positive integers representing the lengths of N ropes and a positive integer K, the task is to find the maximum length of the rope that has a frequency of at least K by cutting any ropes in any number of pieces. Examples: Input: arr[] = {5, 2, 7, 4, 9}, K = 5Output: 4Explanation:Below are the possible cutting of
8 min read
Maximize ropes of consecutive length possible by connecting given ropes
Given an array A[ ] of size N where each array element represents the length of a rope, the task is to find the number of ropes of consecutive length that can be created by connecting given ropes starting from length 1. Examples : Input: N = 5, A[ ] = {1, 2, 7, 1, 1} Output: 5 Explanation: Length | Ropes 1 | [1] 2 | [1, 1] 3 | [1, 2] 4 | [1, 2, 1]
6 min read
N consecutive ropes problem
Given N ropes, each rope has a length associated with it. At a time, only two consecutive small ropes tied at end form a large rope and cost of forming sum of their length. Find the minimum cost when all ropes are tied to form a single rope. Examples: Input: arr[] = {7, 6, 8, 6, 1, 1} Output: 68 {7, 6, 8, 6, 1, 1} - {7, 6, 8, 6, 2}, cost = 2 {7, 6,
9 min read
Number of ways to use all the K ropes
Given two walls A, B with M, and N hooks respectively. You are also given K ropes. By using one rope you can connect one hook on wall A with another hook on wall B. One hook can connect with only one rope. Find the number of different ways you can use all the K ropes.Two ways that use the exact same set of hooks from wall A and wall B are considere
7 min read
Ropes left after every removal of smallest
Given an array of an integer of size, N. Array contains N ropes of length Ropes[i]. You have to perform a cut operation on ropes such that all of them are reduced by the length of the smallest rope. Display the number of ropes left after every cut. Perform operations till the length of each rope becomes zero. Note: IF no ropes left after a single o
8 min read
Connect n ropes with minimum cost
Given are N ropes of different lengths, the task is to connect these ropes into one rope with minimum cost, such that the cost to connect two ropes is equal to the sum of their lengths. Examples: Input: arr[] = {4,3,2,6} , N = 4Output: 29Explanation:  First, connect ropes of lengths 2 and 3. Now we have three ropes of lengths 4, 6, and 5. Now conne
6 min read
Static Data Structure vs Dynamic Data Structure
Data structure is a way of storing and organizing data efficiently such that the required operations on them can be performed be efficient with respect to time as well as memory. Simply, Data Structure are used to reduce complexity (mostly the time complexity) of the code. Data structures can be two types : 1. Static Data Structure 2. Dynamic Data
4 min read
Longest palindromic string formed by concatenation of prefix and suffix of a string
Given string str, the task is to find the longest palindromic substring formed by the concatenation of the prefix and suffix of the given string str. Examples: Input: str = "rombobinnimor" Output: rominnimor Explanation: The concatenation of string "rombob"(prefix) and "mor"(suffix) is "rombobmor" which is a palindromic string. The concatenation of
11 min read
Minimum characters to be replaced to make a string concatenation of a K-length palindromic string
Given a string S of size N and a positive integer K ( where N % K = 0), the task is to find the minimum number of characters required to be replaced such that the string is K-periodic and the K-length periodic string must be a palindrome. Examples: Input: S = "abaaba", K = 3Output: 0Explanation: The given string is already K-periodic and the period
11 min read
Divide given numeric string into at most two increasing subsequences which form an increasing string upon concatenation
Given a string S consisting of N digits, the task is to partition the string into at most two increasing subsequences such that concatenation of them also forms an increasing string. If it is not possible to do so, then print "-1". Examples: Input: S = “040425524644”Output: 0022444 44556Explanation:One of the possible way to partition the given str
10 min read
Count subsequences 01 in string generated by concatenation of given numeric string K times
Given a string S and a positive integer K, the task is to find the number of subsequences "01" in the string generated by concatenation of the given numeric string S K times. Examples: Input: S = "0171", K = 2Output: 6Explanation:The string formed by concatenation of S, K number of times is "01710171". There are total 6 possible subsequences which
6 min read
Number of pairs of String whose concatenation leads to a Sorted string
Given an array of strings S with the size of N where each string contains at least two distinct characters. The task is to find the number of pairs of strings ( s[i], s[j] ) whose concatenation forms a string that is alphabetically sorted. Here concatenation is simply the process of appending one string after another. Examples: Input: S[] = {"aax",
9 min read
Check if given string is a substring of string formed by repeated concatenation of z to a
Given a string str, the task is to check if string str is a substring of an infinite length string S in which lowercase alphabets are concatenated in reverse order as: S = "zyxwvutsrqponmlkjihgfedcbazyxwvutsrqponmlkjihgfedcba...." Examples: Input: str = "cbaz"Output: YES Explanation:Given string "cbaz" is a valid sub string of S. Input: str = "ywxt
10 min read
Check if a string is concatenation of another given string
Given two strings str1 and str2 of length N and M respectively, the task is to check if the string str1 can be formed by concatenating the string str2 repetitively or not. Examples: Input: str1 = “abcabcabc”, str2 = “abc”Output: YesExplanation: Concatenating the string str2 thrice generates the string (“abc” + “abc” + “abc” = ) “abcabcabc”.Therefor
7 min read
Minimum flips required to convert given string into concatenation of equal substrings of length K
Given a binary string S and an integer K, the task is to find the minimum number of flips required to convert the given string into a concatenation of K-length equal sub-strings. It is given that the given string can be split into K-length substrings. Examples: Input: S = "101100101", K = 3 Output: 1 Explanation: Flip the '0' from index 5 to '1'. T
5 min read
Count of pairs of strings whose concatenation forms a palindromic string
Given an array A[ ] consisting of N strings, the task is to count the number of pairs of possible strings that on merging forms a Palindromic String or can be rearranged to form a Palindromic String. Example : Input: N = 6, A[ ] = {aab, abcac, dffe, ed, aa, aade}Output: 6Explanation: All possible pairs of strings which generates a palindromic strin
9 min read
Rearrange characters of a string to make it a concatenation of palindromic substrings
Given a string S consisting of lowercase alphabets, the task is to check whether the given string can be rearranged such that the string can be split into non-overlapping palindromic substrings of at least length 2. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: S = "aaaabbcdd"Output: YesExplanation: Rearrange the gi
6 min read
Check if 2 * K + 1 non-empty strings exists whose concatenation forms the given string
Given a string S consisting of N characters and positive integer K, the task is to check if there exist any (K + 1) strings i.e., A1, A2, A3, ..., AK, A(K + 1) such that the concatenation of strings A1, A2, A3, ..., AK, and A(K + 1) and the concatenation of the reverse of each strings AK, A(K - 1), A(K - 2), ..., A1, and A0 is the string S. If foun
6 min read
Maximum length of string formed by concatenation having even frequency of each character
Given N strings, print the maximum length of the string and the string formed by concatenating any of the N strings, such that every letter in the string occurs even number of times Example: Input: N = 5, str = ["ABAB", "ABF", "CDA", "AD", "CCC"]Output: ABABCDAADCCC 12Explanation: The string formed by concatenation is ABABCDAADCCC. Each letter in t
7 min read
Longest palindromic String formed using concatenation of given strings in any order
Given an array of strings arr[] of the same length, the task is to find the longest palindromic string that can be made using the concatenation of strings in any order. Examples: Input: arr[] = {"aba", "aba"} Output: abaaba Input: arr[] = {"abc", "dba", "kop", "cba", "abd"} Output: abcdbaabdcba Approach: Find all the pairs of strings which are reve
15+ min read
Minimum removals to make a string concatenation of a substring of 0s followed by a substring of 1s
Given binary string str of length N​​​​, the task is to find the minimum number of characters required to be deleted from the given binary string to make a substring of 0s followed by a substring of 1s. Examples: Input: str = "00101101"Output: 2Explanation: Removing str[2] and str[6] or removing str[3] and str[6] modifies the given binary string to
11 min read
Concatenation of Zig-Zag String in N Rows
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: PAHNAPLSIIGYIR. Therefore, for given string str and an integer N, the task is to print the string formed by concatenating
6 min read
Print Concatenation of Zig-Zag String in 'n' Rows
Given a string and number of rows 'n'. Print the string formed by concatenating n rows when input string is written in row-wise Zig-Zag fashion. Examples: Input: str = "ABCDEFGH" n = 2 Output: "ACEGBDFH" Explanation: Let us write input string in Zig-Zag fashion in 2 rows. A C E G B D F H Now concatenate the two rows and ignore spaces in every row.
12 min read
Minimize cost to convert given string into concatenation of equal substrings of length K
Given a string S of length N consisting of lowercase letters and an integer K, where N % K = 0, the task is to find the minimum cost to convert the given string into a concatenated string of the same K-length substrings by performing the following operations: A character can be replaced with another character.The cost of each operation is the absol
8 min read
Lexicographical concatenation of all substrings of a string
Given a string, find the concatenation of all substrings in lexicographic order. Examples: Input : s = "abc"Output : aababcbbccThe substrings of s in lexicographic order are "a", "b", "c", "ab", "abc", "bc". Concatenation of substrings is "a"+"ab"+"abc"+"b"+"bc"+"c" = "aababcbbcc".Input : s = "cba"Output : abbaccbcba Find all the substrings of stri
8 min read
Fast Fourier Transformation for polynomial multiplication
Given two polynomial A(x) and B(x), find the product C(x) = A(x)*B(x). There is already an O([Tex]n^2 [/Tex]) naive approach to solve this problem. here. This approach uses the coefficient form of the polynomial to calculate the product.A coefficient representation of a polynomial [Tex]A(x)=\sum_{j=0}^{n-1}a_jx^j [/Tex]is a = a0, a1, ..., an-1. Exa
13 min read
Iterative Fast Fourier Transformation for polynomial multiplication
Given two polynomials, A(x) and B(x), find the product C(x) = A(x)*B(x). In the previous post, we discussed the recursive approach to solve this problem which has O(nlogn) complexity. Examples: Input : A[] = {9, -10, 7, 6} B[] = {-5, 4, 0, -2} Output : C(x) = [Tex]-12x^6 -14x^5 +44x^4 -20x^3 - 75x^2 +86x -45[/Tex] In real-life applications such as
12 min read
Fast I/O for Competitive Programming in Python
In Competitive Programming, it is important to read input as fast as possible to save valuable time. Input/Output in Python can be sometimes time taking in cases when the input is huge or to output any numbers of lines or a huge number of arrays(lists) line after line. Fast Input Normally, the input is taken from STDIN in the form of String using i
3 min read
Java Competitive Programming Setup in VS Code with Fast I/O and Snippets
Though C++ is the dominating language in the competitive programming universe, there is a fair share of users who still continue to use Java as it has been there seen in the development arena and at the same time can be used competitive programming being fast as it can be toggled to and from where python being slowest among dynamic is hardly seen i
8 min read
Setting up Sublime Text For Competitive Programming (C++) Using Fast Olympic Coding Plugin
Competitive Programming is a mind sport where time matters the most. For that, a fast and easy-to-use tool is required for writing code. Sublime text along with the CppFastOlympicCoding plugin provides the same. Sublime text is popular for its fast performance and aesthetic UI. The CppFastOlympicCoding plugin offers features such as: TestManager: W
4 min read