Sunday, October 12, 2025
HomeData Modelling & AICheck if a Binary String can be sorted in decreasing order by...

Check if a Binary String can be sorted in decreasing order by removing non-adjacent characters

Given a binary string S of size N, the task is to check if the binary string S can be sorted in decreasing order by removing any number of the non-adjacent characters. If it is possible to sort the string in decreasing order, then print “Yes”. Otherwise, print “No”.

Examples:

Input: S = “10101011011”
Output: Yes
Explanation:
After removing the non-adjacent characters at indices 1, 3, 5, and 8 modifies the string to “1111111”, which is sorted in decreasing order. Therefore, print “Yes”.

Input: S = “0011”
Output: No

Approach: The given problem can be solved based on the observations that if there exist two adjacent characters having 1s and then there exists adjacent characters having 0s then it is impossible to sort the string by removing the non-adjacent characters. Follow the steps below to solve the problem:

  • Initialize a boolean variable, say flag as true that stores the status whether the given string can be sorted or not.
  • Traverse the given string S from the end and if there exists any pairs of adjacent characters having values 1s then stored the second index of 1 in a variable say idx and break out of the loop.
  • Traverse the given string S again from the back over the range [idx, 0] and if there exists any pairs of adjacent characters having values 0s then update the value of flag as false and break out of the loop.
  • After completing the above steps, if the value of flag is true, then print “Yes”. Otherwise, print “No”.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to sort the given string in
// decreasing order by removing the non
// adjacent characters
string canSortString(string S, int N)
{
    // Keeps the track whether the
    // string can be sorted or not
    int flag = 1;
 
    int i, j;
 
    // Traverse the given string S
    for (i = N - 2; i >= 0; i--) {
 
        // Check if S[i] and
        // S[i + 1] are both '1'
        if (S[i] == '1'
            && S[i + 1] == '1') {
            break;
        }
    }
 
    // Traverse the string S from
    // the indices i to 0
    for (int j = i; j >= 0; j--) {
 
        // If S[j] and S[j + 1] is
        // equal to 0
        if (S[j] == '0'
            && S[j + 1] == '0') {
 
            // Mark flag false
            flag = 0;
            break;
        }
    }
 
    // If flag is 0, then it is not
    // possible to sort the string
    if (flag == 0) {
        return "No";
    }
 
    // Otherwise
    else {
        return "Yes";
    }
}
 
// Driver Code
int main()
{
    string S = "10101011011";
    int N = S.length();
    cout << canSortString(S, N);
 
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
 
class GFG
{
 
  // Function to sort the given string in
// decreasing order by removing the non
// adjacent characters
static String canSortString(String S, int N)
{
   
    // Keeps the track whether the
    // string can be sorted or not
    int flag = 1;
 
    int i, j;
 
    // Traverse the given string S
    for (i = N - 2; i >= 0; i--) {
 
        // Check if S[i] and
        // S[i + 1] are both '1'
        if (S.charAt(i) == '1'
            && S.charAt(i + 1) == '1') {
            break;
        }
    }
 
    // Traverse the string S from
    // the indices i to 0
    for ( j = i; j >= 0; j--) {
 
        // If S[j] and S[j + 1] is
        // equal to 0
        if (S.charAt(j) == '0'
            && S.charAt(j + 1) == '0') {
 
            // Mark flag false
            flag = 0;
            break;
        }
    }
 
    // If flag is 0, then it is not
    // possible to sort the string
    if (flag == 0) {
        return "No";
    }
 
    // Otherwise
    else {
        return "Yes";
    }
}
 
    public static void main (String[] args) {
      String S = "10101011011";
    int N = S.length();
    System.out.println(canSortString(S, N));
   
    }
}
 
// This code is contributed by offbeat


Python3




# Python3 program for the above approach
 
# Function to sort the given string in
# decreasing order by removing the non
# adjacent characters
def canSortString(S, N):
     
    # Keeps the track whether the
    # string can be sorted or not
    flag = 1
 
    # Traverse the given string S
    i = N - 2
     
    while(i >= 0):
         
        # Check if S[i] and
        # S[i + 1] are both '1'
        if (S[i] == '1' and S[i + 1] == '1'):
            break
         
        i -= 1
 
    # Traverse the string S from
    # the indices i to 0
    j = i
     
    while(j >= 0):
         
        # If S[j] and S[j + 1] is
        # equal to 0
        if (S[j] == '0' and S[j + 1] == '0'):
             
            # Mark flag false
            flag = 0
            break
         
        j -= 1
 
    # If flag is 0, then it is not
    # possible to sort the string
    if (flag == 0):
        return "No"
 
    # Otherwise
    else:
        return "Yes"
 
# Driver Code
if __name__ == '__main__':
     
    S = "10101011011"
    N = len(S)
     
    print(canSortString(S, N))
 
# This code is contributed by ipg2016107


C#




// C# program for the above approach
using System;
 
class GFG{
 
// Function to sort the given string in
// decreasing order by removing the non
// adjacent characters
static string canSortString(string S, int N)
{
     
    // Keeps the track whether the
    // string can be sorted or not
    int flag = 1;
 
    int i, j;
 
    // Traverse the given string S
    for(i = N - 2; i >= 0; i--)
    {
         
        // Check if S[i] and
        // S[i + 1] are both '1'
        if (S[i] == '1' && S[i + 1] == '1')
        {
            break;
        }
    }
 
    // Traverse the string S from
    // the indices i to 0
    for(j = i; j >= 0; j--)
    {
         
        // If S[j] and S[j + 1] is
        // equal to 0
        if (S[j] == '0' && S[j + 1] == '0')
        {
             
            // Mark flag false
            flag = 0;
            break;
        }
    }
 
    // If flag is 0, then it is not
    // possible to sort the string
    if (flag == 0)
    {
        return "No";
    }
 
    // Otherwise
    else
    {
        return "Yes";
    }
}
 
// Driver code
public static void Main(string[] args)
{
    string S = "10101011011";
    int N = S.Length;
     
    Console.WriteLine(canSortString(S, N));
}
}
 
// This code is contributed by ukasp


Javascript




<script>
// Javascript program for the above approach
 
// Function to sort the given string in
// decreasing order by removing the non
// adjacent characters
function canSortString(S, N)
{
    // Keeps the track whether the
    // string can be sorted or not
    let flag = 1;
 
    let i, j;
 
    // Traverse the given string S
    for (let i = N - 2; i >= 0; i--) {
 
        // Check if S[i] and
        // S[i + 1] are both '1'
        if (S[i] == '1'
            && S[i + 1] == '1') {
            break;
        }
    }
 
    // Traverse the string S from
    // the indices i to 0
    for (let j = i; j >= 0; j--) {
 
        // If S[j] and S[j + 1] is
        // equal to 0
        if (S[j] == '0'
            && S[j + 1] == '0') {
 
            // Mark flag false
            flag = 0;
            break;
        }
    }
 
    // If flag is 0, then it is not
    // possible to sort the string
    if (flag == 0) {
        return "No";
    }
 
    // Otherwise
    else {
        return "Yes";
    }
}
 
// Driver Code
    let S = "10101011011";
    let N = S.length;
    document.write(canSortString(S, N));
 
// This code is contributed by gfgking
</script>


Output: 

Yes

 

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

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32353 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6721 POSTS0 COMMENTS
Nicole Veronica
11885 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11943 POSTS0 COMMENTS
Shaida Kate Naidoo
6841 POSTS0 COMMENTS
Ted Musemwa
7105 POSTS0 COMMENTS
Thapelo Manthata
6797 POSTS0 COMMENTS
Umr Jansen
6798 POSTS0 COMMENTS