VOOZH about

URL: https://www.geeksforgeeks.org/dsa/string-obtained-by-reversing-and-complementing-a-binary-string-k-times/

⇱ String obtained by reversing and complementing a Binary string K times - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

String obtained by reversing and complementing a Binary string K times

Last Updated : 12 Jul, 2025

Given a binary string of size N and an integer K, the task is to perform K operations upon the string and print the final string: 

  • If the operation number is odd, then reverse the string,
  • If the operation number even, then complement the string.

Examples:  

Input: str = "1011", K = 2 
Output: 0010 
After the first step, string will be reversed and becomes "1101". 
After the second step, the string will be complemented and becomes "0010".

Input: str = "1001", K = 4 
Output: 1001 
After all operation the string will remain same.  

Naive Approach: 
Traverse for all K steps and if the current step is odd then perform the reverse operation, otherwise complement the string. 

Efficient Approach: Upon observing the given operation pattern:  

  • If a string is reversed even number of times, the original string is obtained.
  • Similarly, if a string is complemented even number of times, the original string is obtained.
  • Therefore, these operations depends only upon the parity of K.
  • So we will count the number of reverse operations to be performed. If parity is odd, then we will reverse it. Else the string will remain unchanged.
  • Similarly we will count the number of complement operations to be performed. If parity is odd, then we will complement it. Else the string will remain unchanged.

Below is the implementation of the above approach:  


Output: 
11001

 

Time Complexity: O(N)
Auxiliary Space: O(1)

Comment