BackmediumTwo PointersAmazonTCS

Warehouse Packaging Solution

Problem Statement

Warehouse Packaging

You are given a string consisting solely of the characters 'L' (large) and 'S' (small). A contiguous subsequence of this string is called a valid segment if it contains an equal number of 'L' and 'S' packages and its first and last characters are identical. Your task is to determine the maximum possible length of a valid segment within the given string. If no such segment exists, the answer is 0.

Input: a single line containing the string. Output: a single integer representing the length of the longest valid segment.

Example 1
Input
LLSSLS
Output
4

Explanation: The substring from index 1 to 4 is "LSSL". It has 2 'L's and 2 'S's, starts with 'L' and ends with 'L', so its length is 4. No longer valid segment exists.

Example 2
Input
SLLS
Output
4

Explanation: The entire string "SLLS" has 2 'S's and 2 'L's, starts and ends with 'S', giving a length of 4.

Example 3
Input
LLLLSSSS
Output
0

Explanation: No contiguous substring has equal counts of 'L' and 'S' while also starting and ending with the same character, so the answer is 0.

Constraints

  • 1 <= string.length <= 100000
  • string contains only the characters 'L' and 'S'
  • time complexity must be O(n)
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

Warehouse Packaging — Problem Statement & Solution Guide

Two PointersMediumMixed
TimeO(N)
|
SpaceO(N)

Problem Description

Warehouse Packaging

You are given a string consisting solely of the characters 'L' (large) and 'S' (small). A contiguous subsequence of this string is called a *valid segment* if it contains an equal number of 'L' and 'S' packages and its first and last characters are identical. Your task is to determine the maximum possible length of a valid segment within the given string. If no such segment exists, the answer is 0.

Input: a single line containing the string.

Output: a single integer representing the length of the longest valid segment.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Warehouse Packaging"

medium

WHY DOES IT MATTER?

This pattern is essential for problems involving balanced sequences, such as parentheses matching, stock trading with transaction fees, or network flow balancing. It teaches the candidate to transform a string problem into a numerical one, leveraging the power of prefix sums to reduce the search space from O(N^2) to O(N).

OPTIMIZATION CHALLENGE

The key insight is to use a hash map to store the first occurrence of each prefix sum value. By iterating through the string once, you can check if the current prefix sum has been seen before. If it has, and the characters at the start and end of the segment are identical, you can update the maximum length. This reduces the time complexity from O(N^2) to O(N).

REAL-WORLD CONNECTION

In financial trading, this is analogous to finding the longest period where the net profit is zero, with the constraint that the starting and ending trade types are the same. In logistics, it helps in identifying the longest stretch of a delivery route where the number of pickups equals the number of drops, with the same type of vehicle at both ends.

During the interview, explicitly state that you are transforming the string into a prefix sum array. This shows you understand the underlying mathematical structure of the problem. Also, be careful with the boundary conditions: the prefix sum at index i-1 is compared with the prefix sum at index j, and the characters s[i] and s[j] must be identical.

COMPLEXITY AT A GLANCE

⏱ Time:O(N)
💾 Space:O(N)

Core Theory — Why This Approach?

The problem of finding the maximum length of a valid segment where the count of 'L' equals the count of 'S' and the first and last characters match is fundamentally a variation of the prefix sum and two-pointer technique. A naive approach would involve checking every possible substring, which results in O(N^3) or O(N^2) complexity, making it infeasible for large inputs (N > 10^5). The key insight is to transform the string into a numerical sequence where 'L' is +1 and 'S' is -1 (or vice versa). A valid segment [i, j] has an equal number of L and S if and only if the prefix sum at index j is equal to the prefix sum at index i-1. Additionally, the condition that the first and last characters are identical implies that s[i] == s[j].

Interview Questions on This Problem

Q1How would you modify your solution if the string contained three types of packages: 'L', 'M', and 'S', and the valid segment required equal counts of all three?

You would need to track a 3-dimensional prefix sum or use a hash map where the key is a tuple of the cumulative counts of L, M, and S. The two-pointer approach becomes less direct, and you would likely iterate through all pairs of indices with the same prefix count tuple, checking the boundary character condition. The complexity would increase, but the core idea of using prefix sums to identify balanced segments remains.

Q2In a distributed warehouse system, how would you handle the case where the string is too large to fit in memory, requiring a streaming approach?

You would process the string in chunks, maintaining a rolling prefix sum and a hash map of the last seen index for each prefix sum value. Since the condition requires the first and last characters to be identical, you would also need to track the last occurrence of each character type for each prefix sum. This allows you to compute the maximum length on the fly without storing the entire string, reducing space complexity to O(K) where K is the number of unique prefix sums.

Q3Can you prove that the optimal solution must involve a prefix sum approach rather than a sliding window?

A sliding window assumes that expanding the window monotonically increases or decreases the validity, which is not true here. The balance of L and S can fluctuate non-monotonically. Prefix sums, however, allow us to directly compare the state of the string at two different points in time. If the prefix sums are equal, the segment between them is balanced, regardless of the internal fluctuations. This makes prefix sums the natural choice for identifying balanced segments in a sequence.

Examples

Example 1

Input

LLSSLS

Output

4

Explanation: The substring from index 1 to 4 is "LSSL". It has 2 'L's and 2 'S's, starts with 'L' and ends with 'L', so its length is 4. No longer valid segment exists.

Example 2

Input

SLLS

Output

4

Explanation: The entire string "SLLS" has 2 'S's and 2 'L's, starts and ends with 'S', giving a length of 4.

Example 3

Input

LLLLSSSS

Output

0

Explanation: No contiguous substring has equal counts of 'L' and 'S' while also starting and ending with the same character, so the answer is 0.

Constraints

  • 1 <= string.length <= 100000
  • string contains only the characters 'L' and 'S'
  • time complexity must be O(n)

Optimal Approach & Strategy

Compute the prefix sum array where 'L' is +1 and 'S' is -1. Use a hash map to store the first index where each prefix sum value occurs. Iterate through the string, and for each index j, check if prefix[j] has been seen before at index i-1. If yes, and s[i] == s[j], update the maximum length.

Brute Force Approach

Iterate through all possible start and end indices (i, j) and check if the substring s[i..j] has an equal number of 'L' and 'S' and if s[i] == s[j]. This takes O(N^3) time due to the substring counting.

Verified Code Solutions

JavaScript Solution
Time: O(N)
function longestSubsequence(packages) {
    let maxLen = 0;
    let left = 0;
    let countL = 0;
    let countS = 0;

    for (let right = 0; right < packages.length; right++) {
        if (packages[right] === 'L') {
            countL++;
        } else {
            countS++;
        }

        while (countL > countS) {
            if (packages[left] === 'L') {
                countL--;
            } else {
                countS--;
            }
            left++;
        }

        if (countL === countS && (right === 0 || packages[right] === packages[0])) {
            maxLen = Math.max(maxLen, right - left + 1);
        }
    }
    return maxLen;
}

Asked in Top Tech Interviews

AmazonTCS

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.