Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

Check if any permutation of a given string is lexicographically larger than the other given string

  • Difficulty Level : Medium
  • Last Updated : 30 Sep, 2021

Given two strings str1 and str2 of same length N, the task is to check if there exists any permutation possible in any of the given strings, such that every character of one string is greater or equal to every character of the other string, at corresponding indices. Return true if permutation exists otherwise false.

Example:

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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: str1 = “adb”, str2 = “cda”
Output: true
Explanation: After permutation str1 = “abd” and str2 = “acd”, so every character from str2 is greater or equals to every character from s1.



Input: str1 = “gfg”, str2 = “agd”
Output: true

 

Approach: The above problem can be solved by sorting both the strings and then lexicographically comparing them. 
Follow the below steps to understand how:

Below is the implementation of above approach:

C++




// C++ implementation for the above approach
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
bool checkGreaterOrNot(string str1,
                       string str2)
{
    // Sorting both strings
    sort(str1.begin(), str1.end());
    sort(str2.begin(), str2.end());
   
    // Checking if any string
      //is greater or not
    bool flag = true;
   
    for (int i = 0; i < str1.length(); i++) {
        if (str1[i] < str2[i]) {
            flag = false;
            break;
        }
    }
   
    // If str1 is greater returning true
    if (flag)
        return true;
   
    flag = true;
    for(int i = 0; i < str2.length(); i++){
        if (str1[i] > str2[i]) {
            return false;
        }
    }
   
    // If str2 is greater returning true
    return true;
}
int main()
{
    string str1 = "adb";
    string str2 = "cda";
    bool ans =
      checkGreaterOrNot(str1, str2);
    if (ans) {
        cout << "true";
    }
    else {
        cout << "false";
    }
    return 0;
}
 
// This code is contributed by Kdheeraj.

Java




// Java implementation for the above approach
import java.io.*;
import java.util.*;
 
class GFG {
    public static boolean
    checkGreaterOrNot(String str1,
                      String str2)
    {
        // Sorting strings
        char[] arr1 = str1.toCharArray();
        Arrays.sort(arr1);
        char[] arr2 = str2.toCharArray();
        Arrays.sort(arr2);
        boolean flag = true;
 
        // str1 is greater
        // if it does not break the loop
        for (int i = 0; i < arr1.length; i++) {
            if (arr1[i] < arr2[i]) {
                flag = false;
                break;
            }
        }
 
        // If str1 is greater returning true
        if (flag)
            return true;
        flag = true;
 
        // If characters of str1 is greater
        // then none of the strings have all
        // corresponding characters greater
        // so return false
        for (int i = 0; i < arr2.length; i++) {
            if (arr1[i] > arr2[i]) {
                return false;
            }
        }
 
        // If str2 is greater returning true
        return true;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        String str1 = "adb";
        String str2 = "cda";
        boolean ans = checkGreaterOrNot(str1, str2);
        System.out.println(ans);
    }
}

Python3




# Python 3 implementation for the above approach
def checkGreaterOrNot(str1, str2):
   
    # Sorting both strings
    str1  = sorted(str1)
    str1 = "".join(str1)
    str2  = sorted(str2)
    str2 = "".join(str2)
   
    # Checking if any string
      #is greater or not
    flag = True
   
    for i in range(len(str1)):
        if(str1[i] < str2[i]):
            flag = False
            break
   
    # If str1 is greater returning true
    if (flag):
        return True
    flag = True
    for i in range(len(str2)):
        if (str1[i] > str2[i]):
            return False
   
    # If str2 is greater returning true
    return True
 
  # Driver code
if __name__ == '__main__':
    str1 = "adb"
    str2 = "cda"
    ans = checkGreaterOrNot(str1, str2)
    if (ans):
        print("true")
    else:
        print("false")
         
        # This code is contributed by ipg2016107.

C#




// C# implementation for the above approach
using System;
 
class GFG {
    public static bool checkGreaterOrNot(string str1,
                                         string str2)
    {
        // Sorting strings
        char[] arr1 = str1.ToCharArray();
        Array.Sort(arr1);
        char[] arr2 = str2.ToCharArray();
        Array.Sort(arr2);
        bool flag = true;
 
        // str1 is greater
        // if it does not break the loop
        for (int i = 0; i < arr1.Length; i++) {
            if (arr1[i] < arr2[i]) {
                flag = false;
                break;
            }
        }
 
        // If str1 is greater returning true
        if (flag)
            return true;
        flag = true;
 
        // If characters of str1 is greater
        // then none of the strings have all
        // corresponding characters greater
        // so return false
        for (int i = 0; i < arr2.Length; i++) {
            if (arr1[i] > arr2[i]) {
                return false;
            }
        }
 
        // If str2 is greater returning true
        return true;
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        string str1 = "adb";
        string str2 = "cda";
        bool ans = checkGreaterOrNot(str1, str2);
        Console.WriteLine(ans);
    }
}
 
// This code is contributed by ukasp.

Javascript




<script>
       // JavaScript Program to implement
       // the above approach
 
       function checkGreaterOrNot(str1,
           str2)
       {
        
           // Sorting both strings
           str1.sort(function (a, b) { return a.charCodeAt(0) - b.charCodeAt(0); });
           str2.sort(function (a, b) { return a.charCodeAt(0) - b.charCodeAt(0); });
            
           // Checking if any string
           //is greater or not
           let flag = true;
 
           for (let i = 0; i < str1.length; i++) {
               if (str1[i].charCodeAt(0) > str2[i].charCodeAt(0)) {
                   flag = false;
                   break;
               }
           }
 
           // If str1 is greater returning true
           if (flag)
               return true;
 
           flag = true;
           for (let i = 0; i < str2.length; i++) {
               if (str1[i].charCodeAt(0) > str2[i].charCodeAt(0)) {
                   return false;
               }
           }
 
           // If str2 is greater returning true
           return true;
       }
 
       let str1 = ['a', 'd', 'b'];
       let str2 = ['c', 'd', 'a']
       let ans =
           checkGreaterOrNot(str1, str2);
       if (ans) {
           document.write("true");
       }
       else {
           document.write("false");
       }
 
    // This code is contributed by Potta Lokesh
   </script>
Output: 
true

 

Time Complexity: O(n*log n)
Auxiliary Space: O(n)

Approach 2: The above approach can be optimized using frequency map for given strings.

  • Make frequency map for both the given strings
  • Create variables count1 and count2 to indicate cumulative frequency of respective strings
  • Iterate through frequency map and check if value for any string is greater than the other or not.
  • If yes, print true. Otherwise print false.

Below is the implementation of above approach:

C++




// C++ implementation for the above approach
#include <iostream>
#include <string>
using namespace std;
bool checkGreaterOrNot(string str1,
                       string str2)
{
    int arr1[26] = { 0 };
    int arr2[26] = { 0 };
 
    // Making frequency map for both strings
    for (int i = 0;
         i < str1.length(); i++) {
        arr1[str1[i] - 'a']++;
    }
    for (int i = 0;
         i < str2.length(); i++) {
        arr1[str2[i] - 'a']++;
    }
 
    // To check if any array
    // is greater to the other or not
    bool str1IsSmaller = false,
          str2IsSmaller = false;
 
    int count1 = 0, count2 = 0;
    for (int i = 0; i < 26; i++) {
        count1 += arr1[i];
        count2 += arr2[i];
 
        if (count1 > count2) {
 
         // None of the strings have
         // all corresponding characters
         // greater than other string
            if (str2IsSmaller)
                return false;
 
            str1IsSmaller = true;
        }
 
        if (count1 < count2) {
 
         // None of the strings have
         // all corresponding characters
         // greater than other string
            if (str1IsSmaller)
                return false;
 
            str2IsSmaller = true;
        }
    }
    return true;
}
 
// Driver code
int main()
{
    string str1 = "geeks";
    string str2 = "peeks";
    bool ans =
      checkGreaterOrNot(str1, str2);
    if (ans) {
        cout << "true";
    }
    else {
        cout << "false";
    }
}
 
// This code is contributed by Kdheeraj.

Java




// Java implementation for the above approach
import java.util.*;
 
class GFG {
 
    public static boolean checkGreaterOrNot(
        String str1, String str2)
    {
        int[] freq1 = new int[26];
        int[] freq2 = new int[26];
 
        // Making frequency map
        // for both strings
        for (int i = 0;
             i < str1.length(); i++) {
 
            freq1[str1.charAt(i) - 'a']++;
        }
 
        for (int i = 0;
             i < str2.length(); i++) {
            freq2[str2.charAt(i) - 'a']++;
        }
 
        boolean str1IsSmaller = false;
        boolean str2IsSmaller = false;
        int count1 = 0, count2 = 0;
 
        // Checking if any array
        // is strictly increasing or not
        for (int i = 0; i < 26; i++) {
 
            count1 += freq1[i];
            count2 += freq2[i];
            if (count1 > count2) {
 
                // None of the strings have
                // all corresponding characters
                // greater than other string
                if (str2IsSmaller)
                    return false;
 
                str1IsSmaller = true;
            }
            else if (count2 > count1) {
 
                // None of the strings have
                // all corresponding characters
                // greater than other string
                if (str1IsSmaller)
                    return false;
 
                str2IsSmaller = true;
            }
        }
        return true;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        String str1 = "geeks";
        String str2 = "peeks";
        boolean ans = checkGreaterOrNot(str1, str2);
        System.out.println(ans);
    }
}

C#




// C# program for the above approach
using System;
 
class GFG {
 
    public static bool checkGreaterOrNot(
        string str1, string str2)
    {
        int[] freq1 = new int[26];
        int[] freq2 = new int[26];
 
        // Making frequency map
        // for both strings
        for (int i = 0;
             i < str1.Length; i++) {
 
            freq1[str1[(i)] - 'a']++;
        }
 
        for (int i = 0;
             i < str2.Length; i++) {
            freq2[str2[(i)] - 'a']++;
        }
 
        bool str1IsSmaller = false;
        bool str2IsSmaller = false;
        int count1 = 0, count2 = 0;
 
        // Checking if any array
        // is strictly increasing or not
        for (int i = 0; i < 26; i++) {
 
            count1 += freq1[i];
            count2 += freq2[i];
            if (count1 > count2) {
 
                // None of the strings have
                // all corresponding characters
                // greater than other string
                if (str2IsSmaller)
                    return false;
 
                str1IsSmaller = true;
            }
            else if (count2 > count1) {
 
                // None of the strings have
                // all corresponding characters
                // greater than other string
                if (str1IsSmaller)
                    return false;
 
                str2IsSmaller = true;
            }
        }
        return true;
    }
 
    // Driver Code
    public static void Main()
    {
        string str1 = "geeks";
        string str2 = "peeks";
        bool ans = checkGreaterOrNot(str1, str2);
        Console.WriteLine(ans);
    }
}
 
// This code is contributed by avijitmondal1998.
Output: 
true

 

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




My Personal Notes arrow_drop_up
Recommended Articles
Page :