TypeScriptEasySorting & Searching10 min

Search a sorted array

Given a strictly increasing array and a target, return its zero-based index or -1 when absent. Inputs are valid JSON and must not be modified unless the algorithm uses a local copy. This exercise probes typed data modeling, boundary handling, and algorithm selection.

Input

One JSON value: { values: number[]; target: number }. See the sample for its exact shape.

Output

One compact JSON value of type number. Strings include JSON quotes; arrays preserve the specified order.

Constraints

Array/string lengths are 0 to 10000 unless stated otherwise. Numbers are integers in [-1000000,1000000]; all computed results fit the safe integer range.

Example

Input

{"values":[1,3,5,9],"target":5}

Output

2

Example 2 input

{"values":[1,2,3,4],"target":4}

Output

3

Checks a boundary or contrasting case beyond the public examples.

Public test cases (2)

  • Input

    {"values":[1,3,5,9],"target":5}

    Expected output

    2
  • Input

    {"values":[],"target":1}

    Expected output

    -1
Hints (2)
  1. Start with the required output order and the empty-input behavior.
  2. Halve the remaining search interval

Target complexity: time O(log(n+1)) · space O(1)

Your solution

Checking runner availability…

Reference solution

Sign in for solution
All TypeScript programs