1

This is a very common problem for a list of number = [1,2,3]

I want to generate all possible consecutive subsequence answer ==> [1],[2],[3],[1,2],[2,3],[1,2,3]

I have tried two solutions

lst = [1,2,3,4]
n = len(lst)

for i in range(n):
    for j in range(i+1, n):
        print(lst[i:j])

Output =

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

Problem this is O(n^2) time complexity and gives Time Limited Exceeded error most of the times what is a faster way to achieve this?

I have also tried using itertools.combinations()

import itertools

lst = [1, 2, 3]
combs = []

for i in range(1, len(lst)+1):
    els = [list(x) for x in itertools.combinations(lst, i)]
    combs.extend(els)
print(combs)

But it generates an extra pair (1,3) which is not consecutive and hence not required Output

[[1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
  • What is your real initial problem? Maybe you don't have to generate the subsequences at all, but can solve it in a different way. – Kolmar Nov 10 '21 at 04:08
  • Well, I have been facing this particular sub problem in various other problems and have always been curious, hence I posted this. – imeetsanghvi Nov 10 '21 at 04:32
  • I don't think you can improve the time complexity – juanpa.arrivillaga Nov 10 '21 at 05:47
  • 2
    It's a quarter to seven in the morning here, and I'm bad at math at the best of times, but isn't the number of subsequences in the order of n^2? (I get n(n+1)/2, to be exact). – Ture Pålsson Nov 10 '21 at 05:48
  • 1
    This kind of problem usually means that you have to apply some algorithm to quickly get an answer for a whole range of subsequence. For example something like `for element in list: calc_ans_for_all_subseqs_ending_with(element)`. The common algorithms for that are Prefix Sum, Bit Indexed Tree, Segment Tree, Rolling Hash, Dynamic Programming and maybe more. – Kolmar Nov 10 '21 at 19:01

0 Answers0