Similar Problems

Similar Problems not available

Determine If String Halves Are Alike - Leetcode Solution

Companies:

LeetCode:  Determine If String Halves Are Alike Leetcode Solution

Difficulty: Easy

Topics: string  

Problem Statement:

You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half.

Two strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). Notice that s contains uppercase and lowercase letters.

Return true if a and b are alike. Otherwise, return false.

Example:

Input: s = "book" Output: true Explanation: a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike.

Solution:

In order to solve this problem, we need to count the number of vowels in both halves of the given string. Since the number of vowels in the string is not fixed, we cannot use an array to store the count of vowels. Therefore, we will use two separate count variables to keep track of the number of vowels in both halves of the string.

In the first step, we will split the given string into two halves a and b using the substring method in python. We can use the len() function to calculate the length of the string and then divide it by 2 to get the middle position of the string.

Then we will create a function called count_vowels to count the number of vowels in a given string. We will iterate through the string character by character, and if we encounter a vowel, we will increase the count of vowels.

Finally, in the main function, we will call the count_vowels function on both halves of the string, and if the count of vowels in both halves is the same, we will return True. Otherwise, we will return False.

Here is the Python code for the solution:

def count_vowels(s): count = 0 vowels = set('aeiouAEIOU') for char in s: if char in vowels: count += 1 return count

def halvesAreAlike(s: str) -> bool: n = len(s) a = s[:n//2] b = s[n//2:] return count_vowels(a) == count_vowels(b)

Time Complexity: O(N), where N is the length of the string s Space Complexity: O(1), as we are not using any extra space

This solution is efficient both in terms of time and space complexity. If you submit this solution on LeetCode, it will pass all test cases.

Determine If String Halves Are Alike Solution Code

1