Sort an Array of Strings according to the number of Vowels in them
Last Updated :
09 Mar, 2023
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 <bits/stdc++.h>
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<pair<int, string> > 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<pair> 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<Tuple<int, string>> vp = new List<Tuple<int, string>>();
// 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
<script>
// JavaScript implementation of the approach
// Function to check the Vowel
function isVowel(ch)
{
ch = ch.toUpperCase();
return (ch == 'A' || ch == 'E'
|| ch == 'I' || ch == 'O'
|| ch == 'U');
}
// Returns count of vowels in str
function countVowels(str)
{
let count = 0;
for (let 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
function sortArr(arr, n)
{
// Vector to store the number of vowels
// with respective elements
let vp = [];
// Inserting number of vowels
// with respective strings
// in the vector pair
for (let i = 0; i < n; i++)
{
vp.push([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 (let i = 0; i < vp.length; i++)
document.write(vp[i][1] + " ");
}
let arr = [ "lmno", "pqrst", "aeiou", "xyz" ];
let n = arr.length;
sortArr(arr, n);
</script>
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 <iostream>
#include <vector>
#include <algorithm>
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<string> sortStrings(vector<string> 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<string> strings = {"lmno", "pqrst", "aeiou", "xyz"};
// Sort the vector of strings
vector<string> 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<String>
sortStrings(List<String> strings)
{
// Sort the list of strings based on the number of
// vowels in each string
Collections.sort(strings, new Comparator<String>() {
@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<String> strings = Arrays.asList(
"lmno", "pqrst", "aeiou", "xyz");
// Sort the list of strings
List<String> 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)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem