BackmediumStringsInfosysMicrosoft

Alternate Ingredient Sequence Length Solution

Problem Statement

Given a string of characters representing ingredient categories, determine the length of the longest subsequences that alternate between 'A' and 'B'.

Example 1
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.

Example 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.
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

Alternate Ingredient Sequence Length — Problem Statement & Solution Guide

StringsMediumMixed
TimeO(n)
|
SpaceO(1)

Problem Description

Given a string of characters representing ingredient categories, determine the length of the longest subsequences that alternate between 'A' and 'B'.

Examples

Example 1

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.

Example 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

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

Asked in Top Tech Interviews

InfosysMicrosoft

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.