mediumTwo PointersPattern: Mixed

Balanced Package Sequence Solution

Problem Statement

Given a sequence of characters, where 'L' represents a large package and 'S' represents a small package, find the length of the longest contiguous subsequence that contains an equal number of 'L' and 'S' packages and starts and ends with the same character.

Examples

Example 1:
Input:LLSS
Output:4
Explanation: The longest contiguous subsequence with an equal number of 'L' and 'S' packages is 'LLSS' itself.
Example 2:
Input:LSL
Output:0
Explanation: There is no contiguous subsequence with an equal number of 'L' and 'S' packages that starts and ends with the same package size.

Constraints

  • 1 <= length of the input string <= 1000
  • The input string only contains 'L' and 'S' characters.
Time: O(n) Space: O(1)
The optimal approach uses two pointers, one at the start and one at the end of the subsequence, and expands or contracts the subsequence as needed to maintain an equal number of 'L' and 'S' packages. This approach has a time complexity of O(n).

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.