# Sum of sparse array in linear time

Let $n=(n_{1},…,n_{d})$. Define $xmodn=(x_{1}modn_{1},…,x_{d}modn_{d})$. We want to represent an $d$-dimensional array. Assume $A$ and $B$ are both $d$-dimensional arrays of size $n$ and one have $m$ non-zero elements one have $m_{′}$ non-zero elements. The following operations should be supported.

- $circshift(A,r)$ creates a new sparse array $C$, such that $C((i+r)modn)=A(i)$. This is the circshift operation in matlab. Running time should be $O(m)$.
- Similarly, we can define $shift(A,t)$, such that $C(i+t)=A(i)$, if $i+t$ is outside the range, we have $0$ instead.
- $A+B$ returns a sparse array $C$ such that $C(i)=A(i)+B(i)$ in $O(m+m_{′})$ time.
- $elements(A)$ output all elements with associated coordinates in $A$ in $O(m)$ time.
- $initialize(x,n)$ create a new sparse array with size $n$ and one element $x$ initialized at $0$ position.

We create a sparse list with $d−1$ dimension slices, and the lower dimension slices can be handled inductively. All we need to do is to implement sparse list. The list should store the position and value pairs ordered by position. Sum can be done with a merge operation. circshift go though all elements one by one and update the position, and then rotate the list so the smallest position is in the beginning.

This data structure can be useful output sensitive dynamic programming problems. For example, multidimensional subset sum have a simple recursive solution.

- Input $S={s_{1},…,s_{n}}$
- $X←{0}$.
- For $i$ from $1$ to $n$, $X←X∪{x+s_{i}∣x∈X}$.
- Return $X$

The running time is $O(∣S∣∣X∣)$, where $X$ is the final output, since ${x+s_{i}∣x∈X}$ is a shift, and union is just a sum. Using circshift, it can produce a output sensitive algorithm for subset sums in finite abelian groups.