From 68d41625405994c9e006a1ae2a0357856aff139f Mon Sep 17 00:00:00 2001 From: NavpreetDevpuri Date: Sat, 30 Oct 2021 17:58:32 +0530 Subject: [PATCH 1/3] added is_contains_unique_chars() --- strings/is_contains_unique_chars.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 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 000000000000..44f3f3b532bb --- /dev/null +++ b/strings/is_contains_unique_chars.py @@ -0,0 +1,28 @@ +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 + """ + bitmap = 0 + for ch in input_str: + ch_unicode = ord(ch) + ch_bit_index_on = pow(2, ch_unicode) + + if bitmap & ch_bit_index_on == ch_bit_index_on: + return False + + bitmap |= ch_bit_index_on + + return True + + +if __name__ == "__main__": + import doctest + + doctest.testmod() From cea6223f7799e1099103f5094dec0e3c61f47358 Mon Sep 17 00:00:00 2001 From: NavpreetDevpuri Date: Sat, 30 Oct 2021 18:33:19 +0530 Subject: [PATCH 2/3] added is_contains_unique_chars() --- strings/is_contains_unique_chars.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/strings/is_contains_unique_chars.py b/strings/is_contains_unique_chars.py index 44f3f3b532bb..4b036d40ea1c 100644 --- a/strings/is_contains_unique_chars.py +++ b/strings/is_contains_unique_chars.py @@ -9,16 +9,18 @@ def is_contains_unique_chars(input_str: str) -> bool: 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' bitmap = 0 for ch in input_str: ch_unicode = ord(ch) ch_bit_index_on = pow(2, ch_unicode) - if bitmap & ch_bit_index_on == ch_bit_index_on: + # 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 From 7ef5ae66d777e8ed702993c6aa9270e0669cb0c6 Mon Sep 17 00:00:00 2001 From: NavpreetDevpuri Date: Sat, 30 Oct 2021 18:40:20 +0530 Subject: [PATCH 3/3] added stackoverflow reference --- strings/is_contains_unique_chars.py | 1 + 1 file changed, 1 insertion(+) diff --git a/strings/is_contains_unique_chars.py b/strings/is_contains_unique_chars.py index 4b036d40ea1c..fdf7a02ff43f 100644 --- a/strings/is_contains_unique_chars.py +++ b/strings/is_contains_unique_chars.py @@ -12,6 +12,7 @@ def is_contains_unique_chars(input_str: str) -> bool: # 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)