>>27 here.
I think I have a good O(n) algorithm. Can anyone break it?
Basically I compensate for faux lists by these assumptions, given our x,y,z tuple as the state:
* It's ALWAYS okay to, given a smaller number than the last value taken, reset the value of x to this value. At this point we save the current value of x as x_earlier.
* We're then guaranteed to get another number greater than the resetted x, if indeed there is one remaining in the list; if not, the list is invalid anyway.
* If at the end of the list we only have x and y populated, no big deal, we re-arrange our tuple to (x_earlier,x,y) giving our x,y,z values.
function indices(array){
var x_earlier = null;
var x = null;
var y = null;
var z = null;
for (i = 0; i < array.length; i++) {
if(x!=null && y!=null & z!=null) break;
if(x == null) {
x = array
[i];
}
else if(y == null) {
if(array
[i] > x) {
y = array
[i];
} else if(array
[i] < x) {
x_earlier = x;
x = array
[i];
}
}
else if(z == null) {
if(array
[i] > y) {
z = array
[i];
} else if(array
[i] < y){
x_earlier = x;
x = array
[i];
y = null;
}
}
}
var result = [];
if(x!=null) result.push(x);
if(y!=null) result.push(y);
if(z!=null) result.push(z);
if(result.length == 2) result.unshift(x_earlier);
if(result.length != 3) return "NO";
return result;
}
console.log(indices([5, 6, 1, 2, 3]));
console.log(indices([1, 5, 2, 3]));
console.log(indices([5, 6, 1, 2, 7]));
console.log(indices([5, 6, 1, 2, 7, 8]));
console.log(indices([1, 2, 999, 3]));
console.log(indices([999, 1, 2, 3]));
[1, 2, 3]
[1, 2, 3]
[1, 2, 7]
[1, 2, 7]
[1, 2, 999]
[1, 2, 3]