-1
0
The input is an array (or space-separated string, as you wish), zero-indexed, consisting of one strictly increasing array and one strictly decreasing array (in this order, not other vice versa), each having a length of 2 at least. Example is:
-10 -2 4 18 38 46 28 19 10
The goal is to write the fastest algorithm to find the joint of two sorted arrays.
In other words, the output is the index of the greatest element. In the provided case the output should be 5
.
The input is guaranteed not to contain repeating numbers.
It's obvious that this can be solved with O(n)
with ease, so please provide more interesting faster answers :)
Other test cases (first line is input, second is output):
0 1 4 3
2
1 10 9 8 7 6 5 4 3 1
1
1 3 4 6 7 8 0 -10 -20
5
1 3 5 3 1
2
You could also accept the length of the array as additional input, if needed
Do we get the length of the array for free? Is arbitrary access O(1)? (I'm guessing yes to both, but they are not stated.) – Jonathan Allan – 2018-03-18T21:10:23.653
@Jon yep right, sorry for not mentioning – nicael – 2018-03-18T21:11:09.433
5I believe the fastest will be O(log n) by divide & conquer. – Jonathan Allan – 2018-03-18T21:15:34.217
8Well, too easy for a [tag:fastest-algorithm], IMO. Now the challenge is essentially closed. – user202729 – 2018-03-19T01:08:05.903
@JonathanAllan, well, there's a bit faster solution (I mean, it exists, but not posted here yet) :) – nicael – 2018-03-19T01:22:03.133
@nicael average or worst-case? – ngn – 2018-03-19T01:44:40.103
1@nicael: You've chosen to score this question by asymptotic complexity (fastest-algorithm tag description: "Fastest-algorithm competitions are won by the answer with the smallest asymptotic time complexity. For challenges based on actual runtime, use [fastest-code] instead.") If you're thinking of some constant-factor improvement, it doesn't matter for this challenge. – user2357112 supports Monica – 2018-03-19T01:54:39.037
@ngn the fastest algorithm to solve this task that I know is O(log(m)), where m is the position of the found max element, i.e. the answer. – nicael – 2018-03-19T06:22:51.790
@user2357112 please see the above comment, I'd say it's not a constant factor. – nicael – 2018-03-19T06:23:50.420
1That's average-case O(log(n)), and using the position of the max as a parameter in the time complexity opens things up to too much ambiguity - you could just as easily make the algorithm O(log(n-m)), or O(log(distance of max from array center)), or any number of other ways of prioritizing the search. – user2357112 supports Monica – 2018-03-19T06:44:50.007
1@nicael "Fastest" could mean fastest on average or fastest in the worst case. If it's worst-case, O(log(m)) is indistinguishable from O(log(n)), as m can be anywhere in 0...n-1. If it's on average, O(log(m)) could be asymptotically better, provided there's a strong bias towards smaller m. – ngn – 2018-03-19T11:06:35.033