Implement an space efficient algorithm to determine if a string (of characters from ‘a’ to ‘z’) has all unique characters or not. Use additional data structures like count array, hash, etc is not allowed.
Expected Time Complexity : O(n)
Input : str = "aaabbccdaa" Output : No Input : str = "abcd" Output : Yes
The idea is to use an integer variable and use bits in its binary representation to store whether a character is present or not. Typically an integer has at-least 32 bits and we need to store presence/absence of only 26 characters.
Below is the implementation of the idea.
Time Complexity : O(n)
Auxiliary Space : O(1)
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Efficiently find first repeated character in a string without using any additional data structure in one traversal
- Python program to check if a string contains all unique characters
- Minimum deletions from string to reduce it to string with at most 2 unique characters
- Determine if a string has all Unique Characters
- Minimize number of unique characters in string
- String with maximum number of unique characters
- Find the longest substring with k unique characters in a given string
- Check if an encoding represents a unique binary string
- Ropes Data Structure (Fast String Concatenation)
- Check whether second string can be formed from characters of first string
- Quick way to check if all the characters of a string are same
- Check if both halves of the string have same set of characters
- Check if the characters of a given string are in alphabetical order
- Check if a given string is made up of two alternating characters
- Check whether the frequencies of all the characters in a string are prime or not