Search code examples
pythonarraysalgorithmsub-array

How to get all sub arrays of an array of length 2 or more in efficient way?


array =[1,2,3,4]

Resulting subarray should be...

[1,2],[2,3],[3,4],[1,2,3],[2,3,4],[1,2,3,4]

Solution

  • O(n)? Maybe if you had infinite memory with every possible subarray in the real/imaginary number system stored for efficient accessing, then sure, you can have any complexity algorithm you like.

    ...But realistically speaking, you're looking at something along the lines of O(n^3), regardless of how efficient you do it.

    >>> [lst[i:j + 1] for i in range(len(lst)) for j in range(i + 1, len(lst))]
    [[1, 2], [1, 2, 3], [1, 2, 3, 4], [2, 3], [2, 3, 4], [3, 4]]
    

    The one liner hides the two loops and the slicing operation, all of which add layers of complexity. However, it is as efficient and as fast as the underlying algorithm allows it to be.