Problemsparse vector with zero accounting

Session: Sign in to solve

Solution.txt

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 getValue returns its most recently assigned value or zero when it has no nonzero assignment.
  • Replace one position. setValue replaces the selected position's current value; repeated assignments never create multiple logical values for one index.
  • Account for zeros. getNumberZeros equals length minus the number of nonzero positions, including after every zero-to-nonzero, nonzero-to-zero, and nonzero-to-nonzero assignment.
  • Clear a range. clearRange sets 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 VectorBoundsError before 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.

SignatureReturnsBehavior
SparseVector(length: integer)Not applicableCreates a fixed-length vector whose positions initially equal zero.
setValue(index: integer, value: integer)voidApplies Replace one position, Account for zeros, and Reject invalid bounds atomically.
getValue(index: integer)integerApplies Read logical values and Reject invalid bounds atomically.
getNumberZeros()integerApplies Account for zeros.
clearRange(startInclusive: integer, endExclusive: integer)voidApplies Clear a range, Account for zeros, and Reject invalid bounds atomically.

Examples

For SparseVector(8):

StepOperationResult
1setValue(1, 4)No return value
2setValue(5, -3)No return value
3getNumberZeros()6
4clearRange(1, 5)No return value
5getValue(1)0
6getValue(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.

PRIVATE WORKSPACE

Checking your session…

The statement is public. The editor, editorial, submissions, and saved work are private.