700591. Arrange Consonants and Vowels

Medium

Arrange Consonants and Vowels

Summary

Given a string, arrange all consonants followed by all vowels. The string may contain spaces and punctuation marks, which should be ignored. This problem involves manipulating a string and identifying consonants and vowels.

Detailed Explanation

The approach to this problem is to iterate through the given string, identify consonants and vowels, and then rearrange them accordingly. A simple way to do this is by maintaining two pointers, one for consonants and one for vowels. Initialize two linked lists: one for consonants and one for vowels.

Here's a step-by-step breakdown of the solution:

  1. Create an empty linked list for consonants (consonantList) and another for vowels (vowelList).
  2. Iterate through the given string:
    • Check if the current character is a consonant (using ASCII values or a helper function). If it's a consonant, add it to consonantList.
    • Check if the current character is a vowel (using ASCII values or a helper function). If it's a vowel, add it to vowelList.
  3. After iterating through the entire string, concatenate the consonantList and vowelList to form the final output string.

The time complexity of this solution is O(n), where n is the length of the input string. The space complexity is also O(n) due to the creation of the linked lists.

Optimized Solutions

Here are optimized solutions in various programming languages:

Java

View on GeeksforGeeks
import java.util.*;

public class Main {
    public static void main(String[] args) {
        String str = "Hello World";
        String consonants = "";
        String vowels = "";

        for (char c : str.toCharArray()) {
            if (!isVowel(c)) {
                consonants += c;
            } else {
                vowels += c;
            }
        }

        System.out.println(consonants + vowels);
    }

    public static boolean isVowel(char c) {
        c = Character.toLowerCase(c);
        return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.