Skip to content

Commit 21c99d2

Browse files
added is_contains_unique_chars() (TheAlgorithms#5701)
* added is_contains_unique_chars() * added is_contains_unique_chars() * added stackoverflow reference
1 parent 359e0e7 commit 21c99d2

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

strings/is_contains_unique_chars.py

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
def is_contains_unique_chars(input_str: str) -> bool:
2+
"""
3+
Check if all characters in the string is unique or not.
4+
>>> is_contains_unique_chars("I_love.py")
5+
True
6+
>>> is_contains_unique_chars("I don't love Python")
7+
False
8+
9+
Time complexity: O(n)
10+
Space compexity: O(1) 19320 bytes as we are having 144697 characters in unicode
11+
"""
12+
13+
# Each bit will represent each unicode character
14+
# For example 65th bit representing 'A'
15+
# https://stackoverflow.com/a/12811293
16+
bitmap = 0
17+
for ch in input_str:
18+
ch_unicode = ord(ch)
19+
ch_bit_index_on = pow(2, ch_unicode)
20+
21+
# If we already turned on bit for current character's unicode
22+
if bitmap >> ch_unicode & 1 == 1:
23+
return False
24+
bitmap |= ch_bit_index_on
25+
return True
26+
27+
28+
if __name__ == "__main__":
29+
import doctest
30+
31+
doctest.testmod()

0 commit comments

Comments
 (0)