1289. Wildcard Anagram Windows

Medium3.5 points estimatedSliding WindowHash TableStringCounting

A badge printer sometimes smudges a character, and every smudge is shown as '?' in the string s. A '?' may stand for any lowercase letter, chosen independently for each '?'. A window of s with exactly p.length characters is a match when the '?' marks can be replaced so that the letters of the window can be rearranged into p. Return, in ascending order, every start index i such that the window beginning at i is a match. Return an empty array when there is none.

Aim for O(n) time and O(1) extra space besides the output, where n is the length of s: slide a 26-entry count array and track how many letters currently exceed their count in p.

Example 1

Input:
s = "abxcab", p = "abc"
Output:
[3]
Explanation:

Only the window 'cab' starting at index 3 can be rearranged into 'abc'; 'abx', 'bxc' and 'xca' each contain an x.

Example 2

Input:
s = "?b?a?c", p = "abc"
Output:
[0,1,2,3]
Explanation:

Each of the four windows of length 3 has at most one a, one b and one c, and the '?' marks fill the rest, so all four starts match.

Example 3

Input:
s = "aaaa", p = "aa"
Output:
[0,1,2]
Explanation:

Every window 'aa' equals the pattern, so starts 0, 1 and 2 all match.

Constraints

1 ≤ p.length ≤ s.length ≤ 2000

p consists of lowercase letters

s consists of lowercase letters or '?'

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)
Space
O(1)

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…