


Ninja is given a binary string ‘S’ of size ‘N’ by his friend, 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. Since Ninja is busy with some work he is asking for your help. Can you help him?
Note:
A binary string is a string in which all characters are either ‘1’ or ‘0’.
The order is not strictly decreasing.
Input Format:
The first line contains an integer 'T' which denotes the number of test cases or queries to be run.
The first line of each test case contains a single integer ‘N’ denoting the size of the given string.
The second line of each test case contains the string ‘S’.
Output Format:
For each test case, If it is possible to sort the string in decreasing order, then print “true”, otherwise print “false”.
The output of each test case will be printed in a separate line.
Note:
You do not need to input or print anything, as it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 5
1 <= N <= 10 ^ 4
Where ‘T’ is the total number of test cases and ‘N’ is the size of the given string.
Time limit: 1 sec
2
7
1010101
4
0011
true
false
Test case 1:
We can remove the non-adjacent characters at indices 1, 3, 5 which modifies the string to “1111” which is sorted in non-increasing order. So we print “true”.
Test case 2:
We cannot sort the string in non-increasing order by removing adjacent characters so we print “false”.
2
4
1011
6
000000
true
true
Test case 1:
We can remove the non-adjacent character at indices 1,3,5 which modifies the string to “111” which is a sorted string in non-increasing order. So we print “true”.
Test case 2:
Since the String is already sorted in non-increasing order we print “true”.
If there exist two adjacent characters having 1s then what makes it impossible to sort the string in decreasing order by removing the non-adjacent characters.
The idea here is to use the fact that while traversing from the end if we encounter 2 consecutive 1s then we can sort the string in decreasing order if and only if after the index which we have found 2 consecutive 1s we have-
O(N), where ‘N’ is the given size of the given string.
As we will only be traversing the given string completely. Hence the overall time complexity is O (N).
O(1)
As we are not using any extra space hence the overall space complexity will be constant.