How to insert characters in a string at a certain position?
Given a string str and an array of indices chars[] that describes the indices in the original string where the characters will be added. For this post, let the character to be inserted in star (*). Each star should be inserted before the character at the given index. Return the modified string after the stars have been added.
Examples:
Input: str = "geeksforgeeks", chars = [1, 5, 7, 9]
Output: g*eeks*fo*rg*eeks
Explanation: The indices 1, 5, 7, and 9 correspond to the bold characters in "geeksforgeeks".Input: str = "spacing", chars = [0, 1, 2, 3, 4, 5, 6]
Output: "*s*p*a*c*i*n*g"
Approach - Linear Traversal with Index Tracking
Iterate over the string and keep track of the count of the characters in the string so far and whenever your count becomes equal to the element in the array of stars, append a star to the resultant string and move ahead in your star array.
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
// Function to add stars
string addStars(string s, vector<int>& stars)
{
// Create a string ans for storing
// resultant string
string ans = "";
int j = 0;
for (int i = 0; i < s.length(); i++) {
// If the count of characters
// become equal to the stars[j],
// append star
if (j < stars.size() && i == stars[j]) {
ans += '*';
j++;
}
ans += s[i];
}
return ans;
}
// Driver code
int main()
{
string str = "geeksforgeeks";
vector<int> chars = { 1, 5, 7, 9 };
string ans = addStars(str, chars);
// Printing the resultant string
cout << ans << endl;
}
// Java code to implement the approach
import java.io.*;
class GFG
{
// Function to add stars
public static String addStars(String s, int stars[])
{
// Create a string ans for storing
// resultant string
String ans = "";
int j = 0;
for (int i = 0; i < s.length(); i++) {
// If the count of characters
// become equal to the stars[j],
// append star
if (j < stars.length && i == stars[j]) {
ans += '*';
j++;
}
ans += s.charAt(i);
}
return ans;
}
// Driver Code
public static void main(String[] args)
{
String str = "geeksforgeeks";
int chars[] = { 1, 5, 7, 9 };
String ans = addStars(str, chars);
// Printing the resultant string
System.out.println(ans);
}
}
# Python3 code to implement the above approach
# Function to add stars
def addStars(s, stars) :
# Create a string ans for storing
# resultant string
ans = "";
j = 0;
for i in range(len(s)) :
# If the count of characters
# become equal to the stars[j],
# append star
if (j < len(stars) and i == stars[j]) :
ans += '*';
j += 1;
ans += s[i];
return ans;
# Driver code
if __name__ == "__main__" :
string = "geeksforgeeks";
chars = [ 1, 5, 7, 9 ];
ans = addStars(string, chars);
# Printing the resultant string
print(ans);
# This code is contributed by AnkThon
// C# code to implement the approach
using System;
using System.Collections;
public class GFG
{
// Function to add stars
public static string addStars(string s, int[] stars)
{
// Create a string ans for storing
// resultant string
string ans = "";
int j = 0;
for (int i = 0; i < s.Length; i++) {
// If the count of characters
// become equal to the stars[j],
// append star
if (j < stars.Length && i == stars[j]) {
ans += '*';
j++;
}
ans += s[i];
}
return ans;
}
// Driver code
public static void Main(string[] args)
{
string str = "geeksforgeeks";
int[] chars = { 1, 5, 7, 9 };
string ans = addStars(str, chars);
// Printing the resultant string
Console.Write(ans);
}
}
// This code is contributed by garg28harsh.
// Javascript code to implement the approach
// Function to add stars
function addStars(s, stars) {
// Create a string ans for storing
// resultant string
let ans = "";
let j = 0;
for (let i = 0; i < s.length; i++) {
// If the count of characters
// become equal to the stars[j],
// append star
if (j < stars.length && i == stars[j]) {
ans += '*';
j++;
}
ans += s[i];
}
return ans;
}
// Driver code
let str = "geeksforgeeks";
let chars = [1, 5, 7, 9];
let ans = addStars(str, chars);
// Printing the resultant string
console.log(ans)
Output
g*eeks*fo*rg*eeks
Time Complexity: O(n)
Auxiliary Space: O(n)
Approach - By Using inbuilt insert function
In this approach we need to increase the length of orignal string as on insert operation the orignal string get modified and so the target index needs to be increased by 1 so we used k.
Step-by-step approach:
- The addStars function takes a string s and a vector of integers stars as input.
- It iterates through the stars vector using a for loop.
- For each position specified in the stars vector, it inserts an asterisk (*) at that position in the string s(using insert function).
- we increment the k on insertion because size increases on an insertion operation.
- The updated string is returned.
#include <bits/stdc++.h>
using namespace std;
// Function to add stars
string addStars(string s, vector<int>& stars)
{
// Iterate through the vector of positions
int k=0;
for (int i = 0; i < stars.size(); i++) {
// Insert a star at the specified position
s.insert(stars[i]+ k++, "*");
}
return s;
}
// Driver code
int main()
{
string str = "geeksforgeeks";
vector<int> chars = { 1, 5, 7, 9 };
string ans = addStars(str, chars);
// Printing the resultant string
cout << ans << endl;
}
import java.util.ArrayList;
import java.util.List;
public class GFG {
// Function to add stars
public static String addStars(String s, List<Integer> stars) {
// Iterate through the vector of positions
int k = 0;
for (int i = 0; i < stars.size(); i++) {
// Insert a star at the specified position
s = s.substring(0, stars.get(i) + k) + "*" + s.substring(stars.get(i) + k);
k++;
}
// Return result
return s;
}
public static void main(String[] args) {
// Test case
String str = "geeksforgeeks";
List<Integer> chars = new ArrayList<>();
chars.add(1);
chars.add(5);
chars.add(7);
chars.add(9);
String ans = addStars(str, chars);
System.out.println(ans);
}
}
# Function to add stars
def addStars(s, stars):
# Iterate through the vector of positions
k = 0
for i in range(len(stars)):
# Insert a star at the specified position
s = s[:stars[i]+k] + "*" + s[stars[i]+k:]
k += 1
return s
# Driver code
str = "geeksforgeeks"
chars = [1, 5, 7, 9]
ans = addStars(str, chars)
# Printing the resultant string
print(ans)
using System;
using System.Collections.Generic;
namespace CodeTranslation
{
class GfG
{
// Function to add stars
static string AddStars(string s, List<int> stars)
{
// Iterate through the list of positions
int k = 0;
for (int i = 0; i < stars.Count; i++)
{
// Insert a star at the specified position
s = s.Insert(stars[i] + k++, "*");
}
return s;
}
// Driver code
static void Main(string[] args)
{
string str = "geeksforgeeks";
List<int> chars = new List<int> { 1, 5, 7, 9 };
string ans = AddStars(str, chars);
// Printing the resultant string
Console.WriteLine(ans);
}
}
}
// Function to add stars
function addStars(s, stars) {
// Iterate through the vector of positions
let k = 0;
for (let i = 0; i < stars.length; i++) {
// Insert a star at the specified position
s = s.slice(0, stars[i] + k) + "*" + s.slice(stars[i] + k);
k += 1;
}
// Return result
return s;
}
// Test case
let str = "geeksforgeeks";
let chars = [1, 5, 7, 9];
let ans = addStars(str, chars);
console.log(ans);
Output
g*eeks*fo*rg*eeks
Time Complexity: O(N*K)
Auxiliary Space: O(N)