Playlist Shuffle Validator - Problem

Given two original playlists playlist1 and playlist2, and a merged playlist merged, determine if the merged playlist is a valid interleaving of the two original playlists.

A valid interleaving means that all songs from both playlists appear in the merged playlist while preserving their relative order from the original playlists. Songs can be interleaved in any pattern, but the order within each original playlist must remain intact.

Example: If playlist1 = ["A", "B"] and playlist2 = ["X", "Y"], then ["A", "X", "B", "Y"] is valid because A comes before B (preserving playlist1 order) and X comes before Y (preserving playlist2 order).

Input & Output

Example 1 — Valid Interleaving
$ Input: playlist1 = ["A", "B"], playlist2 = ["X", "Y"], merged = ["A", "X", "B", "Y"]
Output: true
💡 Note: The merged playlist preserves order: A comes before B (playlist1 order) and X comes before Y (playlist2 order). Valid interleaving pattern.
Example 2 — Invalid Order
$ Input: playlist1 = ["A", "B"], playlist2 = ["X", "Y"], merged = ["A", "Y", "B", "X"]
Output: false
💡 Note: Y appears before X in merged, but playlist2 has X before Y. This violates the relative order requirement.
Example 3 — All From One Playlist First
$ Input: playlist1 = ["Rock", "Pop"], playlist2 = ["Jazz"], merged = ["Rock", "Pop", "Jazz"]
Output: true
💡 Note: All songs from playlist1 appear first, then playlist2. Both maintain their relative order, so this is valid.

Constraints

  • 1 ≤ playlist1.length, playlist2.length ≤ 100
  • 1 ≤ playlist1[i].length, playlist2[i].length ≤ 10
  • playlist1[i], playlist2[i] consist of lowercase English letters

Visualization

Tap to expand
INPUT PLAYLISTSALGORITHM STEPSVALIDATION RESULTABPlaylist 1XYPlaylist 2AXBYMerged Playlist1Initialize DP table2Check valid transitions3Fill DP states bottom-up4Return dp[m][n] resultVALIDTRUEA before B ✓X before Y ✓All songs present ✓Key Insight:Use 2D DP to track valid interleaving states - each cell represents whether we can formmerged[0:i+j] using first i songs from playlist1 and first j songs from playlist2.TutorialsPoint - Playlist Shuffle Validator | 2D Dynamic Programming
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
23.5K Views
Medium-High Frequency
~25 min Avg. Time
987 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen