Last active
November 19, 2018 13:41
-
-
Save pmav99/9fe028abcaa13958d955192e20bb8261 to your computer and use it in GitHub Desktop.
Get the first unique character of a string. Python - single traversal solution
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| # -*- coding: utf-8 -*- | |
| from collections import OrderedDict | |
| def find_index_of_first_unique_char(string): | |
| seen_once = OrderedDict() # LinkedHashMap | |
| seen_many = set() # HashSet | |
| for index, char in enumerate(string): # O(N) | |
| if char not in seen_many: # O(1) | |
| if char in seen_once: # O(1) | |
| seen_many.add(char) # O(1) | |
| seen_once.pop(char) # O(1) | |
| else: | |
| seen_once[char] = index # O(1) | |
| if not seen_once: # O(1) | |
| return -1 | |
| else: | |
| return seen_once.popitem(last=False)[1] # O(1) | |
| assert find_index_of_first_unique_char("") == -1 | |
| assert find_index_of_first_unique_char("aa") == -1 | |
| assert find_index_of_first_unique_char("baa") == 0 | |
| assert find_index_of_first_unique_char("zabcddd") == 0 | |
| assert find_index_of_first_unique_char("this is my string") == 1 | |
| assert find_index_of_first_unique_char("this this is my string") == 13 | |
| assert find_index_of_first_unique_char("this this is my string add an m") == 14 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| # -*- coding: utf-8 -*- | |
| def find_index_of_first_unique_char(string): | |
| seen_once = dict() # LinkedHashMap | |
| seen_many = set() # HashSet | |
| for index, char in enumerate(string): # O(N) | |
| if char not in seen_many: # O(1) | |
| if char in seen_once: # O(1) | |
| seen_many.add(char) # O(1) | |
| seen_once.pop(char) # O(1) | |
| else: | |
| seen_once[char] = index # O(1) | |
| if not seen_once: # O(1) | |
| return -1 | |
| else: | |
| for char in seen_once: # O(1) γιατί επιστρέφουμε στη πρώτη επανάληψη | |
| return seen_once[char] | |
| assert find_index_of_first_unique_char("") == -1 | |
| assert find_index_of_first_unique_char("aa") == -1 | |
| assert find_index_of_first_unique_char("baa") == 0 | |
| assert find_index_of_first_unique_char("zabcddd") == 0 | |
| assert find_index_of_first_unique_char("this is my string") == 1 | |
| assert find_index_of_first_unique_char("this this is my string") == 13 | |
| assert find_index_of_first_unique_char("this this is my string add an m") == 14 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment