Check if both halves of the string have at least one different character

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)

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to check if
// both halves of the string have
// at least one different character
#include <cstring>
#include <iostream>
#include <string>
using namespace std;
# define MAX 26
  
// Function which break string into two halves
// Counts frequency of characters in each half
// Compares the two counter array and returns
// true if these counter arrays differ
bool function(string str)
{
    int l = str.length();
      
    // Declaration and initialization
    // of counter array
    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;
}
  
// Driver function
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;
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementaion of the problem
import java.util.*;
import java.lang.*;
  
class GeeksforGeeks {
    final static int MAX = 26;
  
    // Function which break string into two halves
    // Counts frequency of characters in each half
    // Compares the two counter array and returns
    // true if these counter arrays differ
    static boolean function(String str)
    {
        int l = str.length();
  
        // Declaration and initialization
        // of counter array
        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;
    }
  
    // Driver function
    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");
    }
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python implementation to check if
# both halves of the string have
# at least one different character
  
MAX = 26
  
# Function which break string into two halves
# Counts frequency of characters in each half
# Compares the two counter array and returns
# true if these counter arrays differ
def function(st):
    global MAX
    l = len(st)
      
    # Declaration and initialization
    # of counter array
    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
  
  
# Driver function
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")
  
# This code is contributed by Ansu Kumari
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation to check if
// both halves of the string have
// at least one different character
  
  
using System;
  
class GeeksforGeeks {
    static int MAX = 26;
  
    // Function which break string into two halves
    // Counts frequency of characters in each half
    // Compares the two counter array and returns
    // true if these counter arrays differ
    static bool function(String str)
    {
        int l = str.Length;
  
        // Declaration and initialization
        // of counter array
        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;
    }
  
    // Driver function
    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");
    }
}
  
//This code is contributed by vt_m.
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php 
// PHP implementation to check if
// both halves of the string have
// at least one different character
  
$MAX = 26;
   
// Function which break string into two halves
// Counts frequency of characters in each half
// Compares the two counter array and returns
// true if these counter arrays differ
function function_1($str)
{
    global $MAX;
    $l = strlen($str);
       
    // Declaration and initialization
    // of counter array
    $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;
}
   
// Driver function
  
$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;
?>
chevron_right


Output:

Yes, both halves differ by at least one character

Method 2:(One counter arrays)

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to check if
// both halves of the string have
// at least one different character
#include <cstring>
#include <iostream>
#include <string>
using namespace std;
# define MAX 26
  
// Function which break string into two halves
// Increments frequency of characters for first half
// Decrements frequency of characters for second half
// true if any index has non-zero value
bool function(string str)
{
    int l = str.length();
      
    // Declaration and initialization
    // of counter array
    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;
}
  
// Driver function
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;
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementaion of the problem
import java.util.*;
import java.lang.*;
  
class GeeksforGeeks {
  
    final static int MAX = 26;
  
    // Function which break string into two halves
    // Increments frequency of characters for first half
    // Decrements frequency of characters for second half
    // true if any index has non-zero value
    static boolean function(String str)
    {
        int l = str.length();
  
        // Declaration and initialization
        // of counter array
        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;
    }
  
    // Driver function
    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");
    }
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation to check if
# both halves of the string have
# at least one different character
MAX = 26
  
# Function which break string into two
# halves Increments frequency of characters
# for first half Decrements frequency of
# characters for second half true if any
# index has non-zero value
def function(st):
    global MAX
    l = len(st)
      
    # Declaration and initialization
    # of counter array
    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
  
# Driver function
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")
  
# This code is contributed by Ansu Kumari
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementaion of the problem
using System;
  
class GFG {
  
    static int MAX = 26;
  
    // Function which break string into 
    // two halves Increments frequency 
    // of characters for first half
    // Decrements frequency of characters
    // for second half true if any index
    // has non-zero value
    static bool function(String str)
    {
        int l = str.Length;
  
        // Declaration and initialization
        // of counter array
        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;
    }
  
    // Driver function
    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");
    }
}
  
// This code is contributed by anuj_67.
chevron_right

The time complexity of both the approaches is linear, i.e. O(len)
Method 3: (No extra space)

Follow the code below.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to check if
// both halves of the string have
// at least one different character
#include <algorithm>
#include <cstring>
#include <iostream>
#include <string>
using namespace std;
  
// Function which break string into two halves
// Sorts the two halves separately
// Compares the two halves
// return true if any index has non-zero value
bool function(char str[])
{
    int l = strlen(str);
  
    // Declaration and initialization
    // of counter array
    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;
}
  
// Driver function
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;
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation to check if
// both halves of the string have
// at least one different character
  
import java.io.*;
import java.util.*;
  
class GFG {
  
// Function which break string into two halves
// Sorts the two halves separately
// Compares the two halves
// return true if any index has non-zero value
static Boolean function(char str[])
{
    int l = str.length;
  
    // Declaration and initialization
    // of counter array
    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");
    }
}
  
// This code is contributed by Gitanjali.
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python implementation to check if
# both halves of the string have
# at least one different character
  
# Function which break string into two halves
# Sorts the two halves separately
# Compares the two halves
# return true if any index has non-zero value
def function(st):
    st = list(st)
    l = len(st)
  
    # Declaration and initialization
    # of counter array
    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
  
# Driver function
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")
  
# This code is contributed by Ansu Kumari
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation to check if
// both halves of the string have
// at least one different character
using System;
      
class GFG 
{
  
// Function which break string into two halves
// Sorts the two halves separately
// Compares the two halves
// return true if any index has non-zero value
static Boolean function(char []str)
{
    int l = str.Length;
  
    // Declaration and initialization
    // of counter array
    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;
}
  
// Driver code
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");
}
}
  
// This code contributed by Rajput-Ji
chevron_right

Output:

Yes, both halves differ by at least one character

The complexity of the above approach is O(len log (len))

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.




Recommended Posts:


Waba Laba Dub Dub

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Article Tags :
Practice Tags :