Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Determine if String Halves Are Alike

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "1704" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

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 1: Input: s = "book" Output: true Explanation: a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike. Example 2: Input: s = "textbook" Output: false Explanation: a = "text" and b = "book". a has 1 vowel whereas b has 2. Therefore, they are not alike. Notice that the vowel o is counted twice. Constraints: 2 <= s.length <= 1000 s.length is even. s consists of uppercase and lowercase letters.

Explanation

Here's a solution to the problem:

  • Split and Count: Divide the input string into two halves. Iterate through each half, counting the number of vowels in each.
  • Compare Counts: Compare the vowel counts of the two halves. If they are equal, the strings are alike; otherwise, they are not.

  • Runtime Complexity: O(n), where n is the length of the string.

  • Storage Complexity: O(1)

Code

    def halvesAreAlike(s: str) -> bool:
    """
    Determines if the two halves of a string have the same number of vowels.
    """
    n = len(s)
    a = s[:n // 2]
    b = s[n // 2:]
    vowels = "aeiouAEIOU"
    count_a = 0
    count_b = 0
    for char in a:
        if char in vowels:
            count_a += 1
    for char in b:
        if char in vowels:
            count_b += 1
    return count_a == count_b

More from this blog

C

Chatmagic blog

2894 posts