1206. Deepest Prefix Sighting
A proofreader checks how much of a template shows up in a document. Look at every position of text and the longest prefix of pattern that ends exactly there, matching right up to that character. Let L be the largest such length over all positions, and take the first position where length L is reached.
Return [L, start] where start is the 0-based index in text at which that occurrence of the prefix begins. If the first letter of pattern never occurs in text, return [0, -1]. The prefix can be the whole pattern, and a prefix can be cut off by the end of text.
Run the KMP matcher of pattern over text and track the best matched length. Here 1 <= text.length, pattern.length <= 2 * 10^5 and both use lowercase letters. The intended cost is O(n + m) time and O(m) space.
Example 1
- Input:
- text = "abcabcabd", pattern = "abcabd"
- Output:
- [6,3]
- Explanation:
The whole pattern abcabd occurs starting at index 3, so the longest prefix is 6 long.
Example 2
- Input:
- text = "xyz", pattern = "ab"
- Output:
- [0,-1]
- Explanation:
The letter a never appears in the text, so no prefix is ever matched.
Example 3
- Input:
- text = "aabaab", pattern = "aabaac"
- Output:
- [5,0]
- Explanation:
The prefix aabaa (length 5) ends at index 4 and starts at index 0; the next letter b is not c, so no longer prefix appears.
Constraints
1 ≤ text.length ≤ 2 * 105
1 ≤ pattern.length ≤ 2 * 105
both strings contain lowercase letters only
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms
Expected complexity
- Time
- O(n + m)
- Space
- O(m)