Longest common suffix of two linked lists

Given two singly linked lists, find the Longest common suffix of two linked lists. If there are no common characters which are suffixes, return the minimum length of the two linked lists.

Examples:

Input : list1 = w -> a -> l -> k -> i -> n -> g
list2 = l -> i -> s -> t -> e -> n -> i -> n -> g
Output :i -> n -> g

Input : list1 = p -> a -> r -> t -> y
list2 = p -> a -> r -> t -> y -> i -> n -> g
Output :p -> a -> r -> t -> y

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

A simple solution is to use auxiliary arrays to store linked lists. Then print longest commons suffix of two arrays.

The above solution requires extra space. We can save space by first doing reverse of both linked lists. After reversing, we can easily find length of longest common prefix. Reversing again to get the original lists back.
One important point here is, order of elements. We need to print nodes from n-th to end. We use the above found count and print nodes in required order using two pointer approach.

C#

Output:

ing

Time Complexity : O(N)

My Personal Notes arrow_drop_up Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Improved By : Rajput-Ji, princiraj1992