Katkat

Bracket substrings matching any pattern

UberSoftware Engineer · Technical Screen

Last updated

This problem tests your ability to efficiently match and replace substrings based on a set of predefined patterns, prioritizing matches based on position and length.

Problem Statement

Given an input string s and a list of patterns (an array of strings), implement a function that replaces the first occurrence of any pattern found in s. If multiple patterns can start at the same leftmost position, choose the longest one. If multiple patterns appear at different positions, prioritize the one that starts earliest. After performing the replacement, return the resulting string. If no pattern is found, return the original string.

Function Signature

def replace_first_pattern(s: str, patterns: list[str]) -> str:

Constraints

  • s length: 0 to 1000.
  • patterns length: 1 to 50.
  • Pattern length: 1 to 20.
  • Assume a simple replacement character (e.g., "?").

Examples

Example 1: Input: s = "abccde", patterns = ["bc", "bcc"] Output: "a?de" Explanation: Both "bc" and "bcc" start at index 1. "bcc" is longer, so it is replaced first.

Example 2: Input: s = "hello world", patterns = ["world", "hello"] Output: "? world" Explanation: "hello" starts at index 0, which is earlier than the match for "world" at index 6.

Edge Cases

  • Empty string s.
  • Overlapping patterns where one is a prefix of another.
  • No matches found.

Hints

Hint 1

Iterate through the string starting from each index from 0 to len(s) - 1.

Hint 2

At each index, check which patterns match the substring starting at that position.

Hint 3

Store the best match found (earliest index, then longest length) and perform the replacement once the entire string has been scanned.

Follow-up questions

  • How would you optimize the search if the number of patterns was very large (e.g., 10,000+)?
  • What if you were required to perform the replacement globally (replace all non-overlapping occurrences) instead of just the first one?
  • How does the complexity change if the patterns were dynamic and could be added or removed during the execution?