Sort an Array of Strings according to the number of Vowels in them

Given an array arr[] of N strings, the task is to sort these strings according to the numbers of vowels in them.

Examples:

Input: arr[] = { “geeks”, “for”, “coding” }
Output: for, coding, geeks
for -> o = 1 vowel
coding -> o, i = 2 vowels
geeks -> e, e = 2 vowels

Input: arr[] = { “lmno”, “pqrst”, “aeiou”, “xyz” }
Output: pqrst, xyz, lmno, aeiou

Approach: The idea is to store each element with its number of vowels in a vector pair and then sort all the elements of the vector according to the number of vowels stored. Finally, print the strings in order.

Below is the implementation of the above approach:

C++

 `// C++ implementation of the approach`   `#include ` `using` `namespace` `std;`   `// Function to check the Vowel` `bool` `isVowel(``char` `ch)` `{` `    ``ch = ``toupper``(ch);` `    ``return` `(ch == ``'A'` `|| ch == ``'E'` `            ``|| ch == ``'I'` `|| ch == ``'O'` `            ``|| ch == ``'U'``);` `}`   `// Returns count of vowels in str` `int` `countVowels(string str)` `{` `    ``int` `count = 0;` `    ``for` `(``int` `i = 0; i < str.length(); i++)` `        ``if` `(isVowel(str[i])) ``// Check for vowel` `            ``++count;` `    ``return` `count;` `}`   `// Function to sort the array according to` `// the number of the vowels` `void` `sortArr(string arr[], ``int` `n)` `{` `    ``// Vector to store the number of vowels` `    ``// with respective elements` `    ``vector > vp;`   `    ``// Inserting number of vowels` `    ``// with respective strings` `    ``// in the vector pair` `    ``for` `(``int` `i = 0; i < n; i++) {`   `        ``vp.push_back(` `            ``make_pair(` `                ``countVowels(` `                    ``arr[i]),` `                ``arr[i]));` `    ``}`   `    ``// Sort the vector, this will sort the pair` `    ``// according to the number of vowels` `    ``sort(vp.begin(), vp.end());`   `    ``// Print the sorted vector content` `    ``for` `(``int` `i = 0; i < vp.size(); i++)` `        ``cout << vp[i].second << ``" "``;` `}`   `// Driver code` `int` `main()` `{` `    ``string arr[] = { ``"lmno"``, ``"pqrst"``,` `                     ``"aeiou"``, ``"xyz"` `};` `    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr[0]);`   `    ``sortArr(arr, n);`   `    ``return` `0;` `}`

Java

 `// Java implementation of the approach ` `import` `java.util.*;` `import` `java.lang.*;` `import` `java.io.*;`   `class` `GFG{`   `static` `class` `pair` `{` `    ``int` `first;` `    ``String second;` `    `  `    ``pair(``int` `first,String second)` `    ``{` `        ``this``.first = first;` `        ``this``.second = second;` `    ``}` `}`   `// Function to check the Vowel` `static` `boolean` `isVowel(``char` `ch)` `{` `    ``ch = Character.toUpperCase(ch);` `    ``return` `(ch == ``'A'` `|| ch == ``'E'` `|| ` `            ``ch == ``'I'` `|| ch == ``'O'` `||` `            ``ch == ``'U'``);` `}`   `// Returns count of vowels in str` `static` `int` `countVowels(String str)` `{` `    ``int` `count = ``0``;` `    ``for``(``int` `i = ``0``; i < str.length(); i++)` `    `  `        ``// Check for vowel` `        ``if` `(isVowel(str.charAt(i))) ` `            ``++count;` `            `  `    ``return` `count;` `}`   `// Function to sort the array according to` `// the number of the vowels` `static` `void` `sortArr(String arr[], ``int` `n)` `{` `    `  `    ``// Vector to store the number of vowels` `    ``// with respective elements` `    ``ArrayList vp = ``new` `ArrayList<>();`   `    ``// Inserting number of vowels` `    ``// with respective strings` `    ``// in the vector pair` `    ``for``(``int` `i = ``0``; i < n; i++) ` `    ``{` `        ``vp.add(``new` `pair(countVowels(arr[i]),` `                                    ``arr[i]));` `    ``}`   `    ``// Sort the vector, this will sort the pair` `    ``// according to the number of vowels` `    ``Collections.sort(vp, (a, b) -> a.first - b.first);` `    `  `    ``// Print the sorted vector content` `    ``for``(``int` `i = ``0``; i < vp.size(); i++)` `        ``System.out.print(vp.get(i).second + ``" "``);` `}`   `// Driver code` `public` `static` `void` `main(String[] args) ` `{` `    ``String arr[] = { ``"lmno"``, ``"pqrst"``,` `                     ``"aeiou"``, ``"xyz"` `};` `    ``int` `n = arr.length;` `    `  `    ``sortArr(arr, n);` `}` `}`   `// This code is contributed by offbeat`

Python3

 `# Python3 implementation of the approach`   `# Function to check the Vowel` `def` `isVowel(ch) :` `    `  `    ``ch ``=` `ch.upper();` `    ``return` `(ch ``=``=` `'A'` `or` `ch ``=``=` `'E'``or` `ch ``=``=` `'I'` `or` `            ``ch ``=``=` `'O'``or` `ch ``=``=` `'U'``);`   `# Returns count of vowels in str` `def` `countVowels(string) :`   `    ``count ``=` `0``;` `    ``for` `i ``in` `range``(``len``(string)) :` `        `  `        ``# Check for vowel` `        ``if` `(isVowel(string[i])) : ` `            ``count ``+``=` `1``;` `            `  `    ``return` `count;`   `# Function to sort the array according to` `# the number of the vowels` `def` `sortArr(arr, n) :` `    `  `    ``# Vector to store the number of vowels` `    ``# with respective elements` `    ``vp ``=` `[];`   `    ``# Inserting number of vowels` `    ``# with respective strings` `    ``# in the vector pair` `    ``for` `i ``in` `range``(n) :`   `        ``vp.append((countVowels(arr[i]),arr[i]));`   `    ``# Sort the vector, this will sort the pair` `    ``# according to the number of vowels` `    ``vp.sort()`   `    ``# Print the sorted vector content` `    ``for` `i ``in` `range``(``len``(vp)) :` `        ``print``(vp[i][``1``], end``=` `" "``);`   `# Driver code` `if` `__name__ ``=``=` `"__main__"` `:` `    ``arr ``=` `[ ``"lmno"``, ``"pqrst"``,``"aeiou"``, ``"xyz"` `];` `    ``n ``=` `len``(arr);`   `    ``sortArr(arr, n);`   `# This code is contributed by AnkitRai01`

C#

 `// C# implementation of the approach` `using` `System;` `using` `System.Collections.Generic; ` `class` `GFG ` `{` `    `  `    ``// Function to check the Vowel` `    ``static` `bool` `isVowel(``char` `ch)` `    ``{` `        ``ch = ``char``.ToUpper(ch);` `        ``return` `(ch == ``'A'` `|| ch == ``'E'` `                ``|| ch == ``'I'` `|| ch == ``'O'` `                ``|| ch == ``'U'``);` `    ``}` `     `  `    ``// Returns count of vowels in str` `    ``static` `int` `countVowels(``string` `str)` `    ``{` `        ``int` `count = 0;` `        ``for` `(``int` `i = 0; i < str.Length; i++)` `            ``if` `(isVowel(str[i])) ``// Check for vowel` `                ``++count;` `        ``return` `count;` `    ``}` `     `  `    ``// Function to sort the array according to` `    ``// the number of the vowels` `    ``static` `void` `sortArr(``string``[] arr, ``int` `n)` `    ``{` `      `  `        ``// Vector to store the number of vowels` `        ``// with respective elements` `        ``List> vp = ``new` `List>();` `     `  `        ``// Inserting number of vowels` `        ``// with respective strings` `        ``// in the vector pair` `        ``for` `(``int` `i = 0; i < n; i++)` `        ``{  ` `            ``vp.Add(``new` `Tuple<``int``, ``string``>(countVowels(arr[i]), arr[i]));` `        ``}` `     `  `        ``// Sort the vector, this will sort the pair` `        ``// according to the number of vowels` `        ``vp.Sort();` `     `  `        ``// Print the sorted vector content` `        ``for` `(``int` `i = 0; i < vp.Count; i++)` `            ``Console.Write(vp[i].Item2 + ``" "``);` `    ``}` `     `  `  ``// Driver code` `  ``static` `void` `Main()` `  ``{` `    ``string``[] arr = { ``"lmno"``, ``"pqrst"``,` `                     ``"aeiou"``, ``"xyz"` `};` `    ``int` `n = arr.Length; ` `    ``sortArr(arr, n);` `  ``}` `}`   `// This code is contributed by divyesh072019`

Javascript

 ``

Output:

`pqrst xyz lmno aeiou`

Time Complexity: O(N*log N), for sorting the array.
Auxiliary Space: O(N), for storing the string in an extra array.

The approach sorts the input list of strings based on the number of vowels they contain using sorting function

C++

 `#include ` `#include ` `#include `   `using` `namespace` `std;`   `// Function to count the number of vowels in a word` `int` `countVowels(string word)` `{` `    ``// A string of all vowels` `    ``string vowels = ``"aeiouAEIOU"``;` `    ``int` `count = 0;` `    ``for` `(``int` `i = 0; i < word.length(); i++) {` `        ``// If the character is a vowel, increment the` `        ``// count` `        ``if` `(vowels.find(word[i]) != string::npos) {` `            ``count++;` `        ``}` `    ``}` `    ``return` `count;` `}`   `// Function to sort a vector of strings based on the` `// number of vowels in each string` `vector sortStrings(vector strings)` `{` `    ``// Sort the vector of strings based on the number of` `    ``// vowels in each string` `    ``sort(strings.begin(), strings.end(), [](``const` `string& s1, ``const` `string& s2) {` `        ``return` `countVowels(s1) < countVowels(s2);` `    ``});` `    ``return` `strings;` `}`   `// Main function` `int` `main()` `{` `    ``// Input vector of strings` `    ``vector strings = {``"lmno"``, ``"pqrst"``, ``"aeiou"``, ``"xyz"``};` `    ``// Sort the vector of strings` `    ``vector sortedStrings = sortStrings(strings);` `    ``// Print the sorted vector of strings` `    ``for` `(``const` `auto``& s : sortedStrings) {` `        ``cout << s << ``" "``;` `    ``}` `    ``cout << endl;` `    ``return` `0;` `}`

Java

 `import` `java.util.*;`   `public` `class` `GFG {` `    ``// Function to count the number of vowels in a word` `    ``public` `static` `int` `countVowels(String word)` `    ``{` `        ``// A string of all vowels` `        ``String vowels = ``"aeiouAEIOU"``;` `        ``int` `count = ``0``;` `        ``for` `(``int` `i = ``0``; i < word.length(); i++) {` `            ``// If the character is a vowel, increment the` `            ``// count` `            ``if` `(vowels.indexOf(word.charAt(i)) != -``1``) {` `                ``count++;` `            ``}` `        ``}` `        ``return` `count;` `    ``}`   `    ``// Function to sort a list of strings based on the` `    ``// number of vowels in each string` `    ``public` `static` `List` `    ``sortStrings(List strings)` `    ``{` `        ``// Sort the list of strings based on the number of` `        ``// vowels in each string` `        ``Collections.sort(strings, ``new` `Comparator() {` `            ``@Override` `            ``public` `int` `compare(String s1, String s2)` `            ``{` `                ``return` `countVowels(s1) - countVowels(s2);` `            ``}` `        ``});` `        ``return` `strings;` `    ``}`   `    ``// Main function` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``// Input list of strings` `        ``List strings = Arrays.asList(` `            ``"lmno"``, ``"pqrst"``, ``"aeiou"``, ``"xyz"``);` `        ``// Sort the list of strings` `        ``List sortedStrings = sortStrings(strings);` `        ``// Print the sorted list of strings` `        ``System.out.println(sortedStrings);` `    ``}` `}`

Python3

 `# Function to count the number of vowels in a word` `def` `count_vowels(word):` `    ``# A string of all vowels` `    ``vowels ``=` `"aeiouAEIOU"` `    ``# Return the count of vowels in the word` `    ``return` `sum``(c ``in` `vowels ``for` `c ``in` `word)`   `# Function to sort a list of strings based on the number of vowels in each string` `def` `sort_strings(strings):` `    ``# Sort the list of strings based on the number of vowels in each string` `    ``return` `sorted``(strings, key``=``count_vowels)`   `# Main function` `if` `__name__ ``=``=` `"__main__"``:` `    ``# Input list of strings` `    ``strings ``=` `[``"lmno"``, ``"pqrst"``, ``"aeiou"``, ``"xyz"``]` `    ``# Sort the list of strings` `    ``sorted_strings ``=` `sort_strings(strings)` `    ``# Print the sorted list of strings` `    ``print``(sorted_strings)`

C#

 `using` `System;` `using` `System.Collections.Generic;` `using` `System.Linq;`   `public` `class` `GFG` `{` `    ``// Function to count the number of vowels in a word` `    ``public` `static` `int` `CountVowels(``string` `word)` `    ``{` `        ``// A string of all vowels` `        ``string` `vowels = ``"aeiouAEIOU"``;` `        ``int` `count = 0;` `        ``for` `(``int` `i = 0; i < word.Length; i++)` `        ``{` `            ``// If the character is a vowel, increment the` `            ``// count` `            ``if` `(vowels.IndexOf(word[i]) != -1)` `            ``{` `                ``count++;` `            ``}` `        ``}` `        ``return` `count;` `    ``}`   `    ``// Function to sort a list of strings based on the` `    ``// number of vowels in each string` `    ``public` `static` `List<``string``>` `    ``SortStrings(List<``string``> strings)` `    ``{` `        ``// Sort the list of strings based on the number of` `        ``// vowels in each string` `        ``strings.Sort((s1, s2) => CountVowels(s1) - CountVowels(s2));` `        ``return` `strings;` `    ``}`   `    ``// Main function` `    ``public` `static` `void` `Main(``string``[] args)` `    ``{` `        ``// Input list of strings` `        ``List<``string``> strings = ``new` `List<``string``>` `        ``{` `            ``"lmno"``, ``"pqrst"``, ``"aeiou"``, ``"xyz"` `        ``};` `        ``// Sort the list of strings` `        ``List<``string``> sortedStrings = SortStrings(strings);` `        ``// Print the sorted list of strings` `        ``Console.WriteLine(``string``.Join(``" "``, sortedStrings));` `    ``}` `}`

Javascript

 `// Javascript program for the above approach`   `// Function to count the number of vowels in a word` `function` `count_vowels(word) {` `  ``// A string of all vowels` `  ``const vowels = ``"aeiouAEIOU"``;` `  ``// Return the count of vowels in the word` `  ``return` `Array.from(word).filter(c => vowels.includes(c)).length;` `}`   `// Function to sort a list of strings based on the number of vowels in each string` `function` `sort_strings(strings) {` `  ``// Sort the list of strings based on the number of vowels in each string` `  ``return` `strings.sort((a, b) => count_vowels(a) - count_vowels(b));` `}`   `// Main function` `const strings = [``"lmno"``, ``"pqrst"``, ``"aeiou"``, ``"xyz"``]; ``// Input list of strings` `const sorted_strings = sort_strings(strings); ``// Sort the list of strings` `console.log(sorted_strings); ``// Print the sorted list of strings`   `// This code is contributed by princekumaras`

Output

`['pqrst', 'xyz', 'lmno', 'aeiou']`

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

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Previous
Next