Alternate Ingredient Sequence Length — Problem Statement & Solution Guide
Problem Description
Given a string of characters representing ingredient categories, determine the length of the longest subsequences that alternate between 'A' and 'B'.
Examples
Input
S-T-S
Output
2
Explanation: Step-by-step: The longest alternating subsequence 'S-T-S' has length 2. We can achieve this by considering the sequence as 'S-T' and then appending 'S' to it, resulting in a total length of 2.
Input
A-B-A-B
Output
4
Explanation: Step-by-step: The longest alternating subsequence 'A-B-A-B' has length 4. We can achieve this by considering the sequence as 'A-B-A-B', resulting in a total length of 4.
Constraints
- 1 <= input length <= 500
- The input string contains only 'S' and 'T' characters.
Optimal Approach & Strategy
The optimal approach uses dynamic programming to keep track of the longest alternating subsequences ending at each position, with a time complexity of O(n) and a space complexity of O(n).
Brute Force Approach
The brute-force approach would involve checking all possible subsequences of the input string, which has a time complexity of O(2^n).
Verified Code Solutions
class Solution {
public int longestAlternatingSubsequence(String s) {
int count = 0;
int max_count = 0;
for (int i = 0; i < s.length() - 1; i++) {
if (s.charAt(i) != s.charAt(i + 1)) {
count++;
max_count = Math.max(max_count, count);
} else {
count = 0;
}
}
return max_count + 1;
}
}def longestAlternatingSubsequence(s):
count = 0
max_count = 0
for i in range(len(s) - 1):
if s[i] != s[i + 1]:
count += 1
max_count = max(max_count, count)
else:
count = 0
return max_count + 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.