BackmediumStringsAdobeAccenture

Alternating Sequence Length 2 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'.

Example 1
Input
AABABA
Output
3

Explanation: Step-by-step: We start with the input 'AABABA'. To find the longest alternating subsequence, we can divide it into 'AAB' and 'ABA' subsequences, both of length 3. Therefore, the output is 3.

Example 2
Input
BBAAB
Output
4

Explanation: Step-by-step: We start with the input 'BBAAB'. To find the longest alternating subsequence, we can divide it into 'BBA' and 'AAB' subsequences, both of length 4. Therefore, the output is 4.

Constraints

  • 1 <= signal length <= 1000
  • Signal sequence consists only of 'X' (dot) and 'Y' (dash) characters.
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

šŸš€ Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Alternating Sequence Length 2 — Problem Statement & Solution Guide

StringsMediumMixed
TimeO(n)
|
SpaceO(1)

Problem Description

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

AABABA

Output

3

Explanation: Step-by-step: We start with the input 'AABABA'. To find the longest alternating subsequence, we can divide it into 'AAB' and 'ABA' subsequences, both of length 3. Therefore, the output is 3.

Example 2

Input

BBAAB

Output

4

Explanation: Step-by-step: We start with the input 'BBAAB'. To find the longest alternating subsequence, we can divide it into 'BBA' and 'AAB' subsequences, both of length 4. Therefore, the output is 4.

Constraints

  • 1 <= signal length <= 1000
  • Signal sequence consists only of 'X' (dot) and 'Y' (dash) characters.

Optimal Approach & Strategy

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.

Brute Force Approach

The brute-force approach involves comparing every possible substring to determine if it alternates, resulting in a time complexity of O(n²). This is inefficient for large inputs. A naive approach might also involve unnecessary nested loops to check for alternation.

Verified Code Solutions

No solution currently available for JavaScript. Select another language tab above.

Asked in Top Tech Interviews

AdobeAccenture

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.