Skip to content
Related Articles

Related Articles

Lexicographically largest string possible by reversing substrings having even number of 1s
  • Difficulty Level : Easy
  • Last Updated : 22 Dec, 2020

Given a binary string S, the task is to convert the given string S to its lexicographic maximum form by reversing substrings having an even number of 1s.

Examples:

Input: S = “10101”
Output: 11010
Explanation:
Reversing the substring {S[0], …, S[2]} modifies S to “10101”. 
Reversing the substring {S[1], …, S[4]} modifies S to “11010”. 
Now, any other substring cannot be chosen as each will either have odd number of 1s or will be lexicographically smaller than the previous string. Thus, 11010 is the lexicographically largest string that can be performed.

Input: S = “0101”
Output: 1010

Approach: The idea is to start from the first index and traverse the string till the total number of 1s in the string becomes even. As soon as an index is found where there is exactly an even number of 1s, reverse the string from the starting index to the end index. Repeat this process for every index to get the lexicographically largest string.



Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the lexicographically
// maximum string by reversing substrings
// having even numbers of 1s
void lexicographicallyMax(string s)
{
    // Store size of string
    int n = s.size();
 
    // Traverse the string
    for (int i = 0; i < n; i++) {
 
        // Count the number of 1s
        int count = 0;
 
        // Stores the starting index
        int beg = i;
 
        // Stores the end index
        int end = i;
 
        // Increment count, when 1
        // is encountered
        if (s[i] == '1')
            count++;
 
        // Traverse the remaining string
        for (int j = i + 1; j < n; j++) {
            if (s[j] == '1')
                count++;
 
            if (count % 2 == 0
                && count != 0) {
                end = j;
                break;
            }
        }
 
        // Reverse the string from
        // starting and end index
        reverse(s.begin() + beg,
                s.begin() + end + 1);
    }
 
    // Printing the string
    cout << s << "\n";
}
 
// Driver Code
int main()
{
    string S = "0101";
    lexicographicallyMax(S);
 
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
import java.util.*;
 
class GFG{
     
// Function to find the lexicographically
// maximum string by reversing substrings
// having even numbers of 1s
static void lexicographicallyMax(String s)
{
     
    // Store size of string
    int n = s.length();
     
    // Traverse the string
    for(int i = 0; i < n; i++)
    {
         
        // Count the number of 1s
        int count = 0;
         
        // Stores the starting index
        int beg = i;
 
        // Stores the end index
        int end = i;
 
        // Increment count, when 1
        // is encountered
        if (s.charAt(i) == '1')
            count++;
             
        // Traverse the remaining string
        for(int j = i + 1; j < n; j++)
        {
            if (s.charAt(j) == '1')
                count++;
 
            if (count % 2 == 0 &&
                count != 0)
            {
                end = j;
                break;
            }
        }
         
        // Reverse the string from
        // starting and end index
        s = reverse(s, beg, end + 1);
    }
     
    // Printing the string
   System.out.println(s);
}
 
static String reverse(String s, int beg, int end)
{
    StringBuilder x = new StringBuilder("");
     
    for(int i = 0; i < beg; i++)
        x.append(s.charAt(i));
    for(int i = end - 1; i >= beg; i--)
        x.append(s.charAt(i));
    for(int i = end; i < s.length(); i++)
        x.append(s.charAt(i));
 
    return x.toString();
}
 
// Driver Code
public static void main(String args[])
{
    String S = "0101";
     
    lexicographicallyMax(S);
}
}
 
// This code is contributed by jyoti369

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
 
# Function to find the lexicographically
# maximum string by reversing substrings
# having even numbers of 1s
def lexicographicallyMax(s):
     
    # Store size of string
    n = len(s)
     
    # Traverse the string
    for i in range(n):
         
        # Count the number of 1s
        count = 0
 
        # Stores the starting index
        beg = i
 
        # Stores the end index
        end = i
         
        # Increment count, when 1
        # is encountered
        if (s[i] == '1'):
            count += 1
 
        # Traverse the remaining string
        for j in range(i + 1, n):
            if (s[j] == '1'):
                count += 1
                 
            if (count % 2 == 0 and count != 0):
                end = j
                break
                 
        # temp is for Reverse the string from
        # starting and end index
        temp = s[beg : end + 1]
        temp = temp[::-1]
        s = s[0 : beg] + temp + s[end + 1 :]
         
    # Printing the string
    print(s)
 
# Driver Code
S = "0101"
 
lexicographicallyMax(S)
 
# This code is contributed by avanitrachhadiya2155

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using System;
using System.Text;
class GFG
{
     
// Function to find the lexicographically
// maximum string by reversing substrings
// having even numbers of 1s
static void lexicographicallyMax(String s)
{
     
    // Store size of string
    int n = s.Length;
     
    // Traverse the string
    for(int i = 0; i < n; i++)
    {
         
        // Count the number of 1s
        int count = 0;
         
        // Stores the starting index
        int beg = i;
 
        // Stores the end index
        int end = i;
 
        // Increment count, when 1
        // is encountered
        if (s[i] == '1')
            count++;
             
        // Traverse the remaining string
        for(int j = i + 1; j < n; j++)
        {
            if (s[j] == '1')
                count++;
            if (count % 2 == 0 &&
                count != 0)
            {
                end = j;
                break;
            }
        }
         
        // Reverse the string from
        // starting and end index
        s = reverse(s, beg, end + 1);
    }
     
    // Printing the string
   Console.WriteLine(s);
}
 
static String reverse(String s, int beg, int end)
{
    StringBuilder x = new StringBuilder("");
     
    for(int i = 0; i < beg; i++)
        x.Append(s[i]);
    for(int i = end - 1; i >= beg; i--)
        x.Append(s[i]);
    for(int i = end; i < s.Length; i++)
        x.Append(s[i]);
 
    return x.ToString();
}
 
// Driver Code
public static void Main(String []args)
{
    String S = "0101";
    lexicographicallyMax(S);
}
}
 
 
// This code is contributed by Princi Singh

chevron_right


Output: 

1010

 

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

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :