Is it efficient to search for a common node in 2 singly linked memory-limited lists?

Suppose you are given two linked lists, which at some point enter the game. design the O (n + m) algorithm using a memory of at most O (1), which detects a FIRST common node, where m and n are the distances from the head of the list to the gang point, respectively.

I thought about marking visited nodes, but then I realized that this requires more O (1) memory. The problem is simple when you can run the entire list, which is not allowed here due to run-time limits. help = D

+4
source share
1 answer

I suppose there is a way to compare an element xfrom the first list with an element yfrom the second list to find out if they belong to the same element outside the gang point.

  • Compare x1with the first list of y1and y2, the first two elements of the second list.
  • Compare y1with x1and x2.
  • Compare x2with y2 ... y4.
  • Compare y2with x2 ... x4.
  • Compare x4with y4 ... y8.
  • ...

Generally:

for q in 1, 2, 4, 8, 16, ...
    Compare x_q with y_q ... y_2q
    Compare y_q with x_q ... x_2q

Basically, at every step you double the search range. Let's say m <= n. Then at some point there is m<qalso n-m<q. Now you will find a match x_q==y_(q+n-m). This match is somewhere behind the gang point, from there you just need to return to the gang point. That O(n+m).

, . , n-m , x_k y_(k+n-m) k=1,2,3,..., .

Edit2 , . q 2*q. , q=q1. q q1 4*q1 , . q1=O(n+m). , q=q1/2, m>q1/2, n>2*q1/2, . n+m>q1/2 q1<2*(n+m). 4*q1<8*(n+m), O(n+m). n>=m . , , , O(n+m), .

+4

Source: https://habr.com/ru/post/1536638/


All Articles