A singleton is a list whose elements are equal. Some ways of checking this in Mathematica:
{Equal@@#&,
1==Length@Union@#&,
MatchQ[#,{x_ ..}]&}
I started benchmarking:
Table[First@RepeatedTiming[#@RandomInteger[{-10,10},n]]&/@%1,{n,100}]
Table[First@RepeatedTiming[#@RandomInteger[{-10,10},10^n]]&/@%1,{n,6}]
Plotting the transposes of these lists yields
That's disappointing. Clearly none of these functions terminated early after seeing an inequality between a single pair of elements. I've tried a few other functions, the most promising being
If[Null===Do[If[#[[i]]==#[[i+1]],Return@0],{i,Length@#-1}],True,False]&
It does slightly worse than MatchQ
; its running time scales with input too
All SingletonQ
functions are $O(n)$. Is it possible to write a SingletonQ
which is $\Omega(n)$? Or perhaps there is always a linear cost associated with array passing conventions, and a specially allocated array is needed to achieve a constant time function (for a list whose first two elements are unequal; for a uniformly i.i.d. list I believe the running time should mimick $\log_kn$ where $k$ is the sample size for each element, which would be satisfactory to see implemented).
For the curious, here's the four functions evaluated on lists of size 100000Range@10
Interestingly, last two are rougly (in ratio, asymptotically) equivalent in running time.
F = {Apply[Equal], 1 == Length@Union@# &, MatchQ[#, {x_ ..}] &}
andtest[n_Integer] := With[{a = RandomInteger[{-10, 10}, n]}, First[RepeatedTiming[#[a]]] & /@ F]
you'll see thattest[10^6]
andtest[10^8]
give the same result for theMatchQ
algorithm. $\endgroup$Equal@@
andLength@Union
are linear,MatchQ
andDo
are constant. $\endgroup$Equal @@ MinMax[data]
$\endgroup$Equal@@MinMax@#&
seems to have a small linear cost, about 15x faster thanEqual@@#&
but still increasing. $\endgroup$