Open In App

Sort strings on the basis of their numeric part

Last Updated : 29 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a sentence S of size N where each word is a concatenation of a numeric part followed by a bunch of characters. The task is to arrange the words in increasing order of their numeric part.

Examples:

Input: S = “24-amazing 7-coders 11-are”
Output: coders are amazing
Explanation: order of numeric values are 7, 11, 24. 
So they are arranged accordingly

Input: S = “19-Love 10-I 2001-cricket”
Output: I Love cricket

 

Approach: The approach of the solution is based on the concept of min-heap. Split the strings on the basis of spaces and put them in the heap. At last pop them from the heap and print them in order. That will give the desired solution.

Below is the implementation of the above approach. 

C++
// C++ code to implement the approach
#include <bits/stdc++.h>
#include <boost/algorithm/string.hpp>
using namespace std;

// For arranging words on the basis
// of numeric part

// Function to arrange the sentence
string solve(string str)
{
    
    vector<string> arr;
    boost::split(arr, str, boost::is_any_of(" "));
    
    priority_queue<pair<int,string>> pq;
    for(int i = 0; i < arr.size(); i++)
    {
        string s = arr[i];
        string N = "";
        int a = 0;
        while(s[a] != '-')
        {
            N += s[a];
            a += 1;
        }
        int num = stoi(N);
        string word = arr[i].substr(a + 1);
        pq.push(make_pair(num, word));
    }
    
    string sb = "";
    while (0 < pq.size())
    {    sb = pq.top().second + " "+sb;
        pq.pop();
    }
    return sb;
}

// Driver code
int main()
{
    string S = "19-Love 10-I 2001-cricket";

    string ans = solve(S);
    cout<<ans;
}

// This code is contributed by Pushpesh raj
Java
// Java code to implement above approach
import java.util.*;

class GFG {

    // For arranging words on the basis
    // of numeric part
    public static class pair
        implements Comparable<pair> {

        int num;
        String word;

        pair(int num, String word)
        {
            this.num = num;
            this.word = word;
        }
        public int compareTo(pair o)
        {
            return this.num - o.num;
        }
    }

    // Function to arrange the sentence
    public static String solve(String str)
    {
        String[] arr = str.split(" ");
        PriorityQueue<pair> pq
            = new PriorityQueue<>();
        for (int i = 0; i < arr.length;
             i++) {
            String s = arr[i];
            String N = "";
            int a = 0;
            while (s.charAt(a) != '-') {
                N += s.charAt(a);
                a++;
            }
            int num = Integer.parseInt(N);
            String word = s.substring(a + 1);
            pq.add(new pair(num, word));
        }

        StringBuilder sb
            = new StringBuilder();
        while (pq.size() > 0) {
            pair p = pq.remove();
            sb.append(p.word);
            sb.append(" ");
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    // Driver code
    public static void main(String[] args)
    {
        String S = "19-Love 10-I 2001-cricket";

        String ans = solve(S);
        System.out.println(ans);
    }
}
Python
# python3 code for the above approach

# For arranging words on the basis
# of numeric part

# Function to arrange the sentence
def solve(str):
    arr = str.split(" ")

    pq = []
    for i in range(0, len(arr)):
        s = arr[i]
        N = ""
        a = 0
        while (s[a] != '-'):
            N += s[a]
            a += 1

        num = int(N)
        word = s[a + 1:]

        pq.append([num, word])

    pq.sort()

    sb = ""
    k = 0
    while (k < len(pq)):
        sb += pq[k][1] + " "
        k
        k += 1

    return sb

# Driver code
if __name__ == "__main__":

    S = "19-Love 10-I 2001-cricket"

    ans = solve(S)
    print(ans)

    # This code is contributed by rakeshsahni
C#
// C# code to implement above approach
using System;
using System.Text;
using System.Collections.Generic;

class GFG {

    // Pair class for arranging words based on numeric part
    public class pair : IComparable<pair> {
        public int num;
        public string word;

        public pair(int num, string word)
        {
            this.num = num;
            this.word = word;
        }

        public int CompareTo(pair other)
        {
            return this.num - other.num;
        }
    }

    // Function to arrange the sentence
    public static string solve(string str)
    {
        string[] arr = str.Split(" ");
        List<pair> pq = new List<pair>();
        for (int i = 0; i < arr.Length; i++)
        {
            string s = arr[i];
            string N = "";
            int a = 0;
            while (s[a] != '-')
            {
                N += s[a];
                a++;
            }
            int num = Convert.ToInt32(N);
            string word = s.Substring(a + 1);
            pq.Add(new pair(num, word));
        }

        pq.Sort();

        StringBuilder sb = new StringBuilder();
        foreach (pair p in pq)
        {
            sb.Append(p.word);
            sb.Append(" ");
        }
        sb.Remove(sb.Length - 1, 1);
        return sb.ToString();
    }

    // Driver code
    public static void Main(string[] args)
    {
        string S = "19-Love 10-I 2001-cricket";

        string ans = solve(S);
        Console.WriteLine(ans);
    }
}
JavaScript
 <script>
        // JavaScript code for the above approach 


        // For arranging words on the basis
        // of numeric part


        // Function to arrange the sentence
        function solve(str) {
            let arr = str.split(" ");

            let pq = []
            for (let i = 0; i < arr.length;
                i++) {
                let s = arr[i];
                let N = "";
                let a = 0;
                while (s.charAt(a) != '-') {
                    N += s.charAt(a);
                    a++;
                }
                let num = parseInt(N);
                let word = s.slice(a + 1);

                pq.push({ 'first': num, 'second': word });
            }
            pq.sort(function (a, b) { return a.first - b.first })

            let sb = "";
            let k = 0;
            while (k < pq.length) {
                sb += pq[k].second + " ";
                k++;
            }

            return sb
        }

        // Driver code
        let S = "19-Love 10-I 2001-cricket";

        let ans = solve(S);
        document.write(ans);

       // This code is contributed by Potta Lokesh
    </script>

 
 


Output
I Love cricket

Time Complexity: O(N log N)
Auxiliary Space: O(N)

Using lambda:

  • We split the sentence into words using the split() method, creating a list called words.
  • We sort the words list based on the numeric part of each word (before the hyphen -). We achieve this by using a lambda function as the key for the sorted() function. This lambda function extracts the numeric part of each word and converts it to an integer for proper numerical sorting.
  • We then join the sorted words by stripping off the numeric parts and returning only the character parts.
  • We use a list comprehension to split each word at the hyphen – and only return the second part (the character part).
  • Finally, we join these character parts into a single string using the join() method.
C++
#include <algorithm>
#include <iostream>
#include <sstream>
#include <vector>

struct Word {
    int number;
    std::string text;
};

// Function to split a string by a delimiter and return a
// vector of substrings
std::vector<std::string> split(const std::string& str,
                               char delimiter)
{
    std::vector<std::string> tokens;
    std::stringstream ss(str);
    std::string token;
    while (std::getline(ss, token, delimiter)) {
        tokens.push_back(token);
    }
    return tokens;
}

// Function to parse the input sentence into a vector of
// Word structs
std::vector<Word> parseSentence(const std::string& sentence)
{
    std::vector<Word> words;
    std::vector<std::string> parts = split(sentence, ' ');
    for (const auto& part : parts) {
        std::vector<std::string> wordParts
            = split(part, '-');
        if (wordParts.size() == 2) {
            Word word
                = { std::stoi(wordParts[0]), wordParts[1] };
            words.push_back(word);
        }
    }
    return words;
}

// Function to solve the problem
std::string solve(const std::string& sentence)
{
    std::vector<Word> words = parseSentence(sentence);

    // Sort the words based on the number
    std::sort(words.begin(), words.end(),
              [](const Word& a, const Word& b) {
                  return a.number < b.number;
              });

    // Join the words to form the resulting sentence
    std::stringstream result;
    for (size_t i = 0; i < words.size(); ++i) {
        if (i > 0)
            result << " ";
        result << words[i].text;
    }
    return result.str();
}

int main()
{
    // Given input
    std::string S = "19-Love 10-I 2001-cricket";

    // Function call
    std::cout << solve(S)
              << std::endl; // Output: I Love cricket

    return 0;
}

// This code is contributed by Akshita
Java
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

class Word {
    int number;
    String text;

    public Word(int number, String text)
    {
        this.number = number;
        this.text = text;
    }
}

public class Main {
    // Function to parse the input sentence into a list of
    // Word objects
    public static List<Word> parseSentence(String sentence)
    {
        List<Word> words = new ArrayList<>();
        String[] parts = sentence.split(" ");
        for (String part : parts) {
            String[] wordParts = part.split("-");
            if (wordParts.length == 2) {
                int number = Integer.parseInt(wordParts[0]);
                String text = wordParts[1];
                words.add(new Word(number, text));
            }
        }
        return words;
    }

    // Function to solve the problem
    public static String solve(String sentence)
    {
        List<Word> words = parseSentence(sentence);

        // Sort the words based on the number
        words.sort(Comparator.comparingInt(a -> a.number));

        // Join the words to form the resulting sentence
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < words.size(); ++i) {
            if (i > 0)
                result.append(" ");
            result.append(words.get(i).text);
        }
        return result.toString();
    }

    public static void main(String[] args)
    {
        // Given input
        String S = "19-Love 10-I 2001-cricket";

        // Function call
        System.out.println(
            solve(S)); // Output: I Love cricket
    }
}
Python
def solve(sentence):
    words = sentence.split(" ")
    sorted_words = sorted(words, key=lambda x: int(x.split("-")[0]))
    return " ".join(word.split("-")[1] for word in sorted_words)


# Given input
S = "19-Love 10-I 2001-cricket"

# Function Call
print(solve(S))
JavaScript
class Word {
    constructor(number, text) {
        this.number = number;
        this.text = text;
    }
}

// Function to parse the input sentence into a list of Word objects
function parseSentence(sentence) {
    const words = [];
    const parts = sentence.split(" ");
    for (const part of parts) {
        const wordParts = part.split("-");
        if (wordParts.length === 2) {
            const number = parseInt(wordParts[0]);
            const text = wordParts[1];
            words.push(new Word(number, text));
        }
    }
    return words;
}

// Function to solve the problem
function solve(sentence) {
    const words = parseSentence(sentence);

    // Sort the words based on the number
    words.sort((a, b) => a.number - b.number);

    // Join the words to form the resulting sentence
    return words.map(word => word.text).join(" ");
}

// Given input
const S = "19-Love 10-I 2001-cricket";

// Function call
console.log(solve(S)); // Output: I Love cricket

Output
I Love cricket

Time Complexity: O(N log N)

Space Complexity: O(N)



Next Article

Similar Reads