chore(Python): add remove duplicate and first non-repeating character string (#312)

pull/315/head
Sankalp Sharma 2021-05-18 21:12:29 +05:30 committed by GitHub
parent 0fd4ca4b1d
commit b1e5e4c35f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 66 additions and 0 deletions

View File

@ -34,3 +34,5 @@
1. [Is Good Str](strings/is_good_str.py)
2. [Palindrome](strings/palindrome.py)
3. [Word Count](strings/word_count.py)
4. [Remove Duplicates from a String](strings/remove_duplicates_from_a_string.py)
5. [First Non Repeating Character](strings/first_non_repeating_character.py)

View File

@ -0,0 +1,33 @@
"""
Output the first character which occurred once in the string
I/P: "abcbadabfaa"
O/P: "c" (-1 if no such character is there)
Time Complexity: O(n)
Space Complexity: O(26) => O(1)
"""
string = "abcbadabfaa" # Constraint: only smallcase letters are there
def first_non_repeating_character(string):
"""
One way to do this is to have two dictionaries one which keeps the count of character,
other dictionary will keep the first appearance of the character (index).
After a traversal. Look in first dictionary for characters occurring once and output the one which
has the first appearance as per second dictionary.
Since in this case we have special constraint in mind. We will go with a cleverer way by reducing more stack space.
"""
n = len(string)
occurrence = [n]*26
for i in range(len(string)):
index = ord(string[i])-ord('a')
if index < 0 or index > 25:
return ("Invalid")
if occurrence[index] == n:
occurrence[index] = i
else:
occurrence[index] += n
return string[min(occurrence)] if min(occurrence) < n else -1
if __name__ == "__main__":
print(first_non_repeating_character(string))

View File

@ -0,0 +1,31 @@
"""
Remove all duplicates from a string
I/P: "bbaaccdefabafaz"
O/P: "bacdefz"
Time Complexity: O(n)
Space Complexity: O(26) (constant)
"""
string = "bbaaccdefabafaz" # Constraint: only smallcase letters are there
def remove_duplicate(string):
alphabet = "0" * 26 # instead of going for classic use of sets, dictionaries we can use string containing bits. Either way is fine.
ans_string = ""
for letter in string:
index = ord(letter)-ord('a')
if index < 0 or index > 25:
return ("Invalid")
if alphabet[index] == "1":
pass
else:
index = ord(letter)-ord('a')
if index == 0:
alphabet = "1" + alphabet[1:]
else:
alphabet = alphabet[0:index] + "1" + alphabet[index+1:]
ans_string += letter
return ans_string
if __name__ == "__main__":
print(remove_duplicate(string))