Skip to main content

Interleaving String

Medium
Data Structures and Algorithms
Editorial
Topics:
Dynamic Programming
String
Memoization

Given three strings s1, s2, and s3, determine whether s3 can be formed by interleaving s1 and s2. An interleaving preserves the left-to-right order of the characters taken from s1 and separately preserves the order of the characters taken from s2; at each position, the next character comes from one of those two strings.

Every character from both s1 and s2 must be used exactly once, so a valid interleaving must also have the combined length of the two source strings. Return true if at least one valid interleaving produces s3; otherwise, return false.

Example 1:

Input: s1 = "cat", s2 = "dog", s3 = "cdoatg"
Output: true
Explanation: The characters can be taken in order as c from s1, d and o from s2, a and t from s1, and g from s2.

Example 2:

Input: s1 = "ab", s2 = "ba", s3 = "bbaa"
Output: false
Explanation: After taking b from s2, the next b cannot come from either string: s2 must continue with a, while s1 begins with a.

Example 3:

Input: s1 = "", s2 = "hello", s3 = "hello"
Output: true
Explanation: When s1 is empty, the only possible interleaving uses all of s2, which exactly matches s3.

Constraints:

  • 0 <= s1.length <= 100
  • 0 <= s2.length <= 100
  • 0 <= s3.length <= 200
  • s1, s2, and s3 contain only lowercase English letters
  • s3.length = s1.length + s2.length

Need help or want more practice?

Practise in an interviewGet AI Coach help