The Wayback Machine - https://web.archive.org/web/20211222193534/https://www.geeksforgeeks.org/generate-string-after-adding-spaces-at-specific-positions-in-a-given-string/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Generate string after adding spaces at specific positions in a given String

  • Last Updated : 22 Dec, 2021

Given a string s and an array spaces[] describing the original string’s indices where spaces will be added. The task is to add spaces in given positions in spaces[] and print the string formed.

Examples:

Hey! Looking for some great resources suitable for young ones? You've come to the right place. Check out our self-paced courses designed for students of grades I-XII. 

Start with topics like Python, HTML, ML, and learn to make some games and apps all with the help of our expertly designed content! So students worry no more, because GeeksforGeeks School is now here!

 



Input: s = “GeeksForGeeK”, spaces = {1, 5, 10}
Output: “G eeks ForGe eK”
Explanation: The underlined characters in “GeeksForGeeK” relate to the indices 1, 5, and 10. After that, put spaces in front of those characters.

Input: s = “ilovegeeksforgeek”, spaces = {1, 5, 10, 13}
Output: “i love geeks for geek”

 

Approach: This problem is simple string implementation based. Follow the steps below to solve the given problem. Follow the steps below to solve the given problem.

  • Initialize with a space in the new string of size of the sum of the length of both arrays.
  • Visit the index and wherever the index is equal to the current space value in the space[] array skip it as space is already there.
  • Else keep assigning the value from the main string
  • Here addition of ‘l’ in line { if(l<N and i==sp[l]+l) } is very interesting to observe:
    • The values in the space array are basically according to the old input string.
    • But in the new string, these space values or indices are basically shifting by the number of spaces found before.
  • Print the string formed at the end.

Below is the implementation of the above approach

C++




// C++ program for above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to add space in required positions
string spaceintegration(string s, vector<int>& sp)
{
    int M = s.size(), N = sp.size(), l = 0, r = 0;
  
    string res(M + N, ' ');
  
    // Iterate over M+N length
    for (int i = 0; i < M + N; i++) {
  
        if (l < N and i == sp[l] + l)
            l++;
        else
            res[i] = s[r++];
    }
  
    // Return the requried string
    return res;
}
  
// Driver Code
int main()
{
  
    string s = "ilovegeeksforgeeks";
  
    vector<int> space = { 1, 5, 10, 13 };
  
    // Function Call
    cout << spaceintegration(s, space) << endl;
  
    return 0;
}
Output:
i love geeks for geeks

Time Complexity: O(M+N)
Auxiliary Space: O(M+N)




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!