remove_duplicates.py 965 B

12345678910111213141516171819202122232425262728293031323334
  1. # Design an algorithm that removes the duplicate characters in a string
  2. # without using additional buffer.
  3. import pytest
  4. def test_remove_duplicates():
  5. case1 = ''
  6. case2 = 'a'
  7. case3 = 'asdfghjkl'
  8. case4 = 'aasdee'
  9. assert remove_duplicates(case1) == ''
  10. assert remove_duplicates(case2) == 'a'
  11. assert remove_duplicates(case3) == 'asdfghjkl'
  12. assert remove_duplicates(case4) == 'asde'
  13. pytest.main()
  14. # use two indicies to track non-duplicates in place.
  15. # time complexity: O(n)
  16. # space complexity: O(1)
  17. def remove_duplicates(input):
  18. len_input = len(input)
  19. if len_input <= 1:
  20. return input
  21. else:
  22. list_input = list(input)
  23. len_non_dup = 1
  24. for j in range(1, len_input):
  25. if list_input[j] in list_input[:len_non_dup]:
  26. pass
  27. else:
  28. list_input[len_non_dup] = input[j]
  29. len_non_dup += 1
  30. return ''.join(list_input[:len_non_dup])