The theme comes back
- O(n²) · Very hard
- Full plan
- Python
- JavaScript
- lists
- loops
- indexes
Problem
In a symphony, the theme comes back later on, sometimes higher and sometimes lower: every note moves up or down by the same amount, and the ear still recognizes it.
Write a function that takes melody and theme, lists of integers with the pitch of each note (the theme has at least one; the melody may be empty). Return an integer: the first index of melody where as many notes in a row as the theme has begin, each one equal to the theme's note in that spot plus one same amount d. d can be positive, negative or 0, which is the theme as it is. If it never shows up, return -1.
With melody [4, 9, 11, 13, 2] and theme [1, 3, 5]: not from index 0, because the 4 goes up 3 and the 9 goes up 6. From 1 it works: 9, 11 and 13 are 1, 3 and 5 moved up 8 each. The answer is 1.
Examples
The example
[4, 9, 11, 13, 2], [1, 3, 5] → 1
As it is
[7, 5, 3, 8, 6], [3, 8] → 2
Lower
[10, 20, 5, 3, 7], [15, 13, 17] → 2
A single note
[8, 3], [5] → 0
The theme does not fit
[4, 6], [1, 2, 3] → -1
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def find_theme(melody, theme):
passJavaScript
function findTheme(melody, theme) {
}It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.