mediumStringsPattern: Mixed

Alternating Sequence Length Solution

Problem Statement

Given a string `sequence` consisting of characters 'A' and 'B', determine the length of the longest subsequence where characters alternate between 'A' and 'B'.

Examples

Example 1:
Input:["XYXY"]
Output:4
Explanation: Characters alternate between 'X' and 'Y'
Example 2:
Input:["XXXX"]
Output:1
Explanation: Characters do not alternate between 'X' and 'Y'
Example 3:
Input:["XYYX"]
Output:2
Explanation: Characters do not alternate between 'X' and 'Y' after the first two characters

Constraints

  • 1 <= signal length <= 1000
  • Signal sequence consists only of 'X' (dot) and 'Y' (dash) characters.
Time: O(n) Space: O(1)
The optimal approach involves a single pass through the signal sequence, utilizing a variable to track the current sequence length and another to track the maximum length found, reducing the time complexity.

Run, Test & Submit Code

Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.

Solve on Interactive Workspace

Tested Solutions

No solution code is currently loaded.
Complete this code in the workspace editor.