Swap characters in a String
Last Updated :
26 Oct, 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], 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
Java
// Java Program to Swap characters in a String
import java.util.*;
public class Main {
public static String swapCharacters(String s, int B,
int C)
{
int N = s.length();
// If c is greater than n
C = C % N;
// loop to swap ith element with (i + C) % n th
// element
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);
}
}
// This code is contributed by Susobhan Akhuli
Python3
# Python Program to Swap characters in a String
def swapCharacters(s, B, C):
N = len(s)
# If c is greater than n
C = C % N
# loop to swap ith element with (i + C) % n th element
s = list(s)
for i in range(B):
s[i], s[(i + C) % N] = s[(i + C) % N], s[i]
return ''.join(s)
# Driver code
s = "ABCDEFGH"
B = 4
C = 3
s = swapCharacters(s, B, C)
print(s)
# This code is contributed by Susobhan Akhuli
C#
using System;
class Program
{
// Function to swap characters in a string
static string SwapCharacters(string s, int B, int C)
{
int N = s.Length;
// If C is greater than N, take the modulo to ensure it's within bounds
C = C % N;
// Loop to swap the ith element with (i + C) % N th element
for (int i = 0; i < B; i++)
{
int j = (i + C) % N; // Calculate the index of the character to swap with
char temp = s[i]; // Store the character at index i in a temporary variable
// Replace character at index i with the character at index j
s = s.Remove(i, 1).Insert(i, s[j].ToString());
// Replace character at index j with the character stored in temp
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
// JS Program to Swap characters in a String
function swapCharacters(s, B, C) {
const N = s.length;
// If c is greater than n
C = C % N;
// loop to swap ith element with (i + C) % n th element
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++
// 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
Java
// Java Program to find new after swapping
// characters at position i and i + c
// b times, each time advancing one
// position ahead
class GFG {
// Method to find the required string
String swapChars(String s, int c, int b)
{
// Get string length
int n = s.length();
// 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.substring(0, c),
((n % c) * f) % c);
// Rotate remaining character by
// (n * f) places
String p2 = rotateLeft(s.substring(c),
((c * f) % (n - c)));
// Concatenate the two parts and convert the
// resultant string formed after f full
// iterations to a character array
// (for final swaps)
char a[] = (p1 + p2).toCharArray();
// 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 new String(a);
}
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.substring(p) + s.substring(0, p);
}
// Driver code
public static void main(String args[])
{
// Given values
String s1 = "ABCDEFGHIJK";
int b = 1000;
int c = 3;
// get final string
String s2 = new GFG().swapChars(s1, c, b);
// print final string
System.out.println(s2);
}
}
Python3
# Python3 program to find new after swapping
# characters at position i and i + c
# b times, each time advancing one
# position ahead
# Method to find the required string
def swapChars(s, c, b):
# Get string length
n = len(s)
# 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
f = int(b / n)
r = b % n
# Rotate first c characters by (n % c)
# places f times
p1 = rotateLeft(s[0 : c], ((c * f) % (n - c)))
# Rotate remaining character by
# (n * f) places
p2 = rotateLeft(s[c:], ((c * f) % (n - c)))
# Concatenate the two parts and convert the
# resultant string formed after f full
# iterations to a character array
# (for final swaps)
a = p1 + p2
a = list(a)
# Remaining swaps
for i in range(r):
# Swap ith character with
# (i + c)th character
temp = a[i]
a[i] = a[(i + c) % n]
a[(i + c) % n] = temp
# Return final string
return str("".join(a))
def rotateLeft(s, p):
# Rotating a string p times left is
# effectively cutting the first p
# characters and placing them at the end
return s[p:] + s[0 : p]
# Driver code
# Given values
s1 = "ABCDEFGHIJK"
b = 1000
c = 3
# Get final string
s2 = swapChars(s1, c, b)
# Print final string
print(s2)
# This code is contributed by avanitrachhadiya2155
C#
// C# Program to find new after swapping
// characters at position i and i + c
// b times, each time advancing one
// position ahead
using System;
class GFG
{
// Method to find the required string
String swapChars(String s, int c, int b)
{
// Get string length
int n = s.Length;
// 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.Substring(0, c),
((n % c) * f) % c);
// Rotate remaining character by
// (n * f) places
String p2 = rotateLeft(s.Substring(c),
((c * f) % (n - c)));
// Concatenate the two parts and convert the
// resultant string formed after f full
// iterations to a character array
// (for readonly swaps)
char []a = (p1 + p2).ToCharArray();
// 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 readonly string
return new String(a);
}
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.Substring(p) + s.Substring(0, p);
}
// Driver code
public static void Main(String []args)
{
// Given values
String s1 = "ABCDEFGHIJK";
int b = 1000;
int c = 3;
// get readonly string
String s2 = new GFG().swapChars(s1, c, b);
// print readonly string
Console.WriteLine(s2);
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// Javascript Program to find new after swapping
// characters at position i and i + c
// b times, each time advancing one
// position ahead
function swapChars(s, c, b)
{
// Get string length
let n = s.length;
// 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;
}
let f = Math.floor(b / n);
let r = b % n;
// Rotate first c characters by (n % c)
// places f times
let p1 = rotateLeft(s.substring(0, c),
((n % c) * f) % c);
// Rotate remaining character by
// (n * f) places
let p2 = rotateLeft(s.substring(c),
((c * f) % (n - c)));
// Concatenate the two parts and convert the
// resultant string formed after f full
// iterations to a character array
// (for final swaps)
let a = (p1 + p2).split("");
// Remaining swaps
for (let i = 0; i < r; i++) {
// Swap ith character with
// (i + c)th character
let temp = a[i];
a[i] = a[(i + c) % n];
a[(i + c) % n] = temp;
}
// Return final string
return (a).join("");
}
function rotateLeft(s,p)
{
// Rotating a string p times left is
// effectively cutting the first p
// characters and placing them at the end
return s.substring(p) + s.substring(0, p);
}
// Driver code
// Given values
let s1 = "ABCDEFGHIJK";
let b = 1000;
let c = 3;
// get final string
let s2 = swapChars(s1, c, b);
// print final string
document.write(s2);
// This code is contributed by ab2127
</script>
Time Complexity: O(n)
Space Complexity: O(n)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem