Skip to content

Commit

Permalink
Added the algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
Dipanita45 committed Nov 2, 2024
1 parent 78260c8 commit f560e7a
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
29 changes: 29 additions & 0 deletions Searching Algorithms/Remove_All_Occurrence/Readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
## Remove All Occurrence

# Problem Description
To remove all the occurrences of an element in an array.
Given a string and a character, remove all occurrences of that character from the string. The resulting string should maintain the order of the remaining characters and should be null-terminated.

## Proposed Solution
To solve the problem of removing all occurrences of a specific character from a string ,you can follow these steps:

Iterate through the original string.
Copy characters to a new string only if they are not the target character.
Terminate the new string properly.

# Example :

Input:
String: "hello world"
Character to remove: 'o'
Output:
Resultant String: "hell wrld"

Complexity Analysis
# Time Complexity:

The time complexity of this algorithm is O(n), where n is the length of the input string. This is because we need to iterate through each character of the string exactly once to check if it matches the character to be removed.

# Space Complexity:

The space complexity is also O(n) in the worst case, as we may need to create a new string to hold the result. In the worst case, where none of the characters are removed, the size of the result string could be equal to the input string.
35 changes: 35 additions & 0 deletions Searching Algorithms/Remove_All_Occurrence/Remove All Occurrence.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#include <stdio.h>
#include <string.h>

void removeAllOccurrences(char *str, char charToRemove) {
int i, j = 0;
int length = strlen(str);
char result[length + 1]; // +1 for the null terminator

for (i = 0; i < length; i++) {
if (str[i] != charToRemove) {
result[j++] = str[i]; // Copy the character if it is not the target
}
}
result[j] = '\0'; // Null terminate the new string

// Copy the result back to the original string
strcpy(str, result);
}

int main() {
char str[100];
char charToRemove;

printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = 0; // Remove the trailing newline character

printf("Enter the character to remove: ");
scanf(" %c", &charToRemove);

removeAllOccurrences(str, charToRemove);
printf("Resulting string: %s\n", str);

return 0;
}

0 comments on commit f560e7a

Please sign in to comment.