Given a string S, the task is to check if we can make the string lexicographically smaller by reversing any substring of the given string.
Examples:
Input: S = “striver”
Output: Yes
Reverse “rive” to get “stevirr” which is lexicographically smaller.
Input: S = “rxz”
Output: No
Approach: Iterate in the string and check if for any index s[i] > s[i + 1]. If there exists at least one such index, then it is possible else not.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool check(string &s)
{
int n = s.size();
for ( int i = 0; i < n - 1; i++) {
if (s[i] > s[i + 1])
return true ;
}
return false ;
}
int main()
{
string s = "geeksforgeeks" ;
if (check(s))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
class GFG
{
static boolean check(String s)
{
int n = s.length();
for ( int i = 0 ; i < n - 1 ; i++)
{
if (s.charAt(i) > s.charAt(i + 1 ))
return true ;
}
return false ;
}
public static void main(String args[])
{
String s = "geeksforgeeks" ;
if (check(s))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def check(s):
n = len (s)
for i in range (n - 1 ):
if (s[i] > s[i + 1 ]):
return True
return False
if __name__ = = '__main__' :
s = "geeksforgeeks"
if (check(s)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG
{
static bool check(String s)
{
int n = s.Length;
for ( int i = 0; i < n - 1; i++)
{
if (s[i] > s[i + 1])
return true ;
}
return false ;
}
public static void Main(String []args)
{
String s = "geeksforgeeks" ;
if (check(s))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
PHP
<?php
function check( $s )
{
$n = strlen ( $s );
for ( $i = 0; $i < $n - 1; $i ++)
{
if ( $s [ $i ] > $s [ $i + 1])
return true;
}
return false;
}
$s = "geeksforgeeks" ;
if (check( $s ))
echo "Yes" ;
else
echo "No" ;
?>
|
Javascript
<script>
function check(s)
{
let n = s.length;
for (let i = 0; i < n - 1; i++)
{
if (s[i] > s[i + 1])
return true ;
}
return false ;
}
let s = "geeksforgeeks" ;
if (check(s))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(N), where N is the length of the given string.
Auxiliary Space: O(1), as constant extra space is required.