Open In App

Java Program to Swap characters in a String

Last Updated : 06 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The task at hand involves manipulating a string S of length N, given as input. The string is subjected to a series of B swaps, each performed according to the following procedure: The character at position i is swapped with the character located C positions ahead of it, or (i + C)%N. This swapping process is repeated B times, with each iteration starting from the next position in the string. In other words, after one swap is performed, the next swap begins with the character immediately following the previous one. The result of the B swaps is the final string, which is the desired output of the program. This problem requires a good understanding of string manipulation and basic concepts of modular arithmetic.

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

  1. 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.
  2. 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.
  3. Again, if C is greater than or equal to the N, it is effectively equal to the remainder of C divided by N.
  4. Hereon, let’s consider C to be less than N.

Below is the implementation of the approach:

Java




// Java Program to Swap characters in a String
 
public class GFG {
 
    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[] chars = s.toCharArray();
        for (int i = 0; i < B; i++) {
            char temp = chars[i];
            chars[i] = chars[(i + C) % N];
            chars[(i + C) % N] = temp;
        }
        return String.valueOf(chars);
    }
 
    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


Output

DEFGBCAH

Time Complexity: O(B), to iterate B times.
Auxiliary Space: O(1)

Approach 2: Efficient  

  1. 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.
  2. 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.
  3. The two parts are rotated in some places. The first part is rotated right by (N % C) places every full iteration.
  4. The second part is rotated left by C places every full iteration.
  5. We can calculate the number of full iterations f by dividing B by N.
  6. 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.
  7. 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.
  8. 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:

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 swap characters in the string 's'
    String swapChars(String s, int c, int b)
    {
        int n = s.length();
        // to handle cases where c is greater than the
        // length of string 's'
        c = c % n;
        if (c == 0) {
            // return the original string if c is 0
            return s;
        }
        int f = b / n;
        int r = b % n;
        // split the string into two parts, left and right
        String left = s.substring(0, c);
        String right = s.substring(c);
        // rotate the left part
        left = rotateLeft(left, (n % c) * f % c);
        // rotate the right part
        right = rotateLeft(right, c * f % (n - c));
        // concatenate the left and right parts to get the
        // rotated string
        char[] a = (left + right).toCharArray();
        // perform the swap operation
        for (int i = 0; i < r; i++) {
            int j = (i + c) % n;
            char temp = a[i];
            a[i] = a[j];
            a[j] = temp;
        }
        // return the final rotated string
        return new String(a);
    }
 
    // method to rotate a string 's' to the left by 'p'
    // positions
    String rotateLeft(String s, int p)
    {
        return s.substring(p) + s.substring(0, p);
    }
 
    public static void main(String args[])
    {
        // test the 'swapChars' method with a sample string
        String s1 = "ABCDEFGHIJK";
        int b = 1000;
        int c = 3;
        String s2 = new GFG().swapChars(s1, c, b);
        System.out.println(s2);
    }
}


Output: 

CADEFGHIJKB

 

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

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads