Pages

Friday, 21 March 2025

Rearrange String: Move Vowels to the Beginning While Keeping Order

 


Problem Statement

Given a string s, rearrange the characters such that all vowels appear at the beginning, while maintaining the relative order of the consonants. The order of vowels should also remain the same as in the original string.

Example 1

Input: "automation"
Output: "auaotmtn"

Example 2

Input: "hello"
Output: "eo hll"

Example 3

Input: "java"
Output: "aa jv"


Solution Approach

  1. Extract vowels in order.

  2. Extract consonants in order.

  3. Concatenate vowels + consonants to form the result.


You can find the video here

Java Solution


public class MoveVowelsToLeft {

    public static String moveVowelsToLeft(String s) {

        StringBuilder vowels = new StringBuilder();

        StringBuilder consonants = new StringBuilder();

        

        for (char c : s.toCharArray()) {

            if (isVowel(c)) {

                vowels.append(c);

            } else {

                consonants.append(c);

            }

        }

        return vowels.append(consonants).toString();

    }


    private static boolean isVowel(char c) {

        return "AEIOUaeiou".indexOf(c) != -1;

    }


    public static void main(String[] args) {

        System.out.println(moveVowelsToLeft("automation")); // Output: auaotmtn

        System.out.println(moveVowelsToLeft("hello"));      // Output: eo hll

        System.out.println(moveVowelsToLeft("java"));       // Output: aa jv

    }

}



Time Complexity Analysis

  • O(n), where n is the length of the string (single pass to classify characters, another pass to concatenate).



- 𝗝𝗮𝘃𝗮 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗤&𝗔 𝗣𝗮𝗰𝗸𝗮𝗴𝗲: https://topmate.io/sidharth_shukla/1170024 - Learn Test Automation with 1:1 Guidance & Interview Preparation: https://lnkd.in/giCxnJJ7. HOLI Discount: Use Code 𝗦𝗜𝗗𝗛𝗔𝗥𝗧𝗛𝟭𝟬 to get 10% Discount (ONLY for first 10 enrollments): https://lnkd.in/giCxnJJ7 - 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗤&𝗔 𝗣𝗮𝗰𝗸𝗮𝗴𝗲 𝗳𝗼𝗿 𝗧𝗲𝘀𝘁 𝗔𝘂𝘁𝗼𝗺𝗮𝘁𝗶𝗼𝗻 & 𝗦𝗗𝗘𝗧: https://topmate.io/sidharth_shukla/605319

No comments:

Post a Comment