Javatpoint Logo
Javatpoint Logo

Recursively remove all adjacent duplicates

Introduction

Programming problems involving the removal of adjacent duplicates from a string are frequent, and C offers a great framework for putting effective solutions in place. This article will discuss several approaches that we will use to use the C programming language to remove all adjacent duplicates in a given string recursively. Every technique will be broken down, examined, and performance optimized.

Method 1: Brute Force Approach

The Brute Force Approach to remove adjacent duplicates in C employs a straightforward double-loop structure. The inner loop compares the current character with every character that comes after in order to find adjacent duplicates. In contrast, the outer loop iterates through each character in the input string. In order to eliminate a duplicate, the remaining portion of the string is shifted to the left using the `memmove` function when a duplicate is discovered. The string is lengthened appropriately, and the inner loop variable is decreased to prevent the skipping of adjacent duplicates that follow. Although this method is functional, its time complexity is O(n^2), which means that it is less efficient for larger strings. This is because the removal process requires multiple passes through the string, which could cause performance issues in certain scenarios.

Code

Output:

Recursively remove all adjacent duplicates

Code Explanation

Iteration of a double loop

The function removeAdjacentDuplicates loops through each character in the string using a double loop structure. While the inner loop controlled by j looks for adjacent duplicates beginning with the following character, the outer loop controlled by the variable i continues to traverse the string from the beginning.

Logic for Duplication Removal

When characters at indices i and j are equal in an adjacent duplicate, the memmove function is used to move the remaining portion of the string one position to the left, thereby eliminating the duplicate. Next, the length of the modified string is decreased and reflected in the variable len by decrementing it.

Changing the Loop Variables

After a duplicate is removed, the inner loop variable j is decremented (j--) to make sure all duplicates are correctly removed. This change avoids missing any possible duplicates that might show up one after the other.

In-Place Modification

Duplicate characters are eliminated in-place within the same string (str). This indicates that no new memory is allocated; instead, the original string is changed directly. However, because the shifting operation has an O(n^2) time complexity, the approach might not be the most effective for longer strings.

Example Usage

An example string "abbaccddeeff" is given in the main function, and the original and modified strings are printed before and after the adjacent duplicates are eliminated, respectively. This shows how the problem can be resolved by using the removeAdjacentDuplicates function.

Method 2: Recursive Approach

For the purpose of eliminating adjacent duplicates in a given string, the Recursive Approach uses a more sophisticated and effective method. The {removeAdjacentDuplicatesRecursive} function, which is called recursively, is the central component of this technique. By rearranging the remaining portion of the string, this function eliminates any duplicates that iterates through the string and looks for adjacent ones. Recursion keeps going until no more nearby duplicates are discovered, guaranteeing a complete removal procedure. This strategy achieves an O(n) time complexity by removing duplicates recursively, which makes it more scalable and effective than the brute force method.

Code

Output:

Recursively remove all adjacent duplicates

Code Explanation

Recursive Function

removeAdjacentDuplicatesRecursive, the primary function in this code, recursively eliminates adjacent duplicate characters from the supplied string. When neighboring duplicates are discovered while iterating through the string, it shifts the next character to eliminate the duplicate before making a recursive call to carry on.

String Traversal

The function goes character by character through the input string using a loop. Because it compares each character with its neighbor (i.e., str[i] with str[i + 1]), the loop continues until the second-to-last character.

Duplicate Removal

The function shifts the following characters to the left in a nested loop (for (j = i; j < len - 1; j++)) when it finds adjacent duplicate characters. This effectively removes the duplicate. The modified string is null-terminated by setting the last character (str[len - 1]) to '\0'.

RecursionTrigger

The function calls itself recursively (removeAdjacentDuplicatesRecursive(str)) to search for and eliminate duplicates in the modified string once the adjacent duplicates have been eliminated. Until no more nearby duplicates are discovered, this process is repeated.

Printing Results

The original and modified strings are printed before and after invoking the removeAdjacentDuplicatesRecursive function, respectively. The main function provides an example string ("abbaccddeeff"). This illustrates the usefulness of removing adjacent duplicates recursively.

Termination and Return

After successfully executing the main function, the program ends by returning 0. The user can see the outcome of the recursive removal process when the modified string-which is now free of adjacent duplicates-is printed to the console.

Method 3: Stack-based Approach

An effective way to recursively eliminate adjacent duplicates from a string in C is to use the stack-based approach. This method traverses the input string using a stack data structure to keep track of non-duplicate characters. Non-duplicate characters are pushed onto the stack by the algorithm as it goes through each character in the string. When a duplicate is found, the top element in the stack is removed. In a single pass through the string, this process effectively removes adjacent duplicates, leaving the modified string on the stack. Compared to the brute force method, the stack-based approach makes significant improvements to the time complexity, improving it to O(n). This means that it is more scalable for larger strings. Furthermore, appropriate string termination is guaranteed by the null-terminated character array. The stack-based method is a workable solution for the recursive removal of adjacent duplicates in C since it strikes a balance between simplicity and efficiency overall.

Code

Output:

Recursively remove all adjacent duplicates

Code Explanation

Function Definition

The code defines the removeAdjacentDuplicatesStack function, which employs a stack-based method to eliminate adjacent duplicates from a character array (str). Through the manipulation of an index (stackIndex) and the guarantee that unique characters are pushed onto the stack, the function alters the input string in-place.

Stack-Based Method

To effectively handle adjacent duplicates, the removeAdjacentDuplicatesStack function makes use of a stack. Every character in the input string is compared to the top of the stack (str[stackIndex - 1]) as iteratively processed. In the event that a duplicate is discovered, the adjacent duplicate is effectively eliminated by decreasing the stack index. The stack index is increased to push the character onto the stack if it is deemed non-duplicate and not a duplicate.

Iterative Process

The function evaluates each character individually as it loops through the whole input string. The stack aids in keeping track of the characters that haven't been duplicated thus far. The sequence of the non-duplicate characters in the modified string is maintained thanks to this iterative process.

Effective Memory Usage

The stack-based technique optimizes memory usage in contrast to the brute-force method, which moves parts of the string repeatedly. The elimination of duplicates in a solitary string traversal leads to a more memory-efficient resolution. To guarantee correct termination, the null terminator ('\0') is positioned correctly at the end of the altered string.

Example Usage in Main Function

The removeAdjacentDuplicatesStack function is applied to an example string ("abbaccddeeff") in the main function to demonstrate how to use it. A duplicate of the original string is created and shown (modifiedString). After calling the function on the copied string, the altered outcome-which shows how the adjacent duplicates were eliminated-is printed.

Preventing Modification of Original String

Before applying the removal of adjacent duplicates, the code creates a copy of the original string (modifiedString) in order to protect it. By ensuring that the original string doesn't change, this technique makes it possible to compare and demonstrate ideas without changing the original data. The outcome of the removal process is reflected in the updated string.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA