Table of Contents
Example
method 1
algorithm
Output
Method 2
Home Backend Development C++ 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

Sep 22, 2023 am 08:41 AM
Compare String arrangement Lexicographic order

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;
}
Copy after login

Output

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

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;
}
Copy after login

Output

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

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to enable nfc function on Xiaomi Mi 14 Pro? How to enable nfc function on Xiaomi Mi 14 Pro? Mar 19, 2024 pm 02:28 PM

Nowadays, the performance and functions of mobile phones are becoming more and more powerful. Almost all mobile phones are equipped with convenient NFC functions to facilitate users for mobile payment and identity authentication. However, some Xiaomi 14Pro users may not know how to enable the NFC function. Next, let me introduce it to you in detail. How to enable nfc function on Xiaomi 14Pro? Step 1: Open the settings menu of your phone. Step 2: Find and click the &quot;Connect and Share&quot; or &quot;Wireless &amp; Networks&quot; option. Step 3: In the Connection &amp; Sharing or Wireless &amp; Networks menu, find and click &quot;NFC &amp; Payments&quot;. Step 4: Find and click &quot;NFC Switch&quot;. Normally, the default is off. Step 5: On the NFC switch page, click the switch button to switch it to on.

How to use TikTok on Huawei Pocket2 remotely? How to use TikTok on Huawei Pocket2 remotely? Mar 18, 2024 pm 03:00 PM

Sliding the screen through the air is a feature of Huawei that is highly praised in the Huawei mate60 series. This feature uses the laser sensor on the phone and the 3D depth camera of the front camera to complete a series of functions that do not require The function of touching the screen is, for example, to use TikTok from a distance. But how should Huawei Pocket 2 use TikTok from a distance? How to take screenshots from the air with Huawei Pocket2? 1. Open the settings of Huawei Pocket2 2. Then select [Accessibility]. 3. Click to open [Smart Perception]. 4. Just turn on the [Air Swipe Screen], [Air Screenshot], and [Air Press] switches. 5. When using it, you need to stand 20~40CM away from the screen, open your palm, and wait until the palm icon appears on the screen.

How to set line spacing in WPS Word to make the document neater How to set line spacing in WPS Word to make the document neater Mar 20, 2024 pm 04:30 PM

WPS is our commonly used office software. When editing long articles, the fonts are often too small to be seen clearly, so the fonts and the entire document are adjusted. For example: adjusting the line spacing of the document will make the entire document very clear. I suggest that all friends learn this operation step. I will share it with you today. The specific operation steps are as follows, come and take a look! Open the WPS text file you want to adjust, find the paragraph setting toolbar in the [Start] menu, and you will see the small line spacing setting icon (shown as a red circle in the picture). 2. Click the small inverted triangle in the lower right corner of the line spacing setting, and the corresponding line spacing value will appear. You can choose 1 to 3 times the line spacing (as shown by the arrow in the figure). 3. Or right-click the paragraph and it will appear.

iPhone 16 Pro CAD drawings exposed, adding a second new button iPhone 16 Pro CAD drawings exposed, adding a second new button Mar 09, 2024 pm 09:07 PM

The CAD files of the iPhone 16 Pro have been exposed, and the design is consistent with previous rumors. Last fall, the iPhone 15 Pro added an Action button, and this fall, Apple appears to be planning to make minor adjustments to the size of the hardware. Adding a Capture button According to rumors, the iPhone 16 Pro may add a second new button, which will be the second consecutive year to add a new button after last year. It is rumored that the new Capture button will be set on the lower right side of the iPhone 16 Pro. This design is expected to make camera control more convenient and also allow the Action button to be used for other functions. This button will no longer be just an ordinary shutter button. Regarding the camera, from the current iP

How to switch language in microsoft teams How to switch language in microsoft teams Feb 23, 2024 pm 09:00 PM

There are many languages ​​to choose from in Microsoft Teams, so how to switch languages? Users need to click the menu, then find Settings, select General there, then click Language, select the language and save it. This introduction to switching language methods can tell you the specific content. The following is a detailed introduction. Take a look. Bar! How to switch language in Microsoft Teams Answer: Select the specific process in Settings-General-Language: 1. First, click the three dots next to the avatar to enter the settings. 2. Then click on the general options inside. 3. Then click on the language and scroll down to see more languages. 4. Finally, click Save and Restart.

How to set a custom ringtone for Redmi K70E? How to set a custom ringtone for Redmi K70E? Feb 24, 2024 am 10:00 AM

The Redmi K70E is undoubtedly excellent. As a mobile phone with a price of just over 2,000 yuan, the Redmi K70E can be said to be one of the most cost-effective mobile phones in its class. Many users who pursue cost-effectiveness have purchased this phone to experience various functions on Redmi K70E. So how to set a custom ringtone for Redmi K70E? How to set a custom ringtone for Redmi K70E? To set a custom incoming call ringtone for Redmi K70E, you can follow the steps below: Open the settings application of your phone, find the "Sounds and vibration" or "Sound" option in the settings application, and click "Incoming call ringtone" or "Phone ringtone" " option. In ringtone settings

The difference and comparative analysis between C language and PHP The difference and comparative analysis between C language and PHP Mar 20, 2024 am 08:54 AM

Differences and comparative analysis between C language and PHP C language and PHP are both common programming languages, but they have obvious differences in many aspects. This article will conduct a comparative analysis of C language and PHP and illustrate the differences between them through specific code examples. 1. Syntax and usage: C language: C language is a process-oriented programming language, mainly used for system-level programming and embedded development. The syntax of C language is relatively simple and low-level, can directly operate memory, and is efficient and flexible. C language emphasizes the programmer's completeness of the program

Comparison and analysis of advantages and disadvantages of PHP7.2 and 5 versions Comparison and analysis of advantages and disadvantages of PHP7.2 and 5 versions Feb 27, 2024 am 10:51 AM

Comparison and analysis of advantages and disadvantages of PHP7.2 and 5. PHP is an extremely popular server-side scripting language and is widely used in Web development. However, PHP is constantly being updated and improved in different versions to meet changing needs. Currently, PHP7.2 is the latest version, which has many noteworthy differences and improvements compared with the previous PHP5 version. In this article, we will compare PHP7.2 and PHP5 versions, analyze their advantages and disadvantages, and provide specific code examples. 1. Performance PH

See all articles