I have a list of lists, for example [[0], [1, 1], [4, 2, 4], ...]. I want to iterate through each individual nested list and build a new list of lists that contains all the signed differences between values within each specific list. For this example list, the resulting list of lists would be:
differences = [[0], [0, 0, 0, 0], [0, 2, 0, -2, 0, -2, 0, 2, 0],....]
I have already implemented a brute-force method which contains three nested for loops. The first for loop iterates through all the lists and the other two for loops iterate over a specific list to get all the possible differences.
I was wondering if someone can come up with a more optimized algorithm that runs faster? Thanks!
As clearly pointed out in the comments, you cannot go below
O(n^2)for anelement sublist. However, you can be a little bit efficient, as you suggested to only don(n-1) / 2subtractions.Here's the formalization of your idea:
Take a sublist
L = [a,b,c]of sizen = 3Consider a matrix A of size
n X nto store the differences. Then clearlyYou can just compute the upper triangle having
n(n-1) / 2entries. Diagonals are all 0's. The lower triangle values can be filled from the upper one, sinceAis skew-symmetric.Last but not least, you serialize
Ain row-major order to get your desired 'difference list'D. Note that the entrya_{i,j}will be placed at thei*n + j-th place inD. [I have assumed 0 based indexing like in C.]