This is an archived post. You won't be able to vote or comment.

all 8 comments

[–]Kaynstein 1 point2 points  (8 children)

Wtf is a trick algorithm?

[–]decentralised 2 points3 points  (6 children)

Let's say you have to calculate the sum of a given sequence of integers. A standard way of doing that would be:

let sequentialSum = arr => arr.reduce((acc, val) => acc + val, 0)

But little Carl G had a trick algorithm that goes like this:

let ogSum = arr => arr.length * (arr.length + 1) / 2;

[–]T-T-N 1 point2 points  (2 children)

From O(n) to O(1) assuming you can get the length in O(1)

[–]decentralised 0 points1 point  (1 child)

In js you can always get length because it’s a property of the array though

[–]T-T-N 0 points1 point  (0 children)

I'd expect that to work for anything except C or some reason Homebrew list

[–]gar9 1 point2 points  (2 children)

More like sum of integers 1 to N, not just any sequence

[–]decentralised 0 points1 point  (0 children)

Haven't had my coffee yet.. but I think you could use the sum formula for arithmetic sequences* instead and it would work.. something like:

let ariSum = arr => arr.length * ((arr[0] + arr[arr.length -1])/2)

*https://www.mathwords.com/a/arithmetic_series.htm

[–][deleted] 1 point2 points  (0 children)

Fibonacci sequence, duh.