BackmediumStringsAtlassianSwiggy

Balanced Tree Span Calculator 6 Solution

Problem Statement

Given a string s consisting of lowercase English letters, determine the length of the longest contiguous substring that is a subsequence of a specific target pattern t. A subsequence is defined as a sequence that can be derived from another sequence by deleting zero or more elements without changing the order of the remaining elements. You must identify the maximum window size in s where the characters appear in t in the same relative order.

The input consists of two strings: s (the source string to scan) and t (the target pattern). The output is a single integer representing the maximum length of such a valid subsequence window found within s. If no valid subsequence of length greater than 0 exists, return 0.

This problem requires efficient verification of subsequence properties within sliding windows or via dynamic programming to handle large input sizes effectively. The solution must account for the non-contiguous nature of subsequences while maximizing the span of matched characters.

Example 1
Input
s = "abcde", t = "ace"
Output
3

Explanation: The entire string "abcde" contains the subsequence "ace" (indices 0, 2, 4 in s). The length of this subsequence is 3. No longer subsequence of t exists in s. Thus, the answer is 3.

Example 2
Input
s = "xyz", t = "abc"
Output
0

Explanation: None of the characters in s ('x', 'y', 'z') appear in t ('a', 'b', 'c') in any order. Therefore, no valid subsequence exists, and the maximum length is 0.

Example 3
Input
s = "abab", t = "ba"
Output
2

Explanation: We look for the longest subsequence of s that matches t. The subsequence "ba" can be formed by taking 'b' at index 1 and 'a' at index 2 of s. The length is 2. Another instance is 'b' at index 3 and no 'a' after it, so length 1. The maximum is 2.

Example 4
Input
s = "aabbcc", t = "abc"
Output
3

Explanation: The subsequence "abc" is present in s. We can pick 'a' at index 0, 'b' at index 2, and 'c' at index 4. The length is 3. This is the maximum possible length since t has length 3.

Constraints

  • 1 <= s.length <= 10^5
  • 1 <= t.length <= 10^5
  • s and t consist of lowercase English letters only
  • The total number of test cases is not specified, but the solution must run in O(n*m) or better for each test case
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

Balanced Tree Span Calculator 6 — Problem Statement & Solution Guide

StringsMediumSubsequence Verification
TimeO(|s| + |t|·Σ) where Σ=26 (alphabet size)
|
SpaceO(|t|·Σ)

Problem Description

Given a string s consisting of lowercase English letters, determine the length of the longest contiguous substring that is a subsequence of a specific target pattern t. A subsequence is defined as a sequence that can be derived from another sequence by deleting zero or more elements without changing the order of the remaining elements. You must identify the maximum window size in s where the characters appear in t in the same relative order.

The input consists of two strings: s (the source string to scan) and t (the target pattern). The output is a single integer representing the maximum length of such a valid subsequence window found within s. If no valid subsequence of length greater than 0 exists, return 0.

This problem requires efficient verification of subsequence properties within sliding windows or via dynamic programming to handle large input sizes effectively. The solution must account for the non-contiguous nature of subsequences while maximizing the span of matched characters.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Balanced Tree Span Calculator 6"

medium

WHY DOES IT MATTER?

Recognizing the subsequence‑in‑window pattern lets you transform a seemingly quadratic string problem into a linear scan, a skill that appears in many coding interviews involving pattern matching, text editors, and DNA sequence analysis.

OPTIMIZATION CHALLENGE

The key insight is the construction of the next‑position automaton for t, which converts the subsequence check into a series of constant‑time jumps, enabling a sliding‑window scan that touches each character of s only a few times.

REAL-WORLD CONNECTION

Think of a streaming log processor that must detect whether a burst of events (the window) conforms to a predefined protocol (t). Precomputing the next‑event table lets the processor validate bursts in real time without re‑scanning the entire protocol each time.

When coding, first implement the next‑position table, then write a helper that, given a start index in t, returns the ending index after consuming a string; use this helper inside a classic left‑right window loop to keep the solution clean and bug‑free.

COMPLEXITY AT A GLANCE

⏱ Time:O(|s| + |t|·Σ) where Σ=26 (alphabet size)
💾 Space:O(|t|·Σ)

Core Theory — Why This Approach?

The problem reduces to checking, for any contiguous window of the source string s, whether its characters appear in order within the fixed target pattern t. This is a classic subsequence‑matching task that can be answered in O(length of window) by scanning t, but doing so for every possible window leads to O(|s|^2) time, which is infeasible for large inputs. The optimal paradigm leverages a preprocessing step that builds a “next‑position” automaton for t: for each index i in t and each letter c, next[i][c] stores the smallest index ≥ i where c occurs (or a sentinel if none). With this structure, we can greedily walk through a window of s, jumping through t in O(1) per character, turning a subsequence test into a constant‑time operation per character. By sliding a two‑pointer window over s and maintaining the current position in t, we can expand the right end while the window remains a valid subsequence and contract the left end when it fails, achieving linear overall complexity.

Interview Questions on This Problem

Q1How would you preprocess the target pattern t to answer “is this substring of s a subsequence of t?” in O(1) per character?

Build a next‑position table of size (|t|+1)×26 where next[i][c] gives the first occurrence of character c at or after index i in t; this allows us to jump to the next matching position in constant time.

Q2Explain why a naïve O(|s|^2) enumeration of all substrings fails for |s| up to 10^5, and how the two‑pointer technique avoids this blow‑up.

Enumerating all O(|s|^2) substrings would require billions of subsequence checks, each O(|t|), exceeding time limits. The two‑pointer method expands the right pointer only while the current window stays valid, and each character of s is processed a constant number of times, yielding O(|s|) total work.

Q3If the alphabet were Unicode (≈10^5 symbols) instead of 26 letters, how would you adapt the preprocessing to keep memory usage reasonable?

Replace the dense 2‑D array with a hash map or vector of unordered_maps for each position, storing only the characters that actually appear after that index; this keeps memory proportional to the number of distinct character occurrences in t.

Examples

Example 1

Input

s = "abcde", t = "ace"

Output

3

Explanation: The entire string "abcde" contains the subsequence "ace" (indices 0, 2, 4 in s). The length of this subsequence is 3. No longer subsequence of t exists in s. Thus, the answer is 3.

Example 2

Input

s = "xyz", t = "abc"

Output

0

Explanation: None of the characters in s ('x', 'y', 'z') appear in t ('a', 'b', 'c') in any order. Therefore, no valid subsequence exists, and the maximum length is 0.

Example 3

Input

s = "abab", t = "ba"

Output

2

Explanation: We look for the longest subsequence of s that matches t. The subsequence "ba" can be formed by taking 'b' at index 1 and 'a' at index 2 of s. The length is 2. Another instance is 'b' at index 3 and no 'a' after it, so length 1. The maximum is 2.

Example 4

Input

s = "aabbcc", t = "abc"

Output

3

Explanation: The subsequence "abc" is present in s. We can pick 'a' at index 0, 'b' at index 2, and 'c' at index 4. The length is 3. This is the maximum possible length since t has length 3.

Constraints

  • 1 <= s.length <= 10^5
  • 1 <= t.length <= 10^5
  • s and t consist of lowercase English letters only
  • The total number of test cases is not specified, but the solution must run in O(n*m) or better for each test case

Optimal Approach & Strategy

Preprocess t into a next‑position table, then use a two‑pointer sliding window over s, advancing the right pointer while the window remains a subsequence using O(1) jumps, and moving the left pointer when it fails. The whole algorithm runs in linear time.

Brute Force Approach

Check every possible substring of s, and for each run a linear scan over t to see if it is a subsequence. This costs O(|s|^2·|t|) time, which is far too slow for large inputs.

Verified Code Solutions

JavaScript Solution
Time: O(|s| + |t|·Σ) where Σ=26 (alphabet size)
function solution(nums) {
   let sum = nums.reduce((a, b) => a + b, 0);
   // Implement Subsequence Verification methodology here
   return sum;
}

Asked in Top Tech Interviews

AtlassianSwiggy

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.