From 21c99d2ae294d08893bd0160cd9aacc2ad3ca556 Mon Sep 17 00:00:00 2001 From: Navpreet Singh Devpuri Date: Sun, 31 Oct 2021 01:34:46 +0530 Subject: [PATCH] added is_contains_unique_chars() (#5701) * added is_contains_unique_chars() * added is_contains_unique_chars() * added stackoverflow reference --- strings/is_contains_unique_chars.py | 31 +++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 strings/is_contains_unique_chars.py diff --git a/strings/is_contains_unique_chars.py b/strings/is_contains_unique_chars.py new file mode 100644 index 000000000..fdf7a02ff --- /dev/null +++ b/strings/is_contains_unique_chars.py @@ -0,0 +1,31 @@ +def is_contains_unique_chars(input_str: str) -> bool: + """ + Check if all characters in the string is unique or not. + >>> is_contains_unique_chars("I_love.py") + True + >>> is_contains_unique_chars("I don't love Python") + False + + Time complexity: O(n) + Space compexity: O(1) 19320 bytes as we are having 144697 characters in unicode + """ + + # Each bit will represent each unicode character + # For example 65th bit representing 'A' + # https://stackoverflow.com/a/12811293 + bitmap = 0 + for ch in input_str: + ch_unicode = ord(ch) + ch_bit_index_on = pow(2, ch_unicode) + + # If we already turned on bit for current character's unicode + if bitmap >> ch_unicode & 1 == 1: + return False + bitmap |= ch_bit_index_on + return True + + +if __name__ == "__main__": + import doctest + + doctest.testmod()