C++ Program to Swap characters in a String
Last Updated :
18 Aug, 2023
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++
// C++ Program to Swap characters in a String
#include <iostream>
#include <string>
using namespace std;
string swapCharacters(string s, int B, int C)
{
int N = s.size();
// If c is greater than n
C = C % N;
// loop to swap ith element with (i + C) % n th element
for (int i = 0; i < B; i++) {
swap(s[i % N], 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;
}
// This code is contributed by Susobhan Akhuli
Time Complexity: O(B), to iterate B times.
Space Complexity: 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++
// C++ program to find new after swapping
// characters at position i and i + c
// b times, each time advancing one
// position ahead
#include <bits/stdc++.h>
using namespace std;
string rotateLeft(string s, int p)
{
// Rotating a string p times left is
// effectively cutting the first p
// characters and placing them at the end
return s.substr(p) + s.substr(0, p);
}
// Method to find the required string
string swapChars(string s, int c, int b)
{
// Get string length
int n = s.size();
// If c is larger or equal to the length of
// the string is effectively the remainder of
// c divided by the length of the string
c = c % n;
if (c == 0)
{
// No change will happen
return s;
}
int f = b / n;
int r = b % n;
// Rotate first c characters by (n % c)
// places f times
string p1 = rotateLeft(s.substr(0, c),
((n % c) * f) % c);
// Rotate remaining character by
// (n * f) places
string p2 = rotateLeft(s.substr(c),
((c * f) % (n - c)));
// Concatenate the two parts and convert the
// resultant string formed after f full
// iterations to a string array
// (for final swaps)
string a = p1 + p2;
// Remaining swaps
for(int i = 0; i < r; i++)
{
// Swap ith character with
// (i + c)th character
char temp = a[i];
a[i] = a[(i + c) % n];
a[(i + c) % n] = temp;
}
// Return final string
return a;
}
// Driver code
int main()
{
// Given values
string s1 = "ABCDEFGHIJK";
int b = 1000;
int c = 3;
// Get final string print final string
cout << swapChars(s1, c, b) << endl;
}
// This code is contributed by rag2127
Time Complexity: O(n)
Space Complexity: O(n)
Please refer complete article on Swap characters in a String for more details!
Similar Reads
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
Different Methods to Reverse a String in C++ Reversing the string means the last character will be the first character, second last character will be second character and so on. In C++, we can reverse a string in various different ways as show below:Table of ContentUsing reverse() FunctionUsing Reverse IteratorsUsing a StackUsing Two Pointer T
3 min read
Count of distinct strings that can be obtained after performing exactly one swap Given a string s containing lowercase characters. The task is to calculate the number of distinct strings that can be obtained after performing exactly one swap.Input: s = "geek"Output: 6Explanation: Following are the strings formed by doing exactly one swap:"egek", "eegk", "geek", "geke", "gkee", "
9 min read
Lexicographically largest string possible in one swap Given string str of length N, the task is to obtain the lexicographically largest string by at most one swap. Note: The swapping characters might not be adjacent. Examples: Input: str = "string" Output: tsring Explanation: Lexicographically largest string obtained by swapping string -> tsring. In
7 min read
Left Rotation of a String Given a string s and an integer d, the task is to left rotate the string by d positions.Examples:Input: s = "GeeksforGeeks", d = 2Output: "eksforGeeksGe" Explanation: After the first rotation, string s becomes "eeksforGeeksG" and after the second rotation, it becomes "eksforGeeksGe".Input: s = "qwer
15+ min read