Program to Remove Common Characters From Given Strings

In many java interviews, it is asked this question to compare two strings and remove the common character from the given strings to check the programming aptitude.

For example, suppose there are two string, s1 = "selected" and s2 = "rejected" and after removal of common character the value of s1 and s2 becomes bcgh and sd respectivly.

Following is the kotlin program to remove the common characters from any given strings.

fun removeCommonCharacter(s1: String, s2: String) {
    var s1 = s1
    var s2 = s2
    println("Before removing common character s1 : $s1")
    println("Before removing common character s2 : $s2")
    var commonChars = ""

    for (i in 0 until s1.length) {
        for (j in 0 until s2.length) {
            if (s1[i] == s2[j]) {
                commonChars += s1[i]

    for (i in 0 until commonChars.length) {
        val charToRemove = commonChars[i] + ""
        s1 = s1.replace(charToRemove, "")
        s2 = s2.replace(charToRemove, "")
    println("After removing common character : $s1")
    println("After removing common character : $s2")

fun main(args: Array<String>) {
    removeCommonCharacter("pre destination", "final destination")


Before removing common character s1 :  pre destination
Before removing common character s2 :  final destination
After removing common character :  pr
After removing common character :  fl

Join My Facebook Group
Join Group

About Author

Myself KarthiQ, I am the author of this blog, I know ways to write a good article but some how I donot have the skills to make it to reach people, would you like help me to reach more people By sharing this Article in the social media.

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions