Code Logo

Find First Occurrence

Published at10 Jan 2026
Easy 33 views
Like12

Given a string, remove all vowel characters (a, e, i, o, u) both lowercase and uppercase, and return the resulting string with only consonants and non-letter characters remaining.

For example, removing vowels from "hello" produces "hll". From "AEIOU" produces "". From "xyz" produces "xyz". An empty string returns "".

Removing vowels is a simple text filtering operation that tests character-by-character iteration and conditional skipping. It is used in text analysis, word games, and creating abbreviations.

The solution defines a set of vowels and iterates through the string, building a result string that excludes any character found in the vowel set.

Edge cases include an empty string (return ""), a string with only vowels (return ""), a string with no vowels (return unchanged), and mixed case (both uppercase and lowercase vowels are removed).

Example Input & Output

Example 1
Input
haystack = "sadbutsad", needle = "sad"
Output
0
Explanation

"sad" occurs at index 0 and 6. The first occurrence is at index 0.

Example 2
Input
haystack = "leetcode", needle = "leeto"
Output
-1
Explanation

"leeto" did not occur in "leetcode", so we return -1.

Algorithm Flow

Recommendation Algorithm Flow for Find First Occurrence

Solution Approach

Iterate through the string and build a new string excluding vowels.

function removeVowels(s)
  vowels = set of "aeiouAEIOU"
  result = ""
  for i = 0 to length(s) - 1
    if s[i] not in vowels then result = result + s[i]
  return result

Create a set of vowel characters (both cases). Loop through each character. If the character is not in the vowel set, append it to the result. Return the filtered result.

Time complexity is O(n), space complexity is O(n) for the result.

Best Answers

java
class Solution {
    public String reverse_string_simple(String s) {
        return new StringBuilder(s).reverse().toString();
    }
}