1316. Near-Twin Substrings

Hard7.5 points estimatedSliding WindowTwo PointersString

Two DNA fragments are given as strings s and t. Two pieces of the same length are called near-twins when they differ in at most k positions, comparing them character by character from the left.

Find the largest length L for which some substring of s of length L and some substring of t of length L are near-twins. Then count how many pairs of start positions (i, j) achieve that length, where the substring of s starts at i and the substring of t starts at j. Return the array [L, count]. If no non-empty pair of near-twins exists, return [0, 0].

Slide each alignment of the two strings on its own: along one alignment the mismatches form a 0/1 sequence, and a shrinking window finds the longest stretch with at most k ones. The intended solution runs in O(n * m) time and O(n + m) space.

Example 1

Input:
s = "abcd", t = "abxd", k = 1
Output:
[4,1]
Explanation:

Aligning the full strings gives one mismatch at index 2, so L = 4. Only the pair of start positions (0, 0) has that length, so the answer is [4, 1].

Example 2

Input:
s = "aaa", t = "bbb", k = 0
Output:
[0,0]
Explanation:

The strings share no letter, so with k = 0 there is no near-twin pair and the answer is [0, 0].

Example 3

Input:
s = "aa", t = "aaa", k = 0
Output:
[2,2]
Explanation:

The longest equal pieces have length 2, and the substring "aa" of s matches the t substrings starting at 0 and at 1, so the answer is [2, 2].

Constraints

  • 1 ≤ s.length, t.length ≤ 300

  • 0 ≤ k ≤ 300

  • s and t consist of lowercase English letters

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n * m)
Space
O(n + m)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…