LeetCode #3775 — MEDIUM

Reverse Words With Same Vowel Count

Move from brute-force thinking to an efficient approach using two pointers strategy.

Solve on LeetCode
The Problem

Problem Statement

You are given a string s consisting of lowercase English words, each separated by a single space.

Determine how many vowels appear in the first word. Then, reverse each following word that has the same vowel count. Leave all remaining words unchanged.

Return the resulting string.

Vowels are 'a', 'e', 'i', 'o', and 'u'.

Example 1:

Input: s = "cat and mice"

Output: "cat dna mice"

Explanation:​​​​​​​

  • The first word "cat" has 1 vowel.
  • "and" has 1 vowel, so it is reversed to form "dna".
  • "mice" has 2 vowels, so it remains unchanged.
  • Thus, the resulting string is "cat dna mice".

Example 2:

Input: s = "book is nice"

Output: "book is ecin"

Explanation:

  • The first word "book" has 2 vowels.
  • "is" has 1 vowel, so it remains unchanged.
  • "nice" has 2 vowels, so it is reversed to form "ecin".
  • Thus, the resulting string is "book is ecin".

Example 3:

Input: s = "banana healthy"

Output: "banana healthy"

Explanation:

  • The first word "banana" has 3 vowels.
  • "healthy" has 2 vowels, so it remains unchanged.
  • Thus, the resulting string is "banana healthy".

Constraints:

  • 1 <= s.length <= 105
  • s consists of lowercase English letters and spaces.
  • Words in s are separated by a single space.
  • s does not contain leading or trailing spaces.
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: You are given a string s consisting of lowercase English words, each separated by a single space. Determine how many vowels appear in the first word. Then, reverse each following word that has the same vowel count. Leave all remaining words unchanged. Return the resulting string. Vowels are 'a', 'e', 'i', 'o', and 'u'.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Two Pointers

Example 1

"cat and mice"

Example 2

"book is nice"

Example 3

"banana healthy"
Step 02

Core Insight

What unlocks the optimal approach

  • Simulate as described
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3775: Reverse Words With Same Vowel Count
class Solution {
    public String reverseWords(String s) {
        String[] words = s.split("\\s+");

        int cnt = calc(words[0]);
        List<String> ans = new ArrayList<>();
        ans.add(words[0]);

        for (int i = 1; i < words.length; i++) {
            String w = words[i];
            if (calc(w) == cnt) {
                ans.add(new StringBuilder(w).reverse().toString());
            } else {
                ans.add(w);
            }
        }
        return String.join(" ", ans);
    }

    private int calc(String w) {
        int res = 0;
        for (char c : w.toCharArray()) {
            if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
                res++;
            }
        }
        return res;
    }
}
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n)
Space
O(n)

Approach Breakdown

BRUTE FORCE
O(n²) time
O(1) space

Two nested loops check every pair of elements. The outer loop picks one element, the inner loop scans the rest. For n elements that is n × (n−1)/2 comparisons = O(n²). No extra memory — just two loop variables.

TWO POINTERS
O(n) time
O(1) space

Each pointer traverses the array at most once. With two pointers moving inward (or both moving right), the total number of steps is bounded by n. Each comparison is O(1), giving O(n) overall. No auxiliary data structures are needed — just two index variables.

Shortcut: Two converging pointers on sorted data → O(n) time, O(1) space.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Moving both pointers on every comparison

Wrong move: Advancing both pointers shrinks the search space too aggressively and skips candidates.

Usually fails on: A valid pair can be skipped when only one side should move.

Fix: Move exactly one pointer per decision branch based on invariant.