Constraints

  • Can I assume the string is ASCII?
    • Yes
    • Note: Unicode strings could require special handling depending on your language

Test Case

  • "a" from "tamamdir arAda" -> "tmmdir rAd"

Algorithm

Since Python strings are immutable, we'll use a list of chars instead to exercise in-place string manipulation as you would get with a C string.

create a list as a string builder

  • for each character in string
    • checks whether the current char is not equal to removalChar
    • keep the char in the list

Complexity:

  • Time: O(n)
  • Space: O(n)

In [45]:
def remove_char(string, char):
    newString = []
    for i in string:
        if char != i:
            newString.append(i)
    return "".join(newString)

Pythonic way

You can achive the same goal in a concise way by using python's string modidication methods as follows:


In [46]:
def remove_char2(string, char):
    return string.translate(None, char)

def remove_char3(string, char):
    return string.replace(char, "")

Unittests


In [47]:
from nose.tools import assert_equal


def testWith(func):
    assert_equal(func("tamamdir arAda", "a"), "tmmdir rAd")
    assert_equal(func("wlkwlkfew wifiw longgglonggggw", "w"), "lklkfe ifi longgglongggg")
    assert_equal(func("yu*lkke*", "*"), "yulkke")
    
    print('Success')
testWith(remove_char)
testWith(remove_char2)
testWith(remove_char3)


Success
Success
Success

Benchmark


In [49]:
import timeit
print "remove_char", timeit.timeit(
    "remove_char('wlkwlkfew wifiw longgglonggggw', 'a')",
    "from __main__ import remove_char", number=1200000)
print "remove_char2", timeit.timeit(
    "remove_char2('wlkwlkfew wifiw longgglonggggw', 'a')",
    "from __main__ import remove_char2", number=1200000)
print "remove_char3", timeit.timeit(
    "remove_char3('wlkwlkfew wifiw longgglonggggw', 'a')",
    "from __main__ import remove_char3", number=1200000)


remove_char 5.82854199409
remove_char2 0.402535915375
remove_char3 0.377779960632

In [ ]: