All practice tasks

Coding (Algo)

Keep the Nearest Measurements

Bounded heap · Medium

A diagnostic picker chooses k recorded values nearest to a requested target. It must break equal-distance ties consistently and preserve duplicate occurrences. A small result should not require retaining a second full copy of the batch.

Return up to k values ordered by distance to target then value then original index using O(k) additional selection storage.

Input

Call

  • Implement solve(input) and return the result. The provided adapter handles JSON input and output.

Input shape

{ nums: integer[], target: integer, k: integer }

Fields

  • nums is the measurement batch; target is the comparison value; k limits the number of returned entries.

Output

Return value

  • Return values, not distances or indexes. Sort by absolute distance ascending, then numeric value ascending, then original index ascending.
  • Duplicate entries remain separate. k = 0 returns []; k greater than n returns every entry in the required order.

Constraints

  • 0 <= nums.length <= 100000; values are signed integers between -1000000000 and 1000000000.
  • -1000000000 <= target <= 1000000000; 0 <= k <= 100001.

Examples

Example 1

{
  "k": 3,
  "nums": [
    8,
    2,
    6,
    4
  ],
  "target": 5
}

Returns

[
  4,
  6,
  2
]

Example 2

{
  "k": 2,
  "nums": [
    2,
    2,
    3
  ],
  "target": 2
}

Returns

[
  2,
  2
]

Required complexity

O(n log(k + 1) + k log(k + 1)) time and O(min(n,k) + 1) auxiliary space

What this task practices

Keep the Nearest Measurements is a coding (algo) interview exercise that trains prompt interpretation, explicit assumptions, a concrete response, and a clear explanation of tradeoffs. The catalog marks it as medium difficulty. It focuses on Technical Reasoning, Testing, Validation. The signed-in workspace provides the tools for the round and evaluates the attempt against task-specific criteria. Reference solutions, hidden checks, evaluator instructions, and candidate work remain private.

Sign in to startThe workspace and evaluation open after sign in.