algoblazerEarly Access
LearnProblemsStudy GroupsMock InterviewLeaderboard
Log inSign up

All problems

‹ Back to map
1 shown · 0/307 solved

Merge Two Strings on Their Longest Overlap

SilverCommunity Beta
Asked atApple
Solve problem →
2000ms256MBAdded Oct 5, 2026

You are given two strings first and second, each made of letters and digits.

Define the overlap of a string a onto a string b as the length of the longest suffix of a that is also a prefix of b. This length can be as large as the shorter of a and b, and it is 0 when no suffix of a matches any prefix of b.

Consider joining the two strings in the order first followed by second, and separately in the order second followed by first. When you join two strings in one of these orders, write their overlapping part only once instead of twice.

Return the joined string for whichever order produces the larger overlap. If both orders produce the same overlap length, return the result for the order first followed by second.

Examples

Example 1

Input: first = "1234yyabc", second = "abcxxxx1234"
Output: "abcxxxx1234yyabc"
Explanation: The overlap of first onto second is 3 ("abc"). The overlap of second onto first is 4 ("1234"). Since 4 is larger, join second followed by first and write "1234" only once: "abcxxxx" + "1234" + "yyabc".
Read full statement →

Constraints

  • 1≤1 \leq1≤ first.length ≤105\leq 10^5≤105
  • 1≤1 \leq1≤ second.length ≤105\leq 10^5≤105
  • first and second consist of English letters (uppercase and lowercase) and digits

Details

Solved by2 people
Time limit2000ms
Memory256MB
AddedOct 5, 20269 hours ago