Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
C++ Program to Convert String to Integer
Next article icon

C++ Program to Swap characters in a String

Last Updated : 18 Aug, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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
 
 
Output
DEFGBCAH

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
 
 
Output: 
CADEFGHIJKB

 

Time Complexity: O(n) 
Space Complexity: O(n)
 

Please refer complete article on Swap characters in a String for more details!



Next Article
C++ Program to Convert String to Integer
author
kartik
Improve
Article Tags :
  • C++
  • C++ Programs
  • DSA
  • Strings
  • Constructive Algorithms
  • rotation
  • Swap-Program
Practice Tags :
  • CPP
  • Strings

Similar Reads

  • C++ Program to Replace a Character in a String
    Given a string S, c1 and c2. Replace character c1 with c2 and c2 with c1. Examples: Input: grrksfoegrrks, c1 = e, c2 = r Output: geeksforgeeks Input: ratul, c1 = t, c2 = h Output: rahul Traverse through the string and check for the occurrences of c1 and c2. If c1 is found then replace it with c2 and
    3 min read
  • C++ Program to Sort String of Characters
    Sorting a string means rearranging the characters of the given string in some defined order such as alphabetical order. In this article, we will learn how to sort a string by characters in C++. Examples Input: str = "geeksforgeeks"Output: "eeeefggkkorss"Explanation: The characters in the string are
    4 min read
  • C Program to Extract Characters From a String
    Character extraction can be done by iterating through the string in the form of a character array. It basically means plucking out a certain amount of characters from an array or a string. Now, to take input in C we do it by using the following methods: scanf("%c",&str[i]); - Using a loopscanf("
    2 min read
  • C++ Program to Convert String to Integer
    Given a string of digits, the task is to convert the string to an integer. Examples: Input : str = "12345" Output : 12345 Input : str = "876538"; Output : 876538 Input : str = "0028"; Output : 28 C/C++ Code // C++ program to convert String into Integer #include <bits/stdc++.h> using namespace
    1 min read
  • Convert character array to string in C++
    This article shows how to convert a character array to a string in C++. The std::string in c++ has a lot of inbuilt functions which makes implementation much easier than handling a character array. Hence, it would often be easier to work if we convert a character array to string. Examples: Input: ch
    4 min read
  • Convert String to Char Array in C++
    In C++, we usually represent text data using the std::string object. But in some cases, we may need to convert a std::string to a character array, the traditional C-style strings. In this article, we will learn how to convert the string to char array in C++. Examples Input: str = "geeksforgeeks"Outp
    4 min read
  • How to Convert a Single Character to String in C++?
    A string is a generally made up of a sequence of multiple characters. In this article, we will learn how to convert a single character to a string in C++. Example: Input: c = 'A'Output: s = "a"Explanation: Character c is converted to a string. Input: c = '#'Output: s = "#"Explanation: Character c is
    4 min read
  • How to Convert a std::string to char* in C++?
    In C++, strings are the textual data that is represented in two ways: std::string which is an object, and char* is a pointer to a character. In this article, we will learn how to convert a std::string to char* in C++. Example Input:string myString = "GeeksforGeeks";Output:char * myString = "Geeksfor
    1 min read
  • C++ Program to compare two string using pointers
    Given two strings, compare the strings using pointers Examples: Input: str1 = geeks, str2 = geeks Output: Both are equal Input: str1 = hello, str2 = hellu Output: Both are not equal As their length are same but characters are different The idea is to dereference given pointers, compare values and ad
    1 min read
  • Convert char* to std::string in C++
    Strings are generally represented as an instance of std::string class in C++. But the language also supports the older C-Style representation where they are represented as array of characters (char* or char[]) terminated by null character '\0'. In this article, we will learn how to convert the char*
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences