Determine if String Halves Are Alike - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: s = "AbCdEfGh"
Output: true
💡 Note: First half: "AbCd" has 1 vowel (A). Second half: "EfGh" has 1 vowel (E). Both halves have equal vowels, so return true.
Example 2 — Unequal Vowels
$ Input: s = "book"
Output: true
💡 Note: First half: "bo" has 1 vowel (o). Second half: "ok" has 1 vowel (o). Both halves have equal vowels, so return true.
Example 3 — No Vowels
$ Input: s = "textbook"
Output: false
💡 Note: First half: "text" has 1 vowel (e). Second half: "book" has 2 vowels (o, o). 1 ≠ 2, so return false.

Constraints

  • 2 ≤ s.length ≤ 1000
  • s.length is even
  • s consists of uppercase and lowercase letters

Visualization

Tap to expand
Determine if String Halves Are Alike INPUT String s = "AbCdEfGh" A b C d E f G h 0 1 2 3 4 5 6 7 Split into two halves: First Half (a) "AbCd" Second Half (b) "EfGh" Vowels to check: a, e, i, o, u A, E, I, O, U Input Values: s = "AbCdEfGh" length = 8 (even) ALGORITHM STEPS 1 Initialize Balance balance = 0 2 Single Pass Loop i from 0 to n/2-1 3 Update Balance +1 if s[i] is vowel -1 if s[n/2+i] is vowel 4 Check Result return balance == 0 Balance Tracking: i=0: s[0]='A'(v) s[4]='E'(v) +1-1=0 i=1: s[1]='b' s[5]='f' 0+0=0 i=2: s[2]='C' s[6]='G' 0+0=0 i=3: s[3]='d' s[7]='h' 0+0=0 Final balance = 0 FINAL RESULT Vowel Count Comparison: First Half "AbCd" Vowels: 1 Second Half "EfGh" Vowels: 1 = First half: 'A' (1 vowel) Second half: 'E' (1 vowel) OUTPUT true Halves are ALIKE! 1 == 1 (balance = 0) OK Key Insight: Instead of counting vowels separately for each half, use a single balance counter. Increment for vowels in first half, decrement for second half. If balance = 0, halves are alike. Time: O(n/2) = O(n), Space: O(1) - single pass with constant space! TutorialsPoint - Determine if String Halves Are Alike | Single Pass with Balance Counter
Asked in
Facebook 15 Amazon 12
30.5K Views
Medium Frequency
~8 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen