How to Remove Duplicates From a Given String


 

Duplicate characters within a string can clutter data and complicate processing. Whether you're a programmer, a data analyst, or just someone trying to clean up their text, knowing how to remove duplicates from a string is a valuable skill. In this comprehensive guide, we'll explore various methods to achieve this task using different programming languages: PHP, C, C++, JavaScript, Python, and Java.

Understanding the Problem:

Before delving into solutions, it's essential to understand the problem. Removing duplicates from a string involves scanning each character and filtering out any repetitions. For example, given the input string "hello", the output should be "helo".

#include <stdio.h>
#include <string.h>

void removeDuplicates(char* str) {
    int i, j, len;
    len = strlen(str);
    for (i = 0; i < len; i++) {
        for (j = i + 1; j < len;) {
            if (str[j] == str[i]) {
                memmove(&str[j], &str[j + 1], len - j);
                len--;
            } else {
                j++;
            }
        }
    }
}

int main() {
    char input[] = "hello";
    removeDuplicates(input);
    printf("%s", input);
    return 0;
}

Output

helo
#include <iostream>
#include <algorithm>
#include <string>

void removeDuplicates(std::string& str) {
    str.erase(std::unique(str.begin(), str.end()), str.end());
}

int main() {
    std::string input = "hello";
    removeDuplicates(input);
    std::cout << input;
    return 0;
}

Output

helo
import java.util.LinkedHashSet;
import java.util.Arrays;

public class Main {
    public static String removeDuplicates(String str) {
        return new LinkedHashSet<>(Arrays.asList(str.split(""))).stream().reduce("", String::concat);
    }

    public static void main(String[] args) {
        String input = "hello";
        System.out.println(removeDuplicates(input));
    }
}

Output

helo
def removeDuplicates(s):
    return ''.join(sorted(set(s), key=s.index))

input_str = "hello"
print(removeDuplicates(input_str))

Output

helo
<?php
function removeDuplicates($str) {
    return implode('', array_unique(str_split($str)));
}

$input = "hello";
echo removeDuplicates($input);
?>

Output

helo

Time Complexity: O(n * n) 

Auxiliary Space: O(1), Keeps the order of elements the same as the input. 

Conclusion:

Removing duplicates from a string is a common task encountered in various programming scenarios. Each of the presented methods offers a unique approach to solving this problem efficiently. Whether you're working with PHP, C, C++, JavaScript, Python, or Java, you now have a range of solutions at your disposal to Remove Duplicates From a Given String Using PHP, C, C++, JavaScript, Python, or Java. Choose the method that best fits your requirements and optimize your code for cleaner, more manageable data processing.

       

Advertisements

ads