Problem
Given a list of integers, identify sequences where successive numbers exactly N indexes apart have a value equal to N multiplied by the previous number in the sequence.
Rules:
N must be greater than 1
Sequences with less than 3 entries should be ignored
Sequences returned must always be the longest possible for a given value of N
Sequences of all zeros do not count
My Solution
- Iterate the list of numbers of length M
At each iteration:
1.a hold the current number and current index in
current_number
andcurrent_index
respectively.1.b Calculate the maximum possible number of successive number sequences the
current_number
can fit in, and hold this number innested_iteration_count
.1.c Start the nested iteration with a loop count of
nested_iteration_count
and N at the minimum possible value of N = 21.c.1 Check if a sequence exists. If it exists, store the sequence in an array
1.c.2 Increment N by 1 and repeat the loop until the inner loop iterations are complete.
Repeat outer loop for next number
Example
Consider the following list of integers:
Number 2 10 4 3 8 6 9 9 18 27
Index 0 1 2 3 4 5 6 7 8 9
The following sequences are found:
- 2, 4, 8
- 3, 9, 27
This algorithm obviously has O(n^2)
complexity. Is it possible to improve on this?