I was trying to solve random coding kata’s and found this one, my question here is what is the optimal algorithm and best design approach for solving this kata?
Given a sequence of numbers, determine the type of sequence, calculate and return the next number in
the sequence.
Integer guessNextNumber(List<Integer> sequence);
The given sequence can be one of two types, arithmetic sequence and geometric sequence.
Arithmetic sequence is defined as:
Arith_seq(p,q) = p, p+q, (p+q) +q, …
Example: Arith_seq(7,3) = 7, 10, 13, 16, 19, …
Geometric sequence is defined as:
Geo_seq(p,q) = p, p*q, (p*q) * q, …
Example: Geo_seq(2,3) = 2, 6, 18, 54, …
Expected input and output:
The input sequence will have at least 3 numbers.
For the input sequence (7, 10, 13, 16, 19), the return value would be 22.
For the input sequence (2, 6, 18, 54), the return value would be 162.
Algorithm:
- Check input sequence
if we have sequence as (a, b, c) then, -
if difference between elements of sequence (b-a) or (c-b) is
equal then its Arithmatic Sequence. -
if division between elements of sequence is equal, eg: b/a and
c/b then its Geometric Sequence
My question what would be an optimal algo for solving it?
Update: Is it possible to solve this constant run time?
Lets say your collection is
a,b,c,db - a + b = cthen it is arithmeticb / a * b = cit is geometricTo return the right sequence you could thus do
Java would be (assuming it is either artihmetic or geometric, never anything else, and always atleast 3 entries)
Safe code would be
With List instead of Array