I recently asked this question in one of my telephone interviews.
"There is a list of elements, and you should find the" best "element from the list. The elements are comparable to each other, but the comparison is not transitional . For example. If A> B and B> C, then A should not be greater than C.
You should return the best item as an answer, which is better than any other item in the list. It is possible that there is no such element. In this case, return null. "
My decision:
Attempt 1:
The simple solution is O (n ^ 2) . Comparison of each element with another element.
The interviewer was not satisfied.
Attempt 2:
Start comparing the first item with the second item and on. For any element "E", if A> E, mark E (maybe using another array / list / etc.) And do not consider E for further comparison. This is because there is at least one element that is better than E, so E is definitely not the answer.
The complexity is still O (n ^ 2) with some improvement over the previous attempt.
He was still not satisfied. Can anyone come up with some better solution?
source share