Alternating Sequence Length 2 ā Problem Statement & Solution Guide
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
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.
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
class Solution {
public int longestAlternatingSubsequence(String s) {
int max_length = 0;
int current_length = 0;
for (int i = 0; i < s.length() - 1; i++) {
if (s.charAt(i) != s.charAt(i + 1)) {
current_length++;
max_length = Math.max(max_length, current_length);
} else {
current_length = 0;
}
}
return max_length + 1;
}
}def longestAlternatingSubsequence(s: str) -> int:
max_length = 0
current_length = 0
for i in range(len(s) - 1):
if s[i] != s[i + 1]:
current_length += 1
max_length = max(max_length, current_length)
else:
current_length = 0
return max_length + 1Asked in Top Tech Interviews
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.