Amazon Interview Question
Software Engineer / DevelopersYou can do it in one pass with constant space. No extra space if you can destroy the array.
Just realized that the example above in a little misleading. My code assumed that the characters are sorted. In this case to get a complexity of O(n) we would need some extra storage.
Create an array of size 256 with all elements initialized to 0. Scan the string(str) and increment the appropriate position(str[i]-'a') in the array for each character. Then scan the array and the entry with an odd number is the character that occurs odd number of times.
But why do we require array[256]? isnt array[26] not enough??
can you plz take a alphabet and show i.
@Ravi
Ur code doesnt run in all the cases. What if there are two characters occuring odd # of times in src string. It doesnt run.
apologies!!
i dint see the phrase "one value" in problem statement.
Runs perfectly fine ..!!! :)
If external storage(like a hash table with the value as the index) is allowed, then we only need to traverse the string once, whenver one value is seen, just increment the counter associated with that value in the table.
- ultraviolet January 31, 2007After the traversal, look at the table and output if odd occurrences are seen.