Insert a Character in a Rotated String
Last Updated :
22 Dec, 2022
Given an array of characters arr[] of size N and an integer K. You have to insert the characters into an empty string one by one such that every insertion is done after K positions to the right from the previous insertion and the string is circular. The task is to find the character after which the last insertion is done
Examples:
Input: arr[] = {'1', '2', '3', '4', '5'}, K = 2
Output: 1
After the first insertion string becomes "1"
After the second insertion string becomes "12"
After third insertion, as the previous insertion was at position 2.
So, the current insertion has to be at 2 + 2 i.e. 4th position.
Since, the string is circular so moving 2 positions to the right will
be "1|2" -> "12|" and the final string will be "123"
After the fourth insertion, "123" -> "1|23" -> "12|3" i.e. "1243"
After the fifth insertion, "1243" -> "1243|" -> "1|243" i.e. "15243"
The last character inserted after the character '1'
Input: arr[] = {'1', '2', '3', '4', '5'}, K = 1
Output: 1
Final string is "15324"
Approach: For every character, insert it in the required position and also keep track of the previous position and the character after which the previous insertion was done. When all the characters have been inserted, print the character after which the last insertion was done.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to insert the character
char Insert(char arr[], int n, int k)
{
// To store last position where
// the insertion is done
int ind = 0;
// To store size of the string
int sz = 0;
// To store the modified string
string s = "";
// To store characters
char ch = arr[0];
// Add first character to the string
s += ch;
// Update the size
sz = 1;
// Update the index of last insertion
ind = 0;
// Insert all other characters to the string
for (int i = 1; i < n; i++) {
// Take the character
ch = arr[i];
// Take substring upto ind
string s1 = s.substr(0, ind + 1);
// Take modulo value of k with
// the size of the string
int temp = k % sz;
// Check if we need to move to
// the start of the string
int ro = temp - min(temp, sz - ind - 1);
// If we don't need to move to start of the string
if (ro == 0) {
// Take substring from upto temp
string s2 = s.substr(ind + 1, temp);
// Take substring which will be after
// the inserted character
string s3 = s.substr(ind + temp + 1,
sz - ind - temp - 1);
// Insert into the string
s = s1 + s2 + ch + s3;
// Store new inserted position
ind = s1.size() + s2.size();
// Store size of the new string
// Technically sz + 1
sz = s.size();
}
// If we need to move to start of the string
else {
// Take substring which will before
// the inserted character
string s2 = s.substr(0, ro);
// Take substring which will be after
// the inserted character
string s3 = s.substr(ro, sz - ro);
// Insert into the string
s = s2 + ch + s3;
// Store new inserted position
ind = s2.size();
// Store size of the new string
// Technically sz + 1
sz = s.size();
}
}
// Return the required character
if (ind == 0)
return s[sz - 1];
else
return s[ind - 1];
}
// Driver code
int main()
{
char arr[] = { '1', '2', '3', '4', '5' };
int k = 2;
int n = sizeof(arr) / sizeof(arr[0]);
// Function call
cout << Insert(arr, n, k);
return 0;
}
Java
// Java implementation of the approach
import java.util.*;
class GFG{
// Function to insert the character
public static char Insert(char arr[], int n, int k)
{
// To store last position where
// the insertion is done
int ind = 0;
// To store size of the string
int sz = 0;
// To store the modified string
String s = "";
// To store characters
char ch = arr[0];
// Add first character to the string
s += ch;
// Update the size
sz = 1;
// Update the index of last insertion
ind = 0;
// Insert all other characters to the string
for(int i = 1; i < n; i++)
{
// Take the character
ch = arr[i];
// Take substring upto ind
String s1 = s.substring(0, ind + 1);
// Take modulo value of k with
// the size of the string
int temp = k % sz;
// Check if we need to move to
// the start of the string
int ro = temp - Math.min(temp, sz - ind - 1);
// If we don't need to move to
// start of the string
if (ro == 0)
{
// Take substring from upto temp
String s2 = s.substring(ind + 1,
ind + 1 + temp);
// Take substring which will be after
// the inserted character
String s3 = s.substring(ind + temp + 1, sz);
// Insert into the string
s = s1 + s2 + ch + s3;
// Store new inserted position
ind = s1.length() + s2.length();
// Store size of the new string
// Technically sz + 1
sz = s.length();
}
// If we need to move to start of the string
else
{
// Take substring which will before
// the inserted character
String s2 = s.substring(0, ro);
// Take substring which will be after
// the inserted character
String s3 = s.substring(ro, sz);
// Insert into the string
s = s2 + ch + s3;
// Store new inserted position
ind = s2.length();
// Store size of the new string
// Technically sz + 1
sz = s.length();
}
}
// Return the required character
if (ind == 0)
{
return s.charAt(sz - 1);
}
else
{
return s.charAt(ind - 1);
}
}
// Driver code
public static void main(String []args)
{
char arr[] = { '1', '2', '3', '4', '5' };
int k = 2;
int n = arr.length;
// Function call
System.out.println(Insert(arr, n, k));
}
}
// This code is contributed by avanitrachhadiya2155
Python3
# Python3 implementation of the approach
# Function to insert the character
def insert(arr: list, n: int, k: int) -> chr:
# To store last position where
# the insertion is done
ind = 0
# To store size of the string
sz = 0
# To store the modified string
s = ""
# To store characters
ch = arr[0]
# Add first character to the string
s += ch
# Update the size
sz = 1
# Update the index of last insertion
ind = 0
# Insert all other characters to the string
for i in range(1, n):
# Take the character
ch = arr[i]
# Take substring upto ind
s1 = s[0:ind + 1]
# Take modulo value of k with
# the size of the string
temp = k % sz
# Check if we need to move to
# the start of the string
ro = temp - min(temp, sz - ind - 1)
# If we don't need to move to start of the string
if ro == 0:
# Take substring from upto temp
s2 = s[ind + 1:ind + 1 + temp]
# Take substring which will be after
# the inserted character
s3 = s[ind + temp + 1:sz]
# Insert into the string
s = s1 + s2 + ch + s3
# Store new inserted position
ind = len(s1) + len(s2)
# Store size of the new string
# Technically sz + 1
sz = len(s)
# If we need to move to start of the string
else:
# Take substring which will before
# the inserted character
s2 = s[:ro]
# Take substring which will be after
# the inserted character
s3 = s[ro:sz]
# Insert into the string
s = s2 + ch + s3
# Store new inserted position
ind = len(s2)
# Store size of the new string
# Technically sz + 1
sz = len(s)
# Return the required character
if ind == 0:
return s[sz - 1]
else:
return s[ind - 1]
# Driver Code
if __name__ == "__main__":
arr = ['1', '2', '3', '4', '5']
k = 2
n = len(arr)
# Function call
print(insert(arr, n, k))
# This code is contributed by
# sanjeev2552
C#
// C# implementation of the approach
using System;
class GFG{
// Function to insert the character
static char Insert(char[] arr, int n, int k)
{
// To store last position where
// the insertion is done
int ind = 0;
// To store size of the string
int sz = 0;
// To store the modified string
String s = "";
// To store characters
char ch = arr[0];
// Add first character to the string
s += ch;
// Update the size
sz = 1;
// Update the index of last insertion
ind = 0;
// Insert all other characters to the string
for(int i = 1; i < n; i++)
{
// Take the character
ch = arr[i];
// Take substring upto ind
string s1 = s.Substring(0, ind + 1);
// Take modulo value of k with
// the size of the string
int temp = k % sz;
// Check if we need to move to
// the start of the string
int ro = temp - Math.Min(temp, sz - ind - 1);
// If we don't need to move to
// start of the string
if (ro == 0)
{
// Take substring from upto temp
string s2 = s.Substring(ind + 1, temp);
// Take substring which will be after
// the inserted character
string s3 = s.Substring(ind + temp + 1,
sz - ind - temp - 1);
// Insert into the string
s = s1 + s2 + ch + s3;
// Store new inserted position
ind = s1.Length + s2.Length;
// Store size of the new string
// Technically sz + 1
sz = s.Length;
}
// If we need to move to start of the string
else
{
// Take substring which will before
// the inserted character
string s2 = s.Substring(0, ro);
// Take substring which will be after
// the inserted character
string s3 = s.Substring(ro, sz - ro);
// Insert into the string
s = s2 + ch + s3;
// Store new inserted position
ind = s2.Length;
// Store size of the new string
// Technically sz + 1
sz = s.Length;
}
}
// Return the required character
if (ind == 0)
{
return s[sz - 1];
}
else
{
return s[ind - 1];
}
}
// Driver code
static public void Main()
{
char[] arr = { '1', '2', '3', '4', '5' };
int k = 2;
int n = arr.Length;
// Function call
Console.WriteLine(Insert(arr, n, k));
}
}
// This code is contributed by rag2127
JavaScript
<script>
// Javascript implementation of the approach
// Function to insert the character
function Insert(arr,n,k)
{
// To store last position where
// the insertion is done
let ind = 0;
// To store size of the string
let sz = 0;
// To store the modified string
let s = "";
// To store characters
let ch = arr[0];
// Add first character to the string
s += ch;
// Update the size
sz = 1;
// Update the index of last insertion
ind = 0;
// Insert all other characters to the string
for(let i = 1; i < n; i++)
{
// Take the character
ch = arr[i];
// Take substring upto ind
let s1 = s.substring(0, ind + 1);
// Take modulo value of k with
// the size of the string
let temp = k % sz;
// Check if we need to move to
// the start of the string
let ro = temp - Math.min(temp, sz - ind - 1);
// If we don't need to move to
// start of the string
if (ro == 0)
{
// Take substring from upto temp
let s2 = s.substring(ind + 1,
ind + 1 + temp);
// Take substring which will be after
// the inserted character
let s3 = s.substring(ind + temp + 1, sz);
// Insert into the string
s = s1 + s2 + ch + s3;
// Store new inserted position
ind = s1.length + s2.length;
// Store size of the new string
// Technically sz + 1
sz = s.length;
}
// If we need to move to start of the string
else
{
// Take substring which will before
// the inserted character
let s2 = s.substring(0, ro);
// Take substring which will be after
// the inserted character
let s3 = s.substring(ro, sz);
// Insert into the string
s = s2 + ch + s3;
// Store new inserted position
ind = s2.length;
// Store size of the new string
// Technically sz + 1
sz = s.length;
}
}
// Return the required character
if (ind == 0)
{
return s[sz - 1];
}
else
{
return s[ind - 1];
}
}
// Driver code
let arr=['1', '2', '3', '4', '5' ];
let k = 2;
let n = arr.length;
document.write(Insert(arr, n, k));
// This code is contributed by ab2127
</script>
Time Complexity: O(n2), where n is the length of the given string.
Auxiliary Space: O(n)
Similar Reads
Insert a character in String at a Given Position
Given a string s, a character c and an integer position pos, the task is to insert the character c into the string s at the specified position pos.Examples: Input: s = "Geeks", c = 'A', pos = 3Output: GeeAksInput: s = "HelloWorld", c = '!', pos = 5Output: Hello!WorldTable of Content[Approach-1] Usin
5 min read
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
7 min read
Make a string non-palindromic by inserting a given character
Given a string S and a character X, the task is to generate a non-palindromic string by inserting the character X in the string S. If it is not possible to obtain a non-palindromic string, then print "-1". Examples: Input: S = âabababâ, X = 'a'Output: âaabababâExplanation: Inserting the character 'a
6 min read
Mirror characters of a string
Given a string s and an integer k. The task is to perform a mirror transformation on the substring starting from the k-th position to the end of the string. In this transformation, each letter is replaced by its corresponding mirrored letter in the English alphabet ('a' -> 'z', 'b' -> 'y', 'c'
6 min read
Convert a String into a square matrix grid of characters
Given a string of length L. The task is to convert the string into a grid.Examples: Input : str = "haveaniceday" Output : have anic eday Explanation: k is the separator. If k is 4 then the output will be "have anic eday" Input :str = "geeksforgeeks" Output : geek sfor geek s Note: & l = length o
5 min read
Swap characters in a String
Given a String S of length N, two integers B and C, the task is to traverse characters starting from the beginning, swapping a character with the character after C places from it, i.e. swap characters at position i and (i + C)%N. Repeat this process B times, advancing one position at a time. Your ta
14 min read
Generate all rotations of a given string
Given a string S. The task is to print all the possible rotated strings of the given string.Examples: Input : S = "geeks"Output : geeks eeksg eksge ksgee sgeekInput : S = "abc" Output : abc bca cabMethod 1 (Simple): The idea is to run a loop from i = 0 to n - 1 ( n = length of string) i.e for each p
8 min read
Add index to characters and reverse the string
Given a string str, the task is to encrypt and reverse the string. The string is encrypted by adding every character of the string with it's index in the string i.e. if character'a' is at index 2 then the character in the updated string will be 'a' + 2 = 'c'. Since value of string may go beyond 256,
4 min read
Check if Rotated Concatenated Strings are valid or not
Given a string s formed by concatenating another string s1 to itself, followed by a rotation to the left any number of times, the task is to determine whether a given string s is valid, indicating whether it can be formed from the original string s1. Examples: Input: s = "abcabc"Output: 1Explanation
5 min read
Maximum product of first and last character of String after rotation
Given a string S of length N, the task is to find the maximum possible product of the first and the last character of the string if it is rotated any number of times toward left or right. Examples: Input: Str = "12345" Output: 20Explanation: If we rotate the string once in anticlockwise direction, t
4 min read