Last Updated: 28 Sep, 2020

Remove String

Moderate
Asked in companies
OpenTextAmazonSamsung

Problem statement

You have been given a linked list where each node has a single character. You have also been given a string 'STR'.

You have to remove all the occurrences of string STR from the linked list.

Note:
1. Start checking from the end of the linked list and not from the beginning. For example, if the linked list is ( a, b, a ,b, a)  and the string is equal to “aba” , then the answer should be (a b), not (b a).

2. After removing an occurrence check again for new formations.
Input format:
The first line contains an Integer 'T' which denotes the number of test cases.

The first line of each test case contains the elements of the singly linked list which are the characters not separated by a space.

The second line of each test case contains the string named 'STR'.
Output format:
For each test case, return the head of the linked list with updated character nodes after removing occurrences of the string.
Note:
You don't need to print the output, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 10
0 <= N <= 10^3  
0 <= K <= 10^2

Where 'N' is the size of the singly linked list and 'K' is the size of the string.

Time limit: 1 sec

Approaches

01 Approach

Starting from the head of the linked list make recursive calls until you reach the end of a linked list. Store the address of the head of the linked list in a pointer. Now you reach the end of the linked list and while backtracking, try to match the corresponding character of the string with the data stored in the current pointer ‘TEMP’ in linked list char by char. 

 

If found then simply return the current pointer ‘TEMP’ of the updated linked list, else return the head of the linked list itself.