Earlier we have discussed on how to check if both halves of the string have same set of characters. Now, we further extend our problem on checking if both halves of the string have at least one different character.
Examples:
Input : baaaab
Output: No, both halves do not differ at all
The two halves contain the same characters and their frequencies match so not different the character exists
Input : abccpb
Output : Yes, both halves differ by at least one character
Method 1: (Two counter arrays)
- Split the string into two halves
- Traverse two different halves separately and count the occurrence of each character into two different counter array
- Now, traverse these arrays, and the if these array differ at a point, we get the answer as “Yes”
Implementation:
C++
#include <cstring>
#include <iostream>
#include <string>
using namespace std;
# define MAX 26
bool function(string str)
{
int l = str.length();
int counter1[MAX];
int counter2[MAX];
memset (counter1, 0, sizeof (counter1));
memset (counter2, 0, sizeof (counter2));
for ( int i = 0; i < l / 2; i++)
counter1[str[i] - 'a' ]++;
for ( int i = l / 2; i < l; i++)
counter2[str[i] - 'a' ]++;
for ( int i = 0; i < MAX; i++)
if (counter2[i] != counter1[i])
return true ;
return false ;
}
int main()
{
string str = "abcasdsabcae" ;
if (function(str))
cout << "Yes, both halves differ"
<< " by at least one character" ;
else
cout << "No, both halves do "
<< "not differ at all" ;
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
class neveropen {
final static int MAX = 26 ;
static boolean function(String str)
{
int l = str.length();
int counter1[] = new int [MAX];
int counter2[] = new int [MAX];
for ( int i = 0 ; i < MAX; i++) {
counter1[i] = 0 ;
counter2[i] = 0 ;
}
for ( int i = 0 ; i < l / 2 ; i++)
counter1[str.charAt(i) - 'a' ]++;
for ( int i = l / 2 ; i < l; i++)
counter2[str.charAt(i) - 'a' ]++;
for ( int i = 0 ; i < MAX; i++) {
if (counter2[i] != counter1[i])
return true ;
}
return false ;
}
public static void main(String args[])
{
String str = "abcasdsabcae" ;
if (function(str))
System.out.print( "Yes, both halves " +
"differ by at least one character" );
else
System.out.print( "No, both halves " +
"do not differ at all" );
}
}
|
Python3
MAX = 26
def function(st):
global MAX
l = len (st)
counter1, counter2 = [ 0 ] * MAX , [ 0 ] * MAX
for i in range (l / / 2 ):
counter1[ ord (st[i]) - ord ( 'a' )] + = 1
for i in range (l / / 2 , l):
counter2[ ord (st[i]) - ord ( 'a' )] + = 1
for i in range ( MAX ):
if (counter2[i] ! = counter1[i]):
return True
return False
st = "abcasdsabcae"
if function(st): print ( "Yes, both halves differ " ,
"by at least one character" )
else : print ( "No, both halves do not differ at all" )
|
C#
using System;
class neveropen {
static int MAX = 26;
static bool function(String str)
{
int l = str.Length;
int []counter1 = new int [MAX];
int []counter2 = new int [MAX];
for ( int i = 0; i < MAX; i++)
{
counter1[i] = 0;
counter2[i] = 0;
}
for ( int i = 0; i < l / 2; i++)
counter1[str[i] - 'a' ]++;
for ( int i = l / 2; i < l; i++)
counter2[str[i] - 'a' ]++;
for ( int i = 0; i < MAX; i++) {
if (counter2[i] != counter1[i])
return true ;
}
return false ;
}
public static void Main()
{
String str = "abcasdsabcae" ;
if (function(str))
Console.WriteLine( "Yes, both halves " +
"differ by at least one character" );
else
Console.WriteLine( "No, both halves " +
"do not differ at all" );
}
}
|
PHP
<?php
$MAX = 26;
function function_1( $str )
{
global $MAX ;
$l = strlen ( $str );
$counter1 = array_fill (0, $MAX ,NULL);
$counter2 = array_fill (0, $MAX ,NULL);
for ( $i = 0; $i < $l / 2; $i ++)
$counter1 [ord( $str [ $i ]) - ord( 'a' )]++;
for ( $i = $l / 2; $i < $l ; $i ++)
$counter2 [ord( $str [ $i ]) - ord( 'a' )]++;
for ( $i = 0; $i < $MAX ; $i ++)
if ( $counter2 [ $i ] != $counter1 [ $i ])
return true;
return false;
}
$str = "abcasdsabcae" ;
if (function_1( $str ))
echo "Yes, both halves differ"
. " by at least one character" ;
else
echo "No, both halves do "
. "not differ at all" ;
return 0;
?>
|
Javascript
<script>
let MAX = 26;
function functions(str)
{
let l = str.length;
let counter1 = [];
let counter2 = [];
for (let i = 0; i < MAX; i++)
{
counter1[i] = 0;
counter2[i] = 0;
}
for (let i = 0; i < l / 2; i++)
counter1[str[i] - 'a' ]++;
for (let i = l / 2; i < l; i++)
counter2[str[i] - 'a' ]++;
for (let i = 0; i < MAX; i++) {
if (counter2[i] != counter1[i])
return true ;
}
return false ;
}
let str = "abcasdsabcae" ;
if (functions(str) != 1)
document.write( "Yes, both halves " +
"differ by at least one character" );
else
document.write( "No, both halves " +
"do not differ at all" );
</script>
|
Output
Yes, both halves differ by at least one character
Time Complexity: O(N), as we are using a loop to traverse N times. Where N is the length of the string.
Auxiliary Space: O(26), as we are using extra space for counter arrays.
Method 2:(One counter array)
- This method uses only a single array of length 26.
- For the first half, we increment the characters in the counter array of length 26.
- For second array, we decrement the character in that same counter array.
- Now, if for an index corresponding to a character has non-zero value, that is the distinct character present
- The positive ones are ones present in the first half and the negative ones are characters in the second half
Implementation:
C++
#include <cstring>
#include <iostream>
#include <string>
using namespace std;
# define MAX 26
bool function(string str)
{
int l = str.length();
int counter[MAX];
memset (counter, 0, sizeof (counter));
for ( int i = 0; i < l / 2; i++)
counter[str[i] - 'a' ]++;
for ( int i = l / 2; i < l; i++)
counter[str[i] - 'a' ]--;
for ( int i = 0; i < MAX; i++)
if (counter[i] != 0)
return true ;
return false ;
}
int main()
{
string str = "abcasdsabcae" ;
if (function(str))
cout << "Yes, both halves differ"
<< " by at least one character" ;
else
cout << "No, both halves do"
<< " not differ at all" ;
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
class neveropen {
final static int MAX = 26 ;
static boolean function(String str)
{
int l = str.length();
int counter[] = new int [MAX];
for ( int i = 0 ; i < MAX; i++)
counter[i] = 0 ;
for ( int i = 0 ; i < l / 2 ; i++)
counter[str.charAt(i) - 'a' ]++;
for ( int i = l / 2 ; i < l; i++)
counter[str.charAt(i) - 'a' ]--;
for ( int i = 0 ; i < MAX; i++)
if (counter[i] != 0 )
return true ;
return false ;
}
public static void main(String args[])
{
String str = "abcasdsabcae" ;
if (function(str))
System.out.print( "Yes, both halves"
+ " differ by at least one character" );
else
System.out.print( "No, both halves"
+ " do not differ at all" );
}
}
|
Python3
MAX = 26
def function(st):
global MAX
l = len (st)
counter = [ 0 ] * MAX
for i in range (l / / 2 ):
counter[ ord (st[i]) - ord ( 'a' )] + = 1
for i in range (l / / 2 , l):
counter[ ord (st[i]) - ord ( 'a' )] - = 1
for i in range ( MAX ):
if (counter[i] ! = 0 ):
return True
return False
st = "abcasdsabcae"
if function(st):
print ( "Yes, both halves differ by at " ,
"least one character" )
else :
print ( "No, both halves do not differ at all" )
|
C#
using System;
class GFG {
static int MAX = 26;
static bool function(String str)
{
int l = str.Length;
int []counter = new int [MAX];
for ( int i = 0; i < MAX; i++)
counter[i] = 0;
for ( int i = 0; i < l / 2; i++)
counter[str[i] - 'a' ]++;
for ( int i = l / 2; i < l; i++)
counter[str[i] - 'a' ]--;
for ( int i = 0; i < MAX; i++)
if (counter[i] != 0)
return true ;
return false ;
}
public static void Main()
{
string str = "abcasdsabcae" ;
if (function(str))
Console.Write( "Yes, both halves"
+ " differ by at least one "
+ "character" );
else
Console.Write( "No, both halves"
+ " do not differ at all" );
}
}
|
Javascript
<script>
let MAX = 26;
function Function(str)
{
let l = str.length;
let counter = new Array(MAX);
for (let i = 0; i < MAX; i++)
counter[i] = 0;
for (let i = 0; i < l / 2; i++)
counter[str[i].charCodeAt(0) - 'a' .charCodeAt(0)]++;
for (let i = Math.floor(l / 2); i < l; i++)
counter[str[i].charCodeAt(0) - 'a' .charCodeAt(0)]--;
for (let i = 0; i < MAX; i++)
if (counter[i] != 0)
return true ;
return false ;
}
let str = "abcasdsabcae" ;
if (Function(str))
document.write( "Yes, both halves"
+ " differ by at least one character" );
else
document.write( "No, both halves"
+ " do not differ at all" );
</script>
|
Output
Yes, both halves differ by at least one character
Time Complexity: O(N), as we are using a loop to traverse N times. Where N is the length of the string.
Auxiliary Space: O(26), as we are using extra space for counter array.
Method 3: (No extra space)
- Input the string in form of character array
- Sort the two strings separately
- Traverse the two halves together, if these differ at any point, return true
to the calling function
Implementation:
C++
#include <algorithm>
#include <cstring>
#include <iostream>
#include <string>
using namespace std;
bool function( char str[])
{
int l = strlen (str);
sort(str, str + (l / 2));
sort(str + (l / 2), str + l);
for ( int i = 0; i < l / 2; i++)
if (str[i] != str[l / 2 + i])
return true ;
return false ;
}
int main()
{
char str[] = "abcasdsabcae" ;
if (function(str))
cout << "Yes, both halves differ by"
<< " at least one character" ;
else
cout << "No, both halves do"
<< " not differ at all" ;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static Boolean function( char str[])
{
int l = str.length;
Arrays.sort(str, 0 , (l / 2 ));
Arrays.sort(str,(l / 2 ), l);
for ( int i = 0 ; i < l / 2 ; i++)
if (str[i] != str[l / 2 + i])
return true ;
return false ;
}
public static void main (String[] args) {
char str[] = ( "abcasdsabcae" ).toCharArray();
if (function(str))
System.out.println( "Yes, both halves differ"
+ " by at least one character" );
else
System.out.println( "No, both halves do"
+ " not differ at all" );
}
}
|
Python3
def function(st):
st = list (st)
l = len (st)
st[:l / / 2 ] = sorted (st[:l / / 2 ])
st[l / / 2 :] = sorted (st[l / / 2 :])
for i in range (l / / 2 ):
if (st[i] ! = st[l / / 2 + i]):
return True
return False
st = "abcasdsabcae"
if function(st): print ( "Yes, both halves differ " ,
"by at least one character" )
else : print ( "No, both halves do not differ at all" )
|
C#
using System;
class GFG
{
static Boolean function( char []str)
{
int l = str.Length;
Array.Sort(str, 0, (l / 2));
Array.Sort(str,(l / 2), l-(l/2));
for ( int i = 0; i < l / 2; i++)
if (str[i] != str[l / 2 + i])
return true ;
return false ;
}
public static void Main (String[] args)
{
char []str = ( "abcasdsabcae" ).ToCharArray();
if (function(str))
Console.WriteLine( "Yes, both halves differ"
+ " by at least one character" );
else
Console.WriteLine( "No, both halves do"
+ " not differ at all" );
}
}
|
Javascript
<script>
function Function(str)
{
let l = str.length;
str=(str.slice(0,Math.floor(l/2)).sort()).concat(str.slice(Math.floor(l/2),l).sort());
for (let i = 0; i < Math.floor(l / 2); i++)
if (str[i] != str[(Math.floor(l / 2) + i)])
return true ;
return false ;
}
let str= "abcasdsabcae" .split( "" );
if (Function(str))
document.write( "Yes, both halves differ"
+ " by at least one character" );
else
document.write( "No, both halves do"
+ " not differ at all" );
</script>
|
Output
Yes, both halves differ by at least one character
Time Complexity: O(N*logN), as we are using sorting
Auxiliary Space: O(1), as we are not using any extra space.
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!