Skip to content
ExamSpine

Lesson 7.5 · Write it

Where is it?

A functionPython or Java11 tests, 7 of them hidden

On a phone? Put the lines in order instead

Write a function that does a linear search: it looks through a list (an array in Java) of whole numbers, from the start, for a target value.

  1. Return the index of the target, counting from 0.
  2. If the target is in the list more than once, return the index of the first one.
  3. If the target is not in the list, return -1.
  4. The list can be empty.

Do not use a ready-made search such as values.index(target) (indexOf in Java): write the loop. Only the value your function returns is checked.

def position_of(values: list[int], target: int) -> int

You cannot use these in this question:

  • .index()
  • import operator

This question is about writing the linear search yourself, so ready-made searches are not allowed.

Examples

Your function is tested on 11 cases: the 4 examples below, and 7 hidden ones that check the rules above.

  • position_of([4, 8, 15, 16], 15) should return 2: the target is in the middle (rule 1)
  • position_of([4, 8, 15, 16], 5) should return -1: the target is not there (rule 3)
  • position_of([3, 9, 3, 9], 9) should return 1: the target is there twice: the first one counts (rule 2)
  • position_of([9, 1, 2], 2) should return 2: the target is the last value (rule 1)

public static int positionOf(int[] values, int target)

Checking whether Java answers can run here.

You cannot use these in this question:

  • Arrays.asList()
  • Arrays.binarySearch()
  • .indexOf()
  • .contains()

This question is about writing the linear search yourself, so ready-made searches are not allowed.

Examples

Your function is tested on 11 cases: the 4 examples below, and 7 hidden ones that check the rules above.

  • positionOf(new int[]{4, 8, 15, 16}, 15) should return 2: the target is in the middle (rule 1)
  • positionOf(new int[]{4, 8, 15, 16}, 5) should return -1: the target is not there (rule 3)
  • positionOf(new int[]{3, 9, 3, 9}, 9) should return 1: the target is there twice: the first one counts (rule 2)
  • positionOf(new int[]{9, 1, 2}, 2) should return 2: the target is the last value (rule 1)
solution.pySolution.java

Report a problem with this page