Find all words in given Sentence that are lexicographically increasing and lexicographically decreasing
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.
- words don’t containing numbers.
- words greater than size 1.
Input: str=”geeks for geeks”
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”
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.
1 "by" 3 "We" "won" "the"
Time Complexity: O(N^2)
Auxiliary Space: O(N)