Sort a String in decreasing order of values associated after removal of values smaller than X
Given an integer X and a string str consisting of space-separated texts and numbers placed alternately, the task is to sort the string such that texts and numbers appear in decreasing order of numbers associated after removal of all numbers less than X. If two strings have the same values then sort them in the lexicographic order of the string.
Input: X = 79, str = “Geek 78 for 99 Geeks 88 Gfg 86”
for 99 Geeks 88 Gfg 86
Explanation: “Even 99” is removed, since the number associated to it is smaller than X(= 79) Now, the reordered string string based on decreasing order of numbers associated is “Bob 99 Suzy 88 Alice 86”.
Input: X = 77, str = “Axc 78 Czt 60”
Output: Axc 78
Approach: The idea is to use the Bubble Sort technique. Follow the steps below to solve the problem:
- Split the string in to a list, then remove the entries that are less than the given value i.e. X.
- Sort the list based on the number associated with it using bubble sort method.
- If the numbers are not equal, sort the numbers in decreasing order and simultaneously sort the names.
- If the numbers are equal then sort them lexicographically.
- Swap both the strings and the number together in order to keep them together.
Below is the implementation of the above approach:
Time Complexity: O(N2)
Auxiliary Space: O(N)
Please Login to comment...