LeetCode 1704: Determine if String Halves Are Alike Solution

Master LeetCode problem 1704 (Determine if String Halves Are Alike), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1704. Determine if String Halves Are Alike

Problem Explanation

Explanation

To solve this problem, we will iterate through the characters in the first and second halves of the string and count the number of vowels in each half. We will compare the counts at the end to determine if the two halves are alike.

  1. Initialize two variables vowelCountA and vowelCountB to keep track of the vowel counts in the first and second halves of the string.
  2. Iterate through the first half of the string and increment vowelCountA if the character is a vowel.
  3. Iterate through the second half of the string and increment vowelCountB if the character is a vowel.
  4. Check if vowelCountA is equal to vowelCountB. If they are equal, return true. Otherwise, return false.

Time Complexity

The time complexity of this approach is O(n), where n is the length of the input string s.

Space Complexity

The space complexity is O(1) as we are using a constant amount of extra space.

Solution Code

class Solution {
    public boolean halvesAreAlike(String s) {
        int vowelCountA = 0, vowelCountB = 0;
        String vowels = "aeiouAEIOU";

        for (int i = 0; i < s.length() / 2; i++) {
            if (vowels.indexOf(s.charAt(i)) != -1) {
                vowelCountA++;
            }
        }
        
        for (int i = s.length() / 2; i < s.length(); i++) {
            if (vowels.indexOf(s.charAt(i)) != -1) {
                vowelCountB++;
            }
        }
        
        return vowelCountA == vowelCountB;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1704 (Determine if String Halves Are Alike)?

This page provides optimized solutions for LeetCode problem 1704 (Determine if String Halves Are Alike) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1704 (Determine if String Halves Are Alike)?

The time complexity for LeetCode 1704 (Determine if String Halves Are Alike) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1704 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1704 in Java, C++, or Python.

Back to LeetCode Solutions