search
HomeBackend DevelopmentC++Checks whether any permutation of a given string is lexicographically greater than another given string

Checks whether any permutation of a given string is lexicographically greater than another given string

We have been given two strings and need to check if a permutation of the given string exists so that one permutation can have a greater value than the other permutation at the i-th index character of.

We can solve the problem by sorting the string and comparing each character in the string one by one. Alternatively, we can use the character frequencies of the two strings to solve the problem.

Problem Statement - We are given strings str1 and str2 of length N. We need to check if there are any permutations of strings such that one is lexicographically greater than the other. This means that any permutation should have a character at the i-th index that is greater than the character at the i-th index of another string permutation.

Example

Input - str1 = "aef"; str2 = "fgh";

Output–Yes

Explanation– ‘fgh’ is already larger than ‘aef’. Here, a > f, g > e, h > f.

Input– str1 = "adsm"; str2 = "obpc";

Output–No

Explanation– We cannot find any arrangement in which every character of one string is larger than the other.

method 1

In this method, we will sort two strings in lexicographic order. We will then compare each character of the string. Returns true if all characters of str1 are less than str2, or if all characters of str2 are less than str1. Otherwise, return false.

algorithm

  • Use the sort() method to sort strings.

  • Define the isStr1Greater Boolean variable and initialize it with true.

  • Traverse the string, and if the character at the i-th index position in str1 is less than str2, update the value of isStr1Greater to false, and use the break keyword to interrupt the loop

  • If isStr1Greater is true, the loop completes successfully and returns true.

  • Now, iterate over the string to check if str2 is greater than str1. If we find any character of str1 greater than str2, then return false.

  • Returns true if the loop completes successfully.

Example

#include <algorithm>
#include <iostream>
#include <string>
using namespace std;

bool isAnyPermLarge(string string1, string string2) {
   // sort the strings
   sort(string1.begin(), string1.end());
   sort(string2.begin(), string2.end());
   // to keep track if string1 is greater than string2
   bool isStr1Greater = true;
   // traverse the string
   for (int i = 0; i < string1.length(); i++) {
      // if any character of string1 is less than string2, return false.
      if (string1[i] < string2[i]) {
          isStr1Greater = false;
          break;
      }
   }
   // If string1 is greater, returning true
   if (isStr1Greater)
      return true;
   // traverse the string
   for (int i = 0; i < string2.length(); i++) {
      // if any character of string2 is less than string1, return false.
      if (string1[i] > string2[i]) {
          return false;
      }
   }
   // return true if string2 is greater than string1
   return true;
}
int main() {
   string string1 = "aef";
   string string2 = "fgh";
   bool res = isAnyPermLarge(string1, string2);
   if (res) {
      cout << "Yes, permutation exists such that one string is greater than the other.";
   } else {
      cout << "No, permutation does not exist such that one string is greater than the other.";
   }
   return 0;
}

Output

Yes, permutation exists such that one string is greater than the other.

Time complexity - O(N*logN), because we sort the strings.

Space Complexity - O(N) is required to sort the strings.

Method 2

In this method we will store the total frequency of each character in both strings. Afterwards, we will use the cumulative frequencies to decide if we can find any permutations of strings such that one is greater than the other.

algorithm

  • Define map1 and map2 arrays with a length of 26 and initialize them to zero.

  • Store the frequency of characters in str1 into map1, and store the frequency of characters in str2 into map2.

  • Define isStr1 and isStr2 Boolean variables and initialize them to false to track whether str1 is greater than str2.

  • Define cnt1 and cnt2 variables to store the cumulative frequency of string characters.

  • Traverse map1 and map2. Add map1[i] to cnt1 and map2[i] to cnt2.

  • If cnt1 is greater than cnt2, the cumulative frequency of characters from str1 to the i-th index is greater. If so, and str2 is already larger, return false. Otherwise, change isStr1 to true

  • If cnt2 is greater than cnt1, the cumulative frequency of the character at the i-th index in str2 is greater. If so, and str1 is already larger, return false. Otherwise, change isStr2 to true

  • Finally returns true.

Example

#include <iostream>
#include <string>
using namespace std;

bool isAnyPermLarge(string string1, string string2) {
   int map1[26] = {0};
   int map2[26] = {0};
   // store the frequency of each character in the map1
   for (int i = 0; i < string1.length(); i++) {
      map1[string1[i] - 'a']++;
   }
   // store the frequency of each character in the map2
   for (int i = 0; i < string2.length(); i++) {
      map2[string2[i] - 'a']++;
   }
   // To keep track of which string is smaller. Initially, both strings are equal.
   bool isStr1 = false, isStr2 = false;
   // to count the cumulative frequency of characters of both strings
   int cnt1 = 0, cnt2 = 0;
   // traverse for all characters.
   for (int i = 0; i < 26; i++) {
      // update the cumulative frequency of characters
      cnt1 += map1[i];
      cnt2 += map2[i];
      if (cnt1 > cnt2) {
          // If string2 is already greater and cumulative frequency of string1 is greater than string2, then return false
          if (isStr2)
              return false;
          // update isStr1 to true as string1 is smaller
          isStr1 = true;
      }
      if (cnt1 < cnt2) {
          // If string1 is already greater and cumulative frequency of string2 is greater than string1, then return false
          if (isStr1)
              return false;
          // update isStr2 to true as string2 is smaller
          isStr2 = true;
      }
   }
   return true;
}
int main() {
   string string1 = "aef";
   string string2 = "fgh";
   bool res = isAnyPermLarge(string1, string2);
   if (res) {
      cout << "Yes, permutation exists such that one string is greater than the other.";
   } else {
      cout << "No, permutation does not exist such that one string is greater than the other.";
   }
   return 0;
}

Output

Yes, permutation exists such that one string is greater than the other.

Time complexity - O(N), since we count the frequency of characters.

Space complexity - O(26), since we store the frequency of characters in the array.

We learned to check whether there is any permutation of two strings such that all characters of one string can be larger than the other string. The first method uses a sorting method, and the second method uses the cumulative frequency of characters.

The above is the detailed content of Checks whether any permutation of a given string is lexicographically greater than another given string. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
From XML to C  : Data Transformation and ManipulationFrom XML to C : Data Transformation and ManipulationApr 16, 2025 am 12:08 AM

Converting from XML to C and performing data operations can be achieved through the following steps: 1) parsing XML files using tinyxml2 library, 2) mapping data into C's data structure, 3) using C standard library such as std::vector for data operations. Through these steps, data converted from XML can be processed and manipulated efficiently.

C# vs. C  : Memory Management and Garbage CollectionC# vs. C : Memory Management and Garbage CollectionApr 15, 2025 am 12:16 AM

C# uses automatic garbage collection mechanism, while C uses manual memory management. 1. C#'s garbage collector automatically manages memory to reduce the risk of memory leakage, but may lead to performance degradation. 2.C provides flexible memory control, suitable for applications that require fine management, but should be handled with caution to avoid memory leakage.

Beyond the Hype: Assessing the Relevance of C   TodayBeyond the Hype: Assessing the Relevance of C TodayApr 14, 2025 am 12:01 AM

C still has important relevance in modern programming. 1) High performance and direct hardware operation capabilities make it the first choice in the fields of game development, embedded systems and high-performance computing. 2) Rich programming paradigms and modern features such as smart pointers and template programming enhance its flexibility and efficiency. Although the learning curve is steep, its powerful capabilities make it still important in today's programming ecosystem.

The C   Community: Resources, Support, and DevelopmentThe C Community: Resources, Support, and DevelopmentApr 13, 2025 am 12:01 AM

C Learners and developers can get resources and support from StackOverflow, Reddit's r/cpp community, Coursera and edX courses, open source projects on GitHub, professional consulting services, and CppCon. 1. StackOverflow provides answers to technical questions; 2. Reddit's r/cpp community shares the latest news; 3. Coursera and edX provide formal C courses; 4. Open source projects on GitHub such as LLVM and Boost improve skills; 5. Professional consulting services such as JetBrains and Perforce provide technical support; 6. CppCon and other conferences help careers

C# vs. C  : Where Each Language ExcelsC# vs. C : Where Each Language ExcelsApr 12, 2025 am 12:08 AM

C# is suitable for projects that require high development efficiency and cross-platform support, while C is suitable for applications that require high performance and underlying control. 1) C# simplifies development, provides garbage collection and rich class libraries, suitable for enterprise-level applications. 2)C allows direct memory operation, suitable for game development and high-performance computing.

The Continued Use of C  : Reasons for Its EnduranceThe Continued Use of C : Reasons for Its EnduranceApr 11, 2025 am 12:02 AM

C Reasons for continuous use include its high performance, wide application and evolving characteristics. 1) High-efficiency performance: C performs excellently in system programming and high-performance computing by directly manipulating memory and hardware. 2) Widely used: shine in the fields of game development, embedded systems, etc. 3) Continuous evolution: Since its release in 1983, C has continued to add new features to maintain its competitiveness.

The Future of C   and XML: Emerging Trends and TechnologiesThe Future of C and XML: Emerging Trends and TechnologiesApr 10, 2025 am 09:28 AM

The future development trends of C and XML are: 1) C will introduce new features such as modules, concepts and coroutines through the C 20 and C 23 standards to improve programming efficiency and security; 2) XML will continue to occupy an important position in data exchange and configuration files, but will face the challenges of JSON and YAML, and will develop in a more concise and easy-to-parse direction, such as the improvements of XMLSchema1.1 and XPath3.1.

Modern C   Design Patterns: Building Scalable and Maintainable SoftwareModern C Design Patterns: Building Scalable and Maintainable SoftwareApr 09, 2025 am 12:06 AM

The modern C design model uses new features of C 11 and beyond to help build more flexible and efficient software. 1) Use lambda expressions and std::function to simplify observer pattern. 2) Optimize performance through mobile semantics and perfect forwarding. 3) Intelligent pointers ensure type safety and resource management.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools