Sparse Vector With Zero Accounting
Problem
Design SparseVector to represent a fixed-length integer vector without allocating storage for every logical position. Calls are sequential on one shared instance.
Requirements
- Read logical values. Every position initially equals zero, and
getValuereturns its most recently assigned value or zero when it has no nonzero assignment. - Replace one position.
setValuereplaces the selected position's current value; repeated assignments never create multiple logical values for one index. - Account for zeros.
getNumberZerosequalslengthminus the number of nonzero positions, including after every zero-to-nonzero, nonzero-to-zero, and nonzero-to-nonzero assignment. - Clear a range.
clearRangesets every position in[startInclusive, endExclusive)to zero and leaves every position outside that half-open interval unchanged. - Reject invalid bounds atomically. An invalid point index or range throws
VectorBoundsErrorbefore changing any logical value, sparse entry, or zero count.
API
A point index is valid when 0 <= index < length. A clear range is valid when 0 <= startInclusive < endExclusive <= length.
| Signature | Returns | Behavior |
|---|---|---|
SparseVector(length: integer) | Not applicable | Creates a fixed-length vector whose positions initially equal zero. |
setValue(index: integer, value: integer) | void | Applies Replace one position, Account for zeros, and Reject invalid bounds atomically. |
getValue(index: integer) | integer | Applies Read logical values and Reject invalid bounds atomically. |
getNumberZeros() | integer | Applies Account for zeros. |
clearRange(startInclusive: integer, endExclusive: integer) | void | Applies Clear a range, Account for zeros, and Reject invalid bounds atomically. |
Examples
For SparseVector(8):
| Step | Operation | Result |
|---|---|---|
| 1 | setValue(1, 4) | No return value |
| 2 | setValue(5, -3) | No return value |
| 3 | getNumberZeros() | 6 |
| 4 | clearRange(1, 5) | No return value |
| 5 | getValue(1) | 0 |
| 6 | getValue(5) | -3 |
Constraints
1 <= length <= 1,000,000,000- Values are signed 64-bit integers and may be negative, zero, or positive.
- At most 50,000 method calls and 50,000 nonzero positions occur per testcase.
- Storage must not be proportional to
length. - Range clearing must inspect sparse state rather than every logical position in the range.
- The vector length never changes.
Notes
Point indices and ranges may be invalid only in cases that expect VectorBoundsError. All other calls satisfy the constraints.