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

All Time Popular Posts

Most Featured Post

Remove All Occurrences of a Given Character using Two Pointer Approach

  - ๐—œ๐—ป๐˜๐—ฒ๐—ฟ๐˜ƒ๐—ถ๐—ฒ๐˜„ ๐—ค&๐—” ๐—ฃ๐—ฎ๐—ฐ๐—ธ๐—ฎ๐—ด๐—ฒ ๐—ณ๐—ผ๐—ฟ ๐—ง๐—ฒ๐˜€๐˜ ๐—”๐˜‚๐˜๐—ผ๐—บ๐—ฎ๐˜๐—ถ๐—ผ๐—ป & ๐—ฆ๐——๐—˜๐—ง: https://topmate.io/sidharth_shukla/6053...