Here is the version that works in O (n). The idea is to replace the numbers so that the target array becomes [0, 1, 2, 3, ...], so itβs very easy to count the number of cuts required. Here is the implementation in Javascript ( link ):
function solve(o, d) {
var sub = [], count = 0;
// make arrays 0-based and calculate substitution
for (var i = 0; i < d.length; i++) {
o[i]--;
d[i]--;
sub[d[i]] = i;
}
// substitute
for (var i = 0; i < o.length; i++)
o[i] = sub[o[i]];
// scan and count
for (var i = 1; i < o.length; i++)
if (o[i - 1] + 1 != o[i])
count++;
return count + 1; // the number of pieces is the number of required cuts + 1
}
alert(solve([1, 4, 3, 2], [1, 2, 4, 3]));
source
share