algorithm - Find non-unique characters in a given string in O(n) time with constant space i.e with no extra auxiliary array -
Given a string that contains only lower case letters (az),
for pre , If the string s = "aabcacdddec"
output: ACD
3 approaches to this problem exist:
-
[Brute force] Check every four letters (i.e. s [i] with each other and print if both are the same) Complexity of time: o (n ^ 2) space complexity: o (1)
< Li> -
[Store character count in an array] An array of size 26 (keeping one-jade track ) And for every S [i], index = s [i] - 26 is stored in the array. Finally find the array and print all the elements (i.e. 'A' A 'I') with the value greater than the complexity of time: o (n) space complexity: o (1), but we have a different array for accumulating the frequency of each element.
after sorting (sort and after attache Comparison) (O (n log (n) in time), cross the string and check if s [i] ns [i + 1] are equal time complexity: hey (n logan) + o (n) = O (N Logan) Space complexity: o (1)
Is there an O (N) approach that does not use any array / hash table / map (etc)?
Hint: Use the bit vector
It is, therefore generally Speaking - No o (n)
There is no way to solve in no extra space.
However , if you consider the alphabet as an continuous shape (as an only character is very constant) you can either create a bitset of these letters, O (1)
in space [it is stable!] Or O (n) can check each letter
If it repeats more than once, then it O (continuous * n)
, which is still in O (n)
.
For Pseudo Code 1 solution:
Bit saw [] = new bit [SIZE_OF_ALPHABET] // contant! Bit printed [] = new [SIZE_OF_ALPHABET] // That's it! I saw in each eye Length: // init: seen [i] = 0 printed [i] = 0 for each string in c string: // Strange transpose: i = intValue (c) // has already seen it Do not print? Now print it! If seen [i] == 1 and printed [i] == 0: printed printed [i] = 1 other: seen [i] = 1
2 code for the pseudo code :
for each letter az: // constant number of repetition o (1) string has count = 0 for each character x: // hey (n) if x == c : Calculation == 1 if calculation & gt; 1 print number
Comments
Post a Comment