Check if String Is Decomposable Into Value-Equal Substrings - Problem

A value-equal string is a string where all characters are the same. For example, "1111" and "33" are value-equal strings. In contrast, "123" is not a value-equal string.

Given a digit string s, decompose the string into some number of consecutive value-equal substrings where exactly one substring has a length of 2 and the remaining substrings have a length of 3.

Return true if you can decompose s according to the above rules. Otherwise, return false.

A substring is a contiguous sequence of characters in a string.

Input & Output

Example 1 — Valid Decomposition
$ Input: s = "00111"
Output: true
💡 Note: We can decompose "00111" into "00" (length 2) and "111" (length 3). Exactly one substring has length 2.
Example 2 — Invalid Decomposition
$ Input: s = "01111"
Output: false
💡 Note: We cannot form value-equal substrings since '0' and '1' are different. Groups must contain identical characters.
Example 3 — Multiple Groups Invalid
$ Input: s = "000111"
Output: false
💡 Note: Both "000" and "111" have length 3, so we have zero groups of length 2, but we need exactly one.

Constraints

  • 1 ≤ s.length ≤ 1000
  • s consists only of digits

Visualization

Tap to expand
String Decomposition into Value-Equal Substrings INPUT String s = "00111" '0' idx 0 '0' idx 1 '1' idx 2 '1' idx 3 '1' idx 4 Value-Equal Groups: "00" len = 2 "111" len = 3 Requirements: - Exactly ONE substring of len 2 - All other substrings len 3 - All substrings value-equal - Cover entire string ALGORITHM STEPS 1 Initialize count=0, hasTwo=false 2 Count consecutive chars Group same characters i=0: '0' count=1 i=1: '0' count=2 (group ends) -- 2%3=2, set hasTwo=true i=2-4: '1' count=3 -- 3%3=0, valid group of 3 3 Check remainder count % 3: 0=valid, 2=pair 4 Verify exactly one pair Return hasTwo (must be true) If rem=1: invalid (can't make 1) FINAL RESULT Valid Decomposition Found: "00" len=2 + "111" len=3 Verification: [OK] One substring of length 2 [OK] Remaining have length 3 [OK] All value-equal [OK] Covers entire string Output: true Key Insight: For each group of consecutive equal characters, check count % 3: - If remainder = 0: perfect groups of 3 (valid) - If remainder = 2: one pair + groups of 3 (valid if only one pair total) - If remainder = 1: impossible to form valid groups (invalid) - Must have exactly one pair across all groups for true result TutorialsPoint - Check if String Is Decomposable Into Value-Equal Substrings | Single Pass with Mathematical Check
Asked in
Google 25 Microsoft 18
12.5K Views
Medium Frequency
~15 min Avg. Time
487 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