First Literal Interval
Context
Consider two finite strings over lowercase letters and spaces. Treat every character exactly as written. Determine where the first copy of one string begins inside the other, using an interval whose right endpoint comes immediately after the matched characters.
Problem
Write a function that searches for pattern in source and returns the interval of its first contiguous occurrence. The interval must use zero-based indexing and a half-open boundary: the start is included and the end is excluded. If pattern is empty, define its first occurrence as the empty interval at the beginning of source. If pattern does not occur, return a two-element integer list whose entries are both -1. Do not trim, normalize, or skip spaces, and do not select a later occurrence when an earlier one exists.
Examples
pattern = "brown"source = "the quick brown fox"[10, 15]pattern = "ana"source = "banana bandana"[1, 4]pattern = ""source = "hello world"[0, 0]Constraints
0 <= len(source) <= 2000 <= len(pattern) <= 50source and pattern contain lowercase letters and spaces.- Types:
sourceis str,patternis str; result is int[]
Function signature
def find_first_literal_interval(source: str, pattern: str) -> list[int]
sourcestr- The string in which the search is performed.
patternstr- The literal contiguous string to locate.
- returns list[int]
- A two-element list [start, end] for the first occurrence, with end exclusive; use [-1, -1] when no occurrence exists.
Adapted from MBPP problem task_534 (CC BY 4.0). Rewritten, extended and verified by Iksha.
Notes
- Matching is literal character-for-character.
- The selected occurrence is always the earliest valid one.
- An empty pattern has a defined empty interval at source index 0.