Linked list

A linked list is a Linear Data Structures, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers as shown in the below image:
Linkedlist Data Structure

In simple words, a linked list consists of nodes where each node contains a data field and a reference(link) to the next node in the list.

indexing in linkedList

indexing in linked list is O(n) .

replacing elements

unlike in a regular array when appending new elements require to copy the data sometimes which can be expensive. the linear list allow us to add a new element at index with no further consequences.

merging linked lists

Pasted image 20220506012314.png
we have 2 linked list as above with a merging point x we want to find it. lets examine some of the possible methods to do so :

time complexity :

the first step will be k+n+l+n steps just to calculate the size of each list.
and than iterating again |kl| times and at the end another min(k,l) times to reach x.
therefore the time complexity will be O(k+l+n).

is there a better way to reach the same result?
we can perform the same algorithm in O(d2) and O(d) when d=max(l,k).

O(d2):

find max(l,k) (for this example we will assume d=k).
iterate through L1 when each iterator i
we will move L2 , i times and check all the elements with indexi and we compare the elements with the i element in L1.

time complexity :
d+i=0di=d+d(0+d)2=2d+d22<2d+d2<3d2Θ(d2)

O(d):

we will perform the same method as above but we will only work with elements where indexes are in jumps of power of 2i .

in this method what will happen is Geometric progression instead of Arithmetic progression
now x index marked as k will be 2i

now we "create" a new L1 and L2 with only the elements at indexes that are at 2i indexes.
the problem got smaller now! cool right?

identify a circular linked list

Pasted image 20220506111109.png

the element which start a circular linked list will always have 2 indexes, the first is n+1 and the second is i<n+1 where n is the size of the list.

each element we will assume that his index i=n+1 . and we iterate so we iterate while assuming the length of the list is i and check if we have 2 indexes for same element.

the time complexity is :
i=0niO(n2)

and if we perform the 2i jumps on the same algorithm we can shrink the problem to be O(n)

another way is to iterate the list in a rabbit and turtle style :
one iterator will run 1 element at a time and the rabbit will jump 2 elements at a time ... they will surly meet in the circle. this will be a time complexity of O(n).

now if we want to find the first point which the circle start.
the algorithm will be :