# Minimizing $L_2$ norm of a vector with two distinct entries

Let $$d\in\mathbb N$$ and denote $$V=\bigcup_{a,b\in\mathbb R}\{a,b\}^d$$, the set of all vectors with two distinct values.

Given a vector $$x\in \mathbb R^d$$, I want to compute some $$v^*\in V$$ such that $$\left\lVert x-v^*\right\rVert_2\le \left\lVert x-v\right\rVert_2$$ for any $$v\in V$$.

What would be the fastest algorithm to compute $$v^*$$?

It seems possible to show that the problem is equivalent to finding a threshold $$T\in\mathbb R$$ such that $$v^*_i=\begin{cases}a & \mbox{if x_i, where $$a$$ is the mean of all entries smaller than $$T$$ and $$b$$ is the mean of all entries larger than or equal to $$T$$.

This suggests a $$O(d^2)$$ time algorithm. Can we find the optimal $$T$$ faster?

I am also interested in an extension of the problem where we look at $$V_4=\bigcup_{a,b,c,z\in\mathbb R}\{a,b,c,z\}^d$$ instead of $$V$$. How fast can we find $$v^*$$ in this setting?

• Assuming the unit-cost RAM model, the algorithm you outline in the question does not require time $O(d^2)$, it can be implemented using $O(d\log d)$ operations ($O(d\log d)$ comparisons and $O(d)$ additions and multiplications). Sort the vector, and the for each $i\le d$, try $a={}$ the mean of the first $i$ entries, and $b$ the mean of the remaining entries. Now, the mean $\bar v$ of $v_1,\dots,v_i$ and the squared distance $\sum_{j\le i}(\bar v-v_j)^2$ can be computed using $O(1)$ operations if you know $\sum_{j\le i}v_j$ and $\sum_{j\le i}v_j^2$, and these two quantities can be updated ... – Emil Jeřábek Dec 17 '20 at 20:28
• ... with $O(1)$ operations while adding or removing one element from the list. – Emil Jeřábek Dec 17 '20 at 20:30
• @EmilJeřábek - thanks, that's a cool improvement. Any thoughts on whether a linear algorithm is possible here? – M A Dec 17 '20 at 20:45
• @SarielHar-Peled But the hypercube is not fixed in advance, this is what you need to optimize. So what is “the nearest neighbour in the first coordinate”? And how do you make sure each coordinate separately gives the same values of $a$ and $b$? If $a$ and $b$ is fixed, the problem is indeed trivial: you just put $v_i^*=a$ if $x_i<(a+b)/2$, and $v_i^*=b$ otherwise. – Emil Jeřábek Dec 18 '20 at 7:37
• Yeh. My brain is dead. – Sariel Har-Peled Dec 19 '20 at 16:59

## 1 Answer

(This is probably a comment but I cannot comment)

This seems to be 1-dimensional $$k$$-means clustering for $$k=2$$ and $$k=4$$. Here is a reference that gives a $$O(kn + n \log n)$$ algorithm for 1-d $$k$$-means clustering: Grønlund, Larsen, Mathiasen, Nielsen, Schneider, Song, Fast Exact k-Means, k-Medians and Bregman Divergence Clustering in 1D. It seems similar to the algorithm given in the comments.