Lesson 5.9 · Write it
First repeat in a row
A functionPython or Java12 tests, 8 of them hidden
On a phone? Put the lines in order instead
Write a function that searches a list (an array in Java) of whole numbers for the first value that is equal to the value just before it, and returns that value's position (its index). Positions start at 0.
- Return the position of the later value of the pair, not the earlier one.
- If there is more than one such pair, return the position for the first pair.
- If no value is equal to the value just before it, return
-1. - The list can be empty, and has at most 20 values. Every value is between -1000 and 1000.
Only the number your function returns is checked.
def first_repeat(values: list[int]) -> int
Examples
Your function is tested on 12 cases: the 4 examples below, and 8 hidden ones that check the rules above.
- first_repeat([4, 7, 7, 2]) should return 2: the 7 at position 2 equals the one before it, so 2, the later of the pair (rule 1)
- first_repeat([3, 3, 5, 5]) should return 1: two pairs, and the first pair wins (rule 2)
- first_repeat([1, 2, 3]) should return -1: no value equals the one before it (rule 3)
- first_repeat([]) should return -1: an empty list (rules 3 and 4)
public static int firstRepeat(int[] values)
Running Java here comes later. You can put this answer's lines in order instead. You can still write your Java answer (it stays while this page is open) and compare it with our worked solution. Or try this exercise in Python.Checking whether Java answers can run here.
Examples
Your function is tested on 12 cases: the 4 examples below, and 8 hidden ones that check the rules above.
- firstRepeat(new int[]{4, 7, 7, 2}) should return 2: the 7 at position 2 equals the one before it, so 2, the later of the pair (rule 1)
- firstRepeat(new int[]{3, 3, 5, 5}) should return 1: two pairs, and the first pair wins (rule 2)
- firstRepeat(new int[]{1, 2, 3}) should return -1: no value equals the one before it (rule 3)
- firstRepeat(new int[]{}) should return -1: an empty list (rules 3 and 4)