[15 Feb 2020] Remove duplicates from a string in O(1) extra space
Remove duplicates from a string in O(1) extra space
Given a string str of lowercase characters, the task is to remove duplicates and return a resultant string without modifying the order of characters in the original string.
Examples:
Input: str = "geeksforgeeks" Output: geksfor Input: str = "characters" Output: chartes
Approach: The idea is to use bits of a counter variable to mark the presence of a character in the string. To mark the presence of ‘a’ set 0th bit as 1, for ‘b’ set 1st bit as 1 and so on. If the corresponding bit of character present in the original string is set to 0, it means it is the first occurrence of that character, hence set its corresponding bit as 1 and keep on including the current character in the resultant string.
Output:
geksfor
Time Complexity: O(n)
Space Complexity: O(1)
Space Complexity: O(1)
Output:
geksfor
Time Complexity: O(n)
Space Complexity: O(1)
Space Complexity: O(1)
Output:
geksfor
Time Complexity: O(n)
Space Complexity: O(1)
Space Complexity: O(1)
Comments
Post a Comment