VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-whether-two-linked-lists-are-anagrams-or-not/

⇱ Check whether two Linked Lists are anagrams or not - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check whether two Linked Lists are anagrams or not

Last Updated : 10 Apr, 2023

Given two strings in the form of linked lists, the task is to check if one string is the anagram of the other. Print Yes if they are, otherwise print No.

Examples:

Input: 
Linked List 1 = T->R->I->A->N->G->L->E->NULL
Linked List 2 = I->N->T->E->G->R->A->L->NULL
Output: Yes
Explanation: The given two strings are anagram as they have the same characters present equal times.

Input:
Linked List 1 = S->I->L->E->N->T->NULL
Linked List 2 = L->I->S->T->E->N->NULL
Output: Yes

Approach: This problem can be solved by sorting the linked lists and then checking both of them are identical or not. If they are identical after sorting, then they are anagrams. Otherwise, they aren't. Now follow the below steps to solve this problem:

  1. Sort both the linked lists using bubble sort.
  2. Now, traverse both the linked lists from the start and match each corresponding node.
  3. If two corresponding nodes are different, then print No and return.
  4. Print Yes in the end after the loop ends.

Below is the implementation of the above approach:


Output
Yes

Time Complexity: O(N2)
Auxiliary Space: O(1)

Approach 2: In approach 1 we have used the sorting technique. In this approach we well create an array where we will store the frequencies of characters that are present in the linked lists. By traversing the first linked list we will increment the frequency, by traversing the second linked list we reduce the frequency.  Finally we will traverse the frequency array if we find any element which has frequency not equal to zero. then, we can say that they are not anagrams.

Below is the implementation of the above approach:


Output
true
Comment