This is a question from List Data Model by Ullman
- If L and M are Linked List , under what conditions is LM = ML ?
i was reading Foundation of Computer Science book .The question is from http://i.stanford.edu/~ullman/focs/ch06.pdf 6.3.2
This is a question from List Data Model by Ullman
i was reading Foundation of Computer Science book .The question is from http://i.stanford.edu/~ullman/focs/ch06.pdf 6.3.2
I can think of two conditions right off the top of my head:
One of the lists is empty.
{}+{1,2,3} = {1,2,3}+{} = {1,2,3}
One list is the concatenation of multiple instances of the other list.
{1,2,3}+{1,2,3,1,2,3} = {1,2,3,1,2,3}+{1,2,3} = {1,2,3,1,2,3,1,2,3}
Two side notes: 1)In the first condition, the empty list {}
is the identity of the concatenation operation. 2)The condition M=L
is actually a special case of condition two.
Edit: Thanks to @jwpat7, here's another condition:
{2,3,2,3}+{2,3,2,3,2,3} = {2,3,2,3,2,3}+{2,3,2,3}
Both lists are concatenations of multiple instances of the same list, which is {2,3}
in the example above.
Without loss of generality, we can assume |L| <= |M|. (Otherwise just reverse the assignment of labels L and M.) Then we have LM = ML = LAL where M = LA = AL. Note that we now have a new version of the same problem with LA replacing LM. This says that we can give a recursive condition:
LM = ML if and only if M = AL = LA for some list A
There is a little known theorem (which was recently put to use here: Detect whether sequence is a multiple of a subsequence in Python)
According to that theorem, Suppose x and y are strings. Then xy = yx if an only if x and y are both powers of a certain string z, i.e. both are concatenations of the same string z, i.e. x= z.z.z...z (k times) and y = z.z...z (l times).
Talking in terms of 'plain old' linked lists is essentially the same.
I believe a proof by induction on the length of one of the strings works.
(Unfortunately, I used to remember the name of this theorem, but I have forgotten and so cannot find you a reference).