Write a Program to check whether a string is a valid shuffle of two strings or not
Pattern: Strings basics and frequency
A valid shuffle interleaves the two strings while keeping each one's own order. A table ok[i][j] says whether the first i characters of one and the first j of the other can form the start of the result; each cell looks at only two earlier cells.
The problem
Given strings first, second and result, return whether result is a valid shuffle of the other two. This guide
uses the strict meaning: result must use every character of both strings exactly once, and the characters of first
must appear in their original order, and so must those of second. For example, "1XY2" is a valid shuffle of "XY"
and "12", but "Y1X2" is not, because Y comes before X.
The link above is a Programiz article. Its program only checks that result has the same letters as the other two put
together, so it accepts "Y1X2". This guide's function isValidShuffle and its order-keeping rule are its own (this is
LeetCode's Interleaving String under another name).
Think first
- Why can't you greedily take from whichever string matches the next character? Try
"ab","ac"and"acab". - If the first
ioffirstandjofsecondform the start ofresult, which character comes next? - Which two smaller cases can lead to "the first
iandjwork"?
Hints
Brute force, and why it fails
Try every way of choosing which positions of result come from first: exponential. Plain recursion with both choices
repeats the same (i, j) many times. The table computes each (i, j) once: O(m × n).
The key insight
At every step there are only two choices, take the next character from first or from second. The whole history is
summed up by two numbers (i, j), so the problem has only (m + 1)(n + 1) states.
Dry run
| cell | ok[0][0] = true |
|---|
first = XY, second = 12 and result = 1XY2. ok[0][0] is true, the empty start.
The plan
if m + n != len(result): return false
ok = array of n + 1 falses
for i from 0 to m:
for j from 0 to n:
if i == 0 and j == 0: ok[j] = true; continue
want = result[i + j - 1]
fromFirst = i > 0 and ok[j] and first[i - 1] == want
fromSecond = j > 0 and ok[j - 1] and second[j - 1] == want
ok[j] = fromFirst or fromSecond
return ok[n]
Complexity
- Time
O(m × n)- Space
O(n)
Every pair (i, j) is filled once. One row of n + 1 values is kept, because ok[j] still holds the row above when it
is read.
Edge cases
- Lengths that do not add up: false at once.
- All three empty: true.
- Shared letters, as in
"aabcc","dbbca","aadbbcbcac": true, which greedy can get wrong.
I've built my logic, show the code
Java
class Solution {
public boolean isValidShuffle(String first, String second, String result) {
int m = first.length(), n = second.length();
if (m + n != result.length()) return false;
boolean[] ok = new boolean[n + 1]; // ok[j]: the first i of 'first' and j of 'second' make result's start
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= n; j++) {
if (i == 0 && j == 0) { ok[j] = true; continue; }
char want = result.charAt(i + j - 1);
boolean fromFirst = i > 0 && ok[j] && first.charAt(i - 1) == want; // ok[j] still holds row i - 1
boolean fromSecond = j > 0 && ok[j - 1] && second.charAt(j - 1) == want;
ok[j] = fromFirst || fromSecond;
}
}
return ok[n];
}
}C++
class Solution {
public:
bool isValidShuffle(string first, string second, string result) {
size_t m = first.size(), n = second.size();
if (m + n != result.size()) return false;
vector<bool> ok(n + 1, false); // ok[j]: the first i of 'first' and j of 'second' make result's start
for (size_t i = 0; i <= m; i++) {
for (size_t j = 0; j <= n; j++) {
if (i == 0 && j == 0) { ok[j] = true; continue; }
char want = result[i + j - 1];
bool fromFirst = i > 0 && ok[j] && first[i - 1] == want; // ok[j] still holds row i - 1
bool fromSecond = j > 0 && ok[j - 1] && second[j - 1] == want;
ok[j] = fromFirst || fromSecond;
}
}
return ok[n];
}
};Python
class Solution:
def isValidShuffle(self, first: str, second: str, result: str) -> bool:
m, n = len(first), len(second)
if m + n != len(result):
return False
ok = [False] * (n + 1) # ok[j]: the first i of 'first' and j of 'second' make result's start
for i in range(m + 1):
for j in range(n + 1):
if i == 0 and j == 0:
ok[j] = True
continue
want = result[i + j - 1]
from_first = i > 0 and ok[j] and first[i - 1] == want # ok[j] still holds row i - 1
from_second = j > 0 and ok[j - 1] and second[j - 1] == want
ok[j] = from_first or from_second
return ok[n]Common mistakes
- Using greedy two pointers, which fails when both strings offer the same character.
- Comparing sorted letters, which ignores the order rule.
- Filling
jdownwards in the one-row version. Going upwards,ok[j]still holds the row above when it is read, andok[j - 1]already holds the current row.