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

Adding the true O(m+n) solution

parent 780a8f38
""" 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)))))
# 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
......@@ -74,12 +83,34 @@ def main():
mnode =
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
overlapList = LList(overlap)
print("The overlap list : ", end ='')
# 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 =
nwalker =
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 ='')
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