This is an interview problem I was asked, and I am still trying to figure out if a polynomial time algorithm for this exists :-
Given file sizes for seen and unseen movies in drive A and drive B, along with the free space in both of them,determine if you can move all the unseen movies in one drive and seen in the other, using only the free space in the drives. The only operation allowed is move(source, dest) where dest should have more free space than src file size.
boolean canSegregateSeenUnseen(Drive A, Drive B);
where Drive is {
List<Integer> seenMoviesFileSizes;
List<Integer> unseenMoviesFileSizes;
Integer freeSpace;
}
I thought of doing a BFS over all possible states achievable from the initial state, connecting states using the move operation, but that appears to be exponential.
Is there a better way ? Or can this be reduced to a non-polynomial time problem ?
One possibility: one of the files you have to move is exactly the same size as the total of free space on both drives (I’m not sure whether the question cares which drive ends up with the watched files and which the unwatched, but even if not then it’s still possible that there are two files of this size on the same drive, one watched and one unwatched. Or one on each drive, either both watched or both unwatched).
Then “is it possible to get all the free space onto the destination drive at once?” is (in part) a subset-sum problem: “does there exist a subset of all the files whose sum is the size of the source drive?”
So I don’t think this looks good for a polynomial time solution, although I admit I haven’t given a formal reduction of the subset-sum problem to this problem.
Btw, even if this problem is NP-complete, it doesn’t necessarily follow that there’s no solution better than the brute force you describe.