Merge Two Strings Using the Longest Edge Overlap
Company: Apple
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Online Assessment
Overview: Compare both suffix-to-prefix concatenation orders, merge the longest edge overlap, and favor the original string order when overlap lengths tie.
Constraints
- 0 <= len(str1), len(str2) <= 200000
- Strings contain ASCII characters with code points 32 through 126, inclusive, including spaces and punctuation.
- Comparisons are case-sensitive.
- Empty strings are valid inputs and follow the same rules.
- Target O(len(str1) + len(str2)) time; linear auxiliary storage is allowed.
- The returned string has length at most 400000, so all lengths and indices fit in a 32-bit signed integer.
Examples
Input: ('', '')
Expected Output: ''
Explanation: Both strings are empty, so min(len(a), len(b)) is 0 in both orders; the overlaps tie at 0 and (str1, str2) wins, giving the empty concatenation.
Input: ('', 'hi')
Expected Output: 'hi'
Explanation: Source example. An empty first string forces overlap 0 in both orders; the tie keeps (str1, str2), so the result is '' followed by 'hi'.
Hints
- There are only two candidate answers: the merge for the order (str1, str2) and the merge for the order (str2, str1). Write one helper that answers 'how long is the longest suffix of a that is also a prefix of b' and call it twice.
- An overlap of k = 0 is always legal, so a merge always exists; the task is to find the largest legal k for an order, not the first one you happen to check.
- Testing every candidate k by direct character comparison degrades to quadratic time on highly repetitive inputs; joining the two strings with a delimiter that cannot appear in the input (any code point outside 32 through 126) lets a single linear scan produce the same number.