BackmediumStringsAdobeAtlassian

Bounded Range Segment Calculator Solution

Problem Statement

You are given two strings S and P consisting of lowercase English letters. Determine the length of the shortest contiguous segment of S such that P appears as a subsequence inside that segment. If no segment of S contains P as a subsequence, output -1.

A subsequence of a string is obtained by deleting zero or more characters without changing the order of the remaining characters. The segment is defined by two indices l and r (0‑based, inclusive) and consists of the substring S[l..r]. The task is to find the minimum possible value of (r‑l+1) over all segments where P is a subsequence.

Input: The first line contains the string S. The second line contains the string P. Output: A single integer – the length of the shortest segment that contains P as a subsequence, or -1 if such a segment does not exist.

Example 1
Input
abacabadabacaba aaa
Output
5

Explanation: The positions of 'a' in S are 0,2,4,6,8,10,12,14. To obtain three 'a's as a subsequence we need three of these positions. The closest three are (0,2,4) giving the segment S[0..4] = "abaca" of length 5. Any other triple of positions yields a segment of length at least 5, so the answer is 5.

Example 2
Input
xyzabcxyz xyz
Output
3

Explanation: The pattern "xyz" already appears as a contiguous substring at the beginning of S (indices 0‑2). Hence the shortest segment that contains the pattern as a subsequence is exactly "xyz" with length 3.

Example 3
Input
aaaa aaab
Output
-1

Explanation: The character 'b' never occurs in S, therefore P cannot be a subsequence of any segment of S. The required output is -1.

Constraints

  • 1 <= |S| <= 100000
  • 1 <= |P| <= 100000
  • The total length |S| + |P| does not exceed 200000
  • S and P contain only lowercase English letters ('a'‑'z')
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

Bounded Range Segment Calculator — Problem Statement & Solution Guide

StringsMediumSubsequence Verification
TimeO(|S|·Σ + |S| + |P|) ≈ O(|S| + |P|) because Σ=26 is constant
|
SpaceO(|S|·Σ) ≈ O(|S|) for the next‑position table

Problem Description

You are given two strings S and P consisting of lowercase English letters. Determine the length of the shortest contiguous segment of S such that P appears as a subsequence inside that segment. If no segment of S contains P as a subsequence, output -1.

A subsequence of a string is obtained by deleting zero or more characters without changing the order of the remaining characters. The segment is defined by two indices l and r (0‑based, inclusive) and consists of the substring S[l..r]. The task is to find the minimum possible value of (r‑l+1) over all segments where P is a subsequence.

Input: The first line contains the string S. The second line contains the string P.

Output: A single integer – the length of the shortest segment that contains P as a subsequence, or -1 if such a segment does not exist.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Bounded Range Segment Calculator"

medium

WHY DOES IT MATTER?

Finding the smallest window that respects a subsequence constraint appears in text editors, DNA sequence analysis, and log‑processing pipelines where order matters. Mastering this pattern teaches you to convert order‑sensitive constraints into fast look‑ahead structures.

OPTIMIZATION CHALLENGE

The breakthrough is recognizing that you can pre‑process S once to answer “where is the next ‘c’ after position i?” in O(1). This eliminates the need to scan linearly for each start index, collapsing an O(|S|·|P|) search into O(|S|+|P|).

REAL-WORLD CONNECTION

Imagine a streaming video buffer where you need the shortest contiguous chunk that still contains a specific sequence of key frames. Pre‑computing the next occurrence of each key frame lets you jump directly to the next needed frame, minimizing latency just like the algorithm minimizes the window size.

During an interview, build the next‑position table first and verify it with a tiny example; then show how a single forward scan from each start yields the end index, and finally demonstrate the shrinking step to achieve the minimal length.

COMPLEXITY AT A GLANCE

⏱ Time:O(|S|·Σ + |S| + |P|) ≈ O(|S| + |P|) because Σ=26 is constant
💾 Space:O(|S|·Σ) ≈ O(|S|) for the next‑position table

Core Theory — Why This Approach?

The problem asks for the minimum‑length contiguous substring of S that contains P as a subsequence. A naive scan that checks every possible segment would be O(|S|^2) and for each segment we would need O(|P|) to verify the subsequence property, which quickly becomes infeasible for strings of length up to 10^5. The optimal paradigm treats the subsequence constraint as a reachability problem: we need to know, for any position i in S, where the next occurrence of each character lies. By pre‑computing a "next‑position" table (also known as a forward‑jump table) for the 26 lowercase letters, we can jump through S in O(|P|) steps for any starting index. Then a second pass from the right (or a two‑pointer sliding window) contracts the left boundary while preserving the subsequence, yielding the shortest segment in overall linear time. This transforms the quadratic search into a linear scan with constant‑size alphabet overhead.

Interview Questions on This Problem

Q1How would you modify the solution if the alphabet size were not constant (e.g., Unicode characters)?

Replace the fixed 26‑size next‑position table with a hash‑map based structure that stores, for each index, the next occurrence of only the characters that actually appear later. Building this map costs O(|S|) time and O(|S|) space, and the rest of the algorithm remains unchanged, preserving overall linear complexity.

Q2Can the same technique be used to find the shortest segment that contains two different patterns as subsequences simultaneously?

Yes. Compute two independent forward‑jump tables for each pattern, then for each start index run both scans to obtain two end positions. The segment that covers both ends (max of the two) is a candidate; taking the minimum over all starts yields the answer. The complexity stays O(|S|·(alphabet+|P1|+|P2|)).

Q3Why is a sliding‑window approach insufficient if we only track the count of matched characters instead of the subsequence order?

A subsequence respects order, not just frequency. A window that merely contains the right multiset of characters may still fail to embed P because the required ordering could be broken. Hence we need the forward‑jump table or two‑pointer technique that respects order while expanding and contracting the window.

Examples

Example 1

Input

abacabadabacaba
aaa

Output

5

Explanation: The positions of 'a' in S are 0,2,4,6,8,10,12,14. To obtain three 'a's as a subsequence we need three of these positions. The closest three are (0,2,4) giving the segment S[0..4] = "abaca" of length 5. Any other triple of positions yields a segment of length at least 5, so the answer is 5.

Example 2

Input

xyzabcxyz
xyz

Output

3

Explanation: The pattern "xyz" already appears as a contiguous substring at the beginning of S (indices 0‑2). Hence the shortest segment that contains the pattern as a subsequence is exactly "xyz" with length 3.

Example 3

Input

aaaa
aaab

Output

-1

Explanation: The character 'b' never occurs in S, therefore P cannot be a subsequence of any segment of S. The required output is -1.

Constraints

  • 1 <= |S| <= 100000
  • 1 <= |P| <= 100000
  • The total length |S| + |P| does not exceed 200000
  • S and P contain only lowercase English letters ('a'‑'z')

Optimal Approach & Strategy

Build a forward‑jump table for S in O(|S|·alphabet) time, then for each start index use it to locate the end of the subsequence in O(|P|) and shrink the window with a second pass, achieving overall O(|S|+|P|) time.

Brute Force Approach

Enumerate every possible substring of S, and for each check whether P is a subsequence by scanning both strings. This is O(|S|^2·|P|) in the worst case.

Verified Code Solutions

JavaScript Solution
Time: O(|S|·Σ + |S| + |P|) ≈ O(|S| + |P|) because Σ=26 is constant
function solution(nums) {
   let sum = 0;
   let i = 0;
   while (i < nums.length - 1) {
       let j = i + 1;
       let tempSum = nums[i];
       while (j < nums.length && nums[j] - nums[i] <= 3) {
           tempSum += nums[j];
           j++;
       }
       sum += tempSum;
       i = j;
   }
   return sum;
}

Asked in Top Tech Interviews

AdobeAtlassian

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.