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 task is to find the final String after B swaps.
Examples:
Input : S = "ABCDEFGH", B = 4, C = 3;
Output: DEFGBCAH
Explanation:
after 1st swap: DBCAEFGH
after 2nd swap: DECABFGH
after 3rd swap: DEFABCGH
after 4th swap: DEFGBCAH
Input : S = "ABCDE", B = 10, C = 6;
Output : ADEBC
Explanation:
after 1st swap: BACDE
after 2nd swap: BCADE
after 3rd swap: BCDAE
after 4th swap: BCDEA
after 5th swap: ACDEB
after 6th swap: CADEB
after 7th swap: CDAEB
after 8th swap: CDEAB
after 9th swap: CDEBA
after 10th swap: ADEBC
Naive Approach:
- For large values of B, the naive approach of looping B times, each time swapping ith character with (i + C)%N-th character will result in high CPU time.
- The trick to solving this problem is to observe the resultant string after every N iterations, where N is the length of the string S.
- Again, if C is greater than or equal to the N, it is effectively equal to the remainder of C divided by N.
- Hereon, let’s consider C to be less than N.
Below is the implementation of the approach:
C++
#include <iostream>
#include <string>
using namespace std;
string swapCharacters(string s, int B, int C)
{
int N = s.size();
C = C % N;
for ( int i = 0; i < B; i++) {
swap(s[i], s[(i + C) % N]);
}
return s;
}
int main()
{
string s = "ABCDEFGH" ;
int B = 4;
int C = 3;
s = swapCharacters(s, B, C);
cout << s << endl;
return 0;
}
|
Java
import java.util.*;
public class Main {
public static String swapCharacters(String s, int B,
int C)
{
int N = s.length();
C = C % N;
char [] arr = s.toCharArray();
for ( int i = 0 ; i < B; i++) {
char temp = arr[i];
arr[i] = arr[(i + C) % N];
arr[(i + C) % N] = temp;
}
return new String(arr);
}
public static void main(String[] args)
{
String s = "ABCDEFGH" ;
int B = 4 ;
int C = 3 ;
s = swapCharacters(s, B, C);
System.out.println(s);
}
}
|
Python3
def swapCharacters(s, B, C):
N = len (s)
C = C % N
s = list (s)
for i in range (B):
s[i], s[(i + C) % N] = s[(i + C) % N], s[i]
return ''.join(s)
s = "ABCDEFGH"
B = 4
C = 3
s = swapCharacters(s, B, C)
print (s)
|
C#
using System;
class Program
{
static string SwapCharacters( string s, int B, int C)
{
int N = s.Length;
C = C % N;
for ( int i = 0; i < B; i++)
{
int j = (i + C) % N;
char temp = s[i];
s = s.Remove(i, 1).Insert(i, s[j].ToString());
s = s.Remove(j, 1).Insert(j, temp.ToString());
}
return s;
}
static void Main()
{
string s = "ABCDEFGH" ;
int B = 4;
int C = 3;
s = SwapCharacters(s, B, C);
Console.WriteLine(s);
}
}
|
Javascript
function swapCharacters(s, B, C) {
const N = s.length;
C = C % N;
for (let i = 0; i < B; i++) {
const temp = s[i];
s = s.substring(0, i) + s[(i + C) % N] + s.substring(i + 1);
s = s.substring(0, (i + C) % N) + temp + s.substring((i + C) % N + 1);
}
return s;
}
let s = "ABCDEFGH" ;
const B = 4;
const C = 3;
s = swapCharacters(s, B, C);
console.log(s);
|
Time Complexity: O(B), to iterate B times.
Auxiliary Space: O(1)
Efficient Approach:
- If we observe the string that is formed after every N successive iterations and swaps (let’s call it one full iteration), we can start to get a pattern.
- We can find that the string is divided into two parts: the first part of length C comprising of the first C characters of S, and the second part comprising of the rest of the characters.
- The two parts are rotated by some places. The first part is rotated right by (N % C) places every full iteration.
- The second part is rotated left by C places every full iteration.
- We can calculate the number of full iterations f by dividing B by N.
- So, the first part will be rotated left by ( N % C ) * f . This value can go beyond C and so, it is effectively ( ( N % C ) * f ) % C, i.e. the first part will be rotated by ( ( N % C ) * f ) % C places left.
- The second part will be rotated left by C * f places. Since, this value can go beyond the length of the second part which is ( N – C ), it is effectively ( ( C * f ) % ( N – C ) ), i.e. the second part will be rotated by ( ( C * f ) % ( N – C ) ) places left.
- After f full iterations, there may still be some iterations remaining to complete B iterations. This value is B % N which is less than N. We can follow the naive approach on these remaining iterations after f full iterations to get the resultant string.
Example:
s = ABCDEFGHIJK; c = 4;
parts: ABCD EFGHIJK
after 1 full iteration: DABC IJKEFGH
after 2 full iteration: CDAB FGHIJKE
after 3 full iteration: BCDA JKEFGHI
after 4 full iteration: ABCD GHIJKEF
after 5 full iteration: DABC KEFGHIJ
after 6 full iteration: CDAB HIJKEFG
after 7 full iteration: BCDA EFGHIJK
after 8 full iteration: ABCD IJKEFGH
Below is the implementation of the approach:
C++
#include <bits/stdc++.h>
using namespace std;
string rotateLeft(string s, int p)
{
return s.substr(p) + s.substr(0, p);
}
string swapChars(string s, int c, int b)
{
int n = s.size();
c = c % n;
if (c == 0)
{
return s;
}
int f = b / n;
int r = b % n;
string p1 = rotateLeft(s.substr(0, c),
((n % c) * f) % c);
string p2 = rotateLeft(s.substr(c),
((c * f) % (n - c)));
string a = p1 + p2;
for ( int i = 0; i < r; i++)
{
char temp = a[i];
a[i] = a[(i + c) % n];
a[(i + c) % n] = temp;
}
return a;
}
int main()
{
string s1 = "ABCDEFGHIJK" ;
int b = 1000;
int c = 3;
cout << swapChars(s1, c, b) << endl;
}
|
Java
class GFG {
String swapChars(String s, int c, int b)
{
int n = s.length();
c = c % n;
if (c == 0 ) {
return s;
}
int f = b / n;
int r = b % n;
String p1 = rotateLeft(s.substring( 0 , c),
((n % c) * f) % c);
String p2 = rotateLeft(s.substring(c),
((c * f) % (n - c)));
char a[] = (p1 + p2).toCharArray();
for ( int i = 0 ; i < r; i++) {
char temp = a[i];
a[i] = a[(i + c) % n];
a[(i + c) % n] = temp;
}
return new String(a);
}
String rotateLeft(String s, int p)
{
return s.substring(p) + s.substring( 0 , p);
}
public static void main(String args[])
{
String s1 = "ABCDEFGHIJK" ;
int b = 1000 ;
int c = 3 ;
String s2 = new GFG().swapChars(s1, c, b);
System.out.println(s2);
}
}
|
Python3
def swapChars(s, c, b):
n = len (s)
c = c % n
if (c = = 0 ):
return s
f = int (b / n)
r = b % n
p1 = rotateLeft(s[ 0 : c], ((c * f) % (n - c)))
p2 = rotateLeft(s[c:], ((c * f) % (n - c)))
a = p1 + p2
a = list (a)
for i in range (r):
temp = a[i]
a[i] = a[(i + c) % n]
a[(i + c) % n] = temp
return str ("".join(a))
def rotateLeft(s, p):
return s[p:] + s[ 0 : p]
s1 = "ABCDEFGHIJK"
b = 1000
c = 3
s2 = swapChars(s1, c, b)
print (s2)
|
C#
using System;
class GFG
{
String swapChars(String s, int c, int b)
{
int n = s.Length;
c = c % n;
if (c == 0)
{
return s;
}
int f = b / n;
int r = b % n;
String p1 = rotateLeft(s.Substring(0, c),
((n % c) * f) % c);
String p2 = rotateLeft(s.Substring(c),
((c * f) % (n - c)));
char []a = (p1 + p2).ToCharArray();
for ( int i = 0; i < r; i++)
{
char temp = a[i];
a[i] = a[(i + c) % n];
a[(i + c) % n] = temp;
}
return new String(a);
}
String rotateLeft(String s, int p)
{
return s.Substring(p) + s.Substring(0, p);
}
public static void Main(String []args)
{
String s1 = "ABCDEFGHIJK" ;
int b = 1000;
int c = 3;
String s2 = new GFG().swapChars(s1, c, b);
Console.WriteLine(s2);
}
}
|
Javascript
<script>
function swapChars(s, c, b)
{
let n = s.length;
c = c % n;
if (c == 0) {
return s;
}
let f = Math.floor(b / n);
let r = b % n;
let p1 = rotateLeft(s.substring(0, c),
((n % c) * f) % c);
let p2 = rotateLeft(s.substring(c),
((c * f) % (n - c)));
let a = (p1 + p2).split( "" );
for (let i = 0; i < r; i++) {
let temp = a[i];
a[i] = a[(i + c) % n];
a[(i + c) % n] = temp;
}
return (a).join( "" );
}
function rotateLeft(s,p)
{
return s.substring(p) + s.substring(0, p);
}
let s1 = "ABCDEFGHIJK" ;
let b = 1000;
let c = 3;
let s2 = swapChars(s1, c, b);
document.write(s2);
</script>
|
Time Complexity: O(n)
Space Complexity: O(n)
Last Updated :
26 Oct, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...