Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Find all words in given Sentence that are lexicographically increasing and lexicographically decreasing

  • Last Updated : 03 Dec, 2021

Given a string representing a sentence named str of size N, the task is to find all the valid words in a sentence that are lexicographically sorted in increasing order and in decreasing order along with their counts.

Note: Valid words are:-

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.

  • words don’t containing numbers.
  • words greater than size 1.

Examples:



Input: str=”geeks for geeks”
Output: 
1 “for”
0
Explanation: “for” is word which is lexicographically sorted in increasing order(1). There is no word which lexicographically sorted in decreasing order(0).

Input: str=”We won the match by 4 runs”
Output: 
1 “by”
3 “we”, “won”, “the”
Explanation: “by” is sorted in increasing order(1) whereas “we”, “won” and “the” are lexicographically sorted in decreasing order(3).

 

Approach: The idea to traverse the string word by word and check for each word if it is lexicographically increasing or lexicographically decreasing. Print each word based on the type found.

Follow below steps to know about the approach in detail: 

  • First traverse the words in given string and count the number of lexicographically increasing and lexicographically decreasing words, in count1 and count2 respectively.
  • Now first print the count of lexicographically increasing words stored in count1
  • Then traverse the string again word by word and print all lexicographically increasing words.
  • Repeat the last two steps for lexicographically decreasing words.

Below is the implementation of the above approach.

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if string is
// sorted in increasing order
bool issorted(string s)
{
    // using transform() function and ::tolower in STL
    transform(s.begin(), s.end(), s.begin(), ::tolower);
 
    for (int i = 0; i < s.size() - 1; i++) {
        if (s[i] > s[i + 1] or isdigit(s[i])) {
            return false;
        }
    }
    return true;
}
 
// Function to check ifstring is
// sorted in decreasing order
bool issortedre(string s)
{
    // using transform() function and ::tolower in STL
    transform(s.begin(), s.end(), s.begin(), ::tolower);
 
    for (int i = 0; i < s.size() - 1; i++) {
        if (s[i] < s[i + 1] or isdigit(s[i])) {
            return false;
        }
    }
    return true;
}
 
// Function to count
// the required absolute difference
void count(string s)
{
    stringstream ss(s);
    string word;
    int count1 = 0, count2 = 0;
 
    // Checking validity of word
    while (ss >> word) {
        if (word.size() == 1)
            continue;
 
        // Counting the valid words
        // in incresing order
        if (issorted(word)) {
            count1++;
        }
 
        // Counting the valid words
        // in decreasing order
        else if (issortedre(word)) {
            count2++;
        }
    }
 
    stringstream ss1(s);
 
    // Printing count of
    // lexicographically increasing words
    cout << count1 << " ";
 
    // Print all lexicographically
    // increasing words
    while (ss1 >> word) {
        if (word.size() == 1)
            continue;
 
        // Printing all valid words
        // in incresing order
        if (issorted(word)) {
            cout << "\"" << word << "\" ";
        }
    }
    cout << endl;
 
    stringstream ss2(s);
 
    // Printing count of
    // lexicographically increasing words
    cout << count2 << " ";
 
    // Print all lexicographically
    // increasing words
    while (ss2 >> word) {
        if (word.size() == 1)
            continue;
 
        // Printing all valid words
        // in decreasing order
        else if (issortedre(word)) {
            cout << "\"" << word << "\" ";
        }
    }
    cout << endl;
}
 
// Driver Code
int main()
{
    string s = "We won the match by 4 runs";
 
    count(s);
 
    return 0;
}


Python3




# Python Program to implement
# the above approach
def isCharNumber(c):
    return c >= '0' and c <= '9'
 
# Function to check if string is
# sorted in increasing order
def issorted(s):
 
    # using transform() function and ::tolower in STL
    s = s.lower()
 
    for i in range(len(s) - 1):
        if (ord(s[i]) > ord(s[i + 1]) or isCharNumber(s[i])):
            return False
    return True
 
# Function to check ifstring is
# sorted in decreasing order
def issortedre(s):
 
    # using transform() function and ::tolower in STL
    s = s.lower()
 
    for i in range(len(s) - 1):
        if (ord(s[i]) < ord(s[i + 1]) or isCharNumber(s[i])):
            return False
    return True
 
# Function to count
# the required absolute difference
def count(s):
 
    word = ""
    count1 = 0
    count2 = 0
    ss = s.split(" ")
 
    # Checking validity of word
    for i in range(len(ss)):
        word = ss[i]
        if (len(word) == 1):
            continue
 
        # Counting the valid words
        # in incresing order
        if (issorted(word)):
            count1 += 1
         
 
        # Counting the valid words
        # in decreasing order
        elif (issortedre(word)):
            count2 += 1
 
 
    # Printing count of
    # lexicographically increasing words
    print(count1, end=" ")
 
    # Print all lexicographically
    # increasing words
    for i in range(len(ss)):
        word = ss[i]
        if (len(word) == 1):
            continue
 
        # Printing all valid words
        # in incresing order
        if (issorted(word)):
            print(f" {word} ")
 
 
    # Printing count of
    # lexicographically increasing words
    print(count2, end=" ")
 
    # Print all lexicographically
    # increasing words
    for i in range(len(ss)):
        word = ss[i]
        if (len(word) == 1):
            continue
 
        # Printing all valid words
        # in decreasing order
        elif (issortedre(word)):
            print(f" {word} ", end=" ")
  
 
# Driver Code
s = "We won the match by 4 runs"
count(s)
 
# This code is contributed by gfgking


Javascript




<script>
 
       // JavaScript Program to implement
       // the above approach
 
       function isCharNumber(c) {
           return c >= '0' && c <= '9';
       }
        
       // Function to check if string is
       // sorted in increasing order
       function issorted(s)
       {
        
           // using transform() function and ::tolower in STL
           s = s.toLowerCase()
 
           for (let i = 0; i < s.length - 1; i++) {
               if (s[i].charCodeAt(0) > s[i + 1].charCodeAt(0) || isCharNumber(s[i])) {
                   return false;
               }
           }
           return true;
       }
 
       // Function to check ifstring is
       // sorted in decreasing order
       function issortedre(s)
       {
        
           // using transform() function and ::tolower in STL
           s = s.toLowerCase();
 
           for (let i = 0; i < s.length - 1; i++) {
               if (s[i].charCodeAt(0) < s[i + 1].charCodeAt(0) || isCharNumber(s[i])) {
                   return false;
               }
           }
           return true;
       }
 
       // Function to count
       // the required absolute difference
       function count(s) {
 
           let word;
           let count1 = 0, count2 = 0;
           let ss = s.split(" ");
 
           // Checking validity of word
           for (let i = 0; i < ss.length; i++) {
               word = ss[i]
               if (word.length == 1)
                   continue;
 
               // Counting the valid words
               // in incresing order
               if (issorted(word)) {
                   count1++;
               }
 
               // Counting the valid words
               // in decreasing order
               else if (issortedre(word)) {
                   count2++;
               }
           }
 
 
           // Printing count of
           // lexicographically increasing words
           document.write(count1 + " ");
 
           // Print all lexicographically
           // increasing words
           for (let i = 0; i < ss.length; i++) {
               word = ss[i];
               if (word.length == 1)
                   continue;
 
               // Printing all valid words
               // in incresing order
               if (issorted(word)) {
                   document.write(" " + word + " ")
               }
           }
           document.write('<br>');
 
           // Printing count of
           // lexicographically increasing words
           document.write(count2 + " ");
 
           // Print all lexicographically
           // increasing words
           for (let i = 0; i < ss.length; i++) {
               word = ss[i];
               if (word.length == 1)
                   continue;
 
               // Printing all valid words
               // in decreasing order
               else if (issortedre(word)) {
                   document.write(" " + word + " ")
               }
           }
           document.write('<br>');
       }
 
       // Driver Code
       let s = "We won the match by 4 runs";
       count(s);
 
   // This code is contributed by Potta Lokesh
   </script>


 
 

Output: 

1 "by" 
3 "We" "won" "the"

 

 

Time Complexity: O(N^2)
Auxiliary Space: O(N)

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!