How to get the order relationship between string elements in linear time?

86 Views Asked by At

I have a string and I want to get the order relationship between string elements in linear time.

For example, the string "abc", there are three partial order relations, namely ab, bc, ac

1

There are 1 best solutions below

0
On

If you want to generate all the ordered pairs - well there are n^2 of those, so you won't even be able to print them in linear time.

However, if you just need to be able to lookup the ordering of two characters for some larger algorithm (and they are all unique in the original string): You could build a map of characters to their index in the string in a single pass (linear time). Then, whenever you need to know the ordering of a given pair, look up and compare their indices in constant time.