Flip the String by Either Swapping given Characters or Rotating it Horizontally for Q Queries


Flip the String by either swapping given characters or rotating it horizontally for Q queries is a fascinating problem that involves manipulating a string based on a series of queries. In this tutorial, we delve into this problem and provide a solution using C++.

The problem statement revolves around a string of characters and a set of queries, each containing instructions to swap specific characters or perform a horizontal rotation. Our objective is to determine the final configuration of the string after applying all the queries.

Through this tutorial, we will explore the intricacies of the problem, discuss the implementation details in C++, and provide a step-by-step guide to solving it efficiently. By the end, readers will have a comprehensive understanding of how to tackle similar string manipulation challenges using C++ programming. So, let's dive into the exciting world of flipping strings and discover the elegant solutions that await us.

Problem Statement

Consider a string of length 2N and a set of queries represented by three integers T, A, and B. Each query type T can be either 1 or 2. For type 1 queries, the Ath and Bth characters (using 1-based indexing) in the string are swapped, while for type 2 queries, the first N characters are swapped with the last N characters. The objective is to find the resulting string after applying all the queries.

Let’s understand this problem statement with examples.

Sample Example 1

Input

Given a string "ABCD" with N = 2 and the following queries: {{2, 0, 0}, {1, 1, 3}, {2, 0, 0}}

Output

The final string is "CBAD".

Explanation

  • Applying the first query (type 2) results in the string "CDAB".

  • Performing the second query (type 1) swaps the characters at positions 1 and 3, transforming the string into "ADCB".

  • The third query (type 2) swaps the first N characters with the last N characters, resulting in the final string "CBAD".

Sample Example 2

Input

Consider the string "LEAP" with N = 2 and the queries: {{2, 0, 0}, {1, 1, 2}, {1, 2, 3}, {1, 3, 4}, {2, 0, 0}}

Output

The final string is "EAPL".

Explanation

  • Applying the first query (type 2) does not modify the string: "LEAP".

  • Performing the second query (type 1) swaps the characters at positions 1 and 2, resulting in "ELAP".

  • The third query (type 1) swaps the characters at positions 2 and 3, transforming the string into "EALP".

  • Performing the fourth query (type 1) swaps the characters at positions 3 and 4, resulting in "EAPL".

  • The final query (type 2) swaps the first N characters with the last N characters, leaving the string unchanged: "EAPL".

Therefore, after applying all the queries to the input string "LEAP," the final string is "EAPL".

Algorithm

  • Step 1 − Define the function ‘swapCharacters’ that swaps two characters in a given string based on their indices.

  • Step 2 − Define the function ‘rotateString’ that rotates a given string by ‘N’ positions by moving the first ‘N’ characters to the end of the string.

  • Step 3 − Define the function ‘applyQueries’ that takes the original string, the rotation value ‘N’, and the vector of queries as input.

  • Step 4 − Initialize ‘modifiedString’ as a copy of the original string.

  • Step 5 − Iterate through each query in the vector of queries.

    • Extract the type, ‘a’, and ‘b’ values from the current query.

    • If the type is 1, call ‘swapCharacters’ to swap the characters at indices ‘a’ and ‘b’ in ‘modifiedString’.

    • Otherwise, call ‘rotateString’ to rotate ‘modifiedString’ by ‘N’ positions.

  • Step 6 − Return the modified string.

  • Step 7 − In the ‘main’ function, initialize the original string ‘S’, rotation value ‘N’, and vector of queries.

  • Step 8 − Call the ‘applyQueries’ function with these values to obtain the modified string.

  • Step 9 − Print the final string as the output.

Example

Implementation of the above Algorithm using C++

The below C++ program takes a string ‘S’ and performs different operations on it based on a set of queries. The queries are represented as a vector of vectors, where each inner vector contains three elements: the type of operation, and the indices ‘a’ and ‘b’ representing the characters to be swapped. The program applies these queries to the string ‘S’ and produces the modified string as the output.

Input

"ABCD"; N: 2; Queries: {{2, 0, 0}, {1, 1, 3}, {2, 0, 0}};

Output

Final String: "CBAD"

Example

#include <stdio.h>
#include <stdlib.h> // Add this line to include stdlib.h
#include <string.h>

// Function to swap characters at indices a and b in a string
void swapCharacters(char *str, int a, int b) {
   char temp = str[a - 1];
   str[a - 1] = str[b - 1];
   str[b - 1] = temp;
}

// Function to rotate a string by N positions
void rotateString(char *str, int N) {
   int length = strlen(str);
   if (N <= 0 || N >= length)
      return;
   char temp[N];
   strncpy(temp, str, N);
   memmove(str, str + N, length - N);
   strncpy(str + length - N, temp, N);
}

// Function to apply queries to a string
char* applyQueries(const char* str, int N, int queries[][3], int numQueries) {
   char* modifiedString = strdup(str);
   for (int i = 0; i < numQueries; i++) {
      int type = queries[i][0];
      int a = queries[i][1];
      int b = queries[i][2];
      if (type == 1) {
         swapCharacters(modifiedString, a, b);
      } else {
         rotateString(modifiedString, N);
      }
   }
   return modifiedString;
}

int main() {
   char S[] = "ABCD";
   int N = 2;
   int queries[][3] = {{2, 0, 0}, {1, 1, 3}, {2, 0, 0}};
   int numQueries = sizeof(queries) / sizeof(queries[0]);
   char* result = applyQueries(S, N, queries, numQueries);
   printf("Final String: %s\n", result);
   free(result); // Now free can be used without warnings
   return 0;
}

Output

Final String: CBAD
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
void swapCharacters(std::string& str, int a, int b) {
   std::swap(str[a - 1], str[b - 1]);
}
void rotateString(std::string& str, int N) {
   int length = str.length();
   if (N <= 0 || N >= length)
      return;
   std::string temp = str.substr(0, N);
   str.erase(0, N);
   str += temp;
}
std::string applyQueries(const std::string& str, int N, const 
std::vector<std::vector<int>>& queries) {
   std::string modifiedString = str;
   for (const std::vector<int>& query : queries) {
      int type = query[0];
      int a = query[1];
      int b = query[2];
      if (type == 1) {
         swapCharacters(modifiedString, a, b);
      } else {
         rotateString(modifiedString, N);
      }
   }
   return modifiedString;
}
int main() {
   std::string S = "ABCD";
   int N = 2;
   std::vector<std::vector<int>> queries = {{2, 0, 0}, {1, 1, 3}, {2, 0, 0}};
   std::string result = applyQueries(S, N, queries);
   std::cout << "Final String: " << result << std::endl;
   return 0;
}

Output

Final String: CBAD
import java.util.ArrayList;
import java.util.List;

public class StringManipulation {
   // Function to swap characters at indices a and b in a string
   public static String swapCharacters(String str, int a, int b) {
      char[] charArray = str.toCharArray();
      char temp = charArray[a - 1];
      charArray[a - 1] = charArray[b - 1];
      charArray[b - 1] = temp;
      return new String(charArray);
   }

   // Function to rotate a string by N positions
   public static String rotateString(String str, int N) {
      int length = str.length();
      if (N <= 0 || N >= length)
         return str;
      String temp = str.substring(0, N);
      return str.substring(N) + temp;
   }

   // Function to apply queries to a string
   public static String applyQueries(String str, int N, List<int[]> queries) {
      String modifiedString = str;
      for (int[] query : queries) {
         int type = query[0];
         int a = query[1];
         int b = query[2];
         if (type == 1) {
            modifiedString = swapCharacters(modifiedString, a, b);
         } else {
            modifiedString = rotateString(modifiedString, N);
         }
      }
      return modifiedString;
   }

   public static void main(String[] args) {
      String S = "ABCD";
      int N = 2;
      List<int[]> queries = new ArrayList<>();
      queries.add(new int[]{2, 0, 0});
      queries.add(new int[]{1, 1, 3});
      queries.add(new int[]{2, 0, 0});
      String result = applyQueries(S, N, queries);
      System.out.println("Final String: " + result);
   }
}

Output

Final String: CBAD
def swap_characters(s, a, b):
   s_list = list(s)
   s_list[a - 1], s_list[b - 1] = s_list[b - 1], s_list[a - 1]
   return ''.join(s_list)

def rotate_string(s, N):
   if N <= 0 or N >= len(s):
      return s
   return s[N:] + s[:N]

def apply_queries(s, N, queries):
   modified_string = s
   for query in queries:
      type, a, b = query
      if type == 1:
         modified_string = swap_characters(modified_string, a, b)
      else:
         modified_string = rotate_string(modified_string, N)
   return modified_string

S = "ABCD"
N = 2
queries = [[2, 0, 0], [1, 1, 3], [2, 0, 0]]
result = apply_queries(S, N, queries)
print("Final String:", result)

Output

Final String: CBAD

Conclusion

To sum up, the problem of flipping a string by either swapping given characters or rotating it horizontally for Q queries offers an interesting exercise in string manipulation. Throughout this tutorial, we explored the problem statement, discussed its implementation in various programming languages, and provided a step-by-step solution. By leveraging C, C++, Java and Python programming techniques and utilizing functions to swap characters and rotate the string, we have successfully tackled the problem and obtained the desired output. With this tutorial, readers can efficiently solve similar problems or challenges. Happy Learning. Happy coding!

Updated on: 20-Oct-2023

62 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements