PracticeSearching

First Literal Interval

MediumSearchingtraversalstate trackingprefix reasoning Time not estimated Not started

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

Example 1
Input: pattern = "brown"source = "the quick brown fox"
Output: [10, 15]
Explanation: For source "the quick brown fox" and pattern "brown", the executed result is [10, 15].
Example 2
Input: pattern = "ana"source = "banana bandana"
Output: [1, 4]
Explanation: For source "banana bandana" and pattern "ana", the executed result is [1, 4], which is the earliest occurrence specified by the example.
Example 3
Input: pattern = ""source = "hello world"
Output: [0, 0]
Explanation: For source "hello world" and an empty pattern, the executed result is [0, 0].

Constraints

  • 0 <= len(source) <= 200
  • 0 <= len(pattern) <= 50
  • source and pattern contain lowercase letters and spaces.
  • Types: source is str, pattern is str; result is int[]

Function signature

def find_first_literal_interval(source: str, pattern: str) -> list[int]
source str
The string in which the search is performed.
pattern str
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.
Approved · cb056-abs_398_v114 execution-verified tests
Code
Saved
Checking environment…Python SandboxLn 1, Col 1