Skip to content
Advertisement

With lowest possible time complexity , subtract every number in a list from the first lower number after it

I have a list of numbers and I want to subtract every number from the smaller value after it but with the lowest possible complexity I have the list [7, 18 ,5 ,5 ,20 ,9 ,14 ,7 ,19]

The first lower value after 7 is 5 so it will subtract 7 from 5, the same for 18 the first lower value after it is 5, so it will subtract 18 from 5 and so on.

The output should be [2, 13, 5, 5, 11, 2, 7, 7, 19]

I have written a code that solves the problem but with O(N^2), but I was wondering if I could solve it with lower time complexity

JavaScript

Advertisement

Answer

I am not sure what complexity this exactly is but it is not O(n^2)you can try this. You can use a stack.

JavaScript

Output

JavaScript

Benchmark using %%timeit -n 10 -r 10 in jupyter, input list has been increased to show the efficiency.

JavaScript

This Solution

JavaScript

Original Code

JavaScript

This solution is faster.

Edit according to @JérômeRichard comment this runs in linear time O(n).

This is O(n). Here is the proof: you cannot append more element to the stack than the number of element in the input list because of the append. You cannot remove more element from the stack than the number of appended elements. Both pop and append are (amortized) O(1) operations. Then final loop is running in O(n)

Commented Version for Better Understanding

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement