Commit 4260de3a authored by Bradley Small's avatar Bradley Small

Adding the true O(m+n) solution

parent 780a8f38
#!/usr/bin/python3
""" Find beginning of overlapping list """
""" Wrote my own linked list for this. There is no error checking and all
assumptions are optimistic. This may be a fun project to flesh out with
......@@ -52,13 +53,21 @@ class LList:
def main():
""" Main driver create lists, reverse them, find beginning overlap """
# This is just setup
mlist = LList(Node(3,Node(7,Node(8,Node(10)))))
nlist = LList(Node(99,Node(1,Node(8,Node(10)))))
mlist.show()
nlist.show()
# list reversal in place solution
# this is in constant space but the solution is actually
# in O(m+n+l) where l is the final length of the overlapped
# string. Still in constant space since the reversal is in place
nlist.reverse()
mlist.reverse()
......@@ -74,12 +83,34 @@ def main():
mnode = mlist.next()
print("The overlap = ", overlap.val)
# At this point the list would have to be reversed again to actually
# get the true overlapped list, though not part of the problem it
# doubles the effort to achieve
nlist.reverse()
mlist.reverse()
overlapList = LList(overlap)
print("The overlap list : ", end ='')
overlapList.show()
LList(overlap).show()
# solution using 2 "pointers" solves the O(m+n) in constant space
# aspect of the problem.
mwalker = mlist.head
nwalker = nlist.head
while mwalker.val != nwalker.val:
mwalker = mwalker.next
nwalker = nwalker.next
if not mwalker:
mwalker = nlist.head
if not nwalker:
nwalker = mlist.heead
print("The overlap = ", nwalker.val);
# Getting the actual list, though not part of the problem no longer
# takes double the processing.
print("The overlap list is:", end ='')
LList(nwalker).show();
if __name__ == "__main__":
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment