How to find minimal-length subsequence that contains all element of a sequence

后端 未结 7 1432
无人共我
无人共我 2021-02-01 07:29

Given a sequence such as S = {1,8,2,1,4,1,2,9,1,8,4}, I need to find the minimal-length subsequence that contains all element of S (no duplicates, order does n

相关标签:
7条回答
  • 2021-02-01 08:15

    I'd say:

    1. Construct the set of elements D.
    2. Keep an array with the same size as your sequence S.
    3. Fill the array with indexes from S indicating the latest start of a sequence with all elements from D that ends at that index.
    4. Find the min length of sequences in the array and save the position for start and end.

    Obviously, only item 3. is tricky. I'd use a priority queue / heap that assigns a key to each element from D and has the element as value. Apart from that you'll want a data structure that is able to access the elements in the heap by their value (map w/ pointers to the elements). The key should always be the last position in S that the element has occurred.

    So you go through S and for each char you read, you do one of setKey O(log n) and then look at the current min O(1) and write it to in the array.

    Should be O(n * log n). I hope I didn't miss anything. It just came to my mind, so take it with a grain of salt, or let the community point out possible mistakes I might have made.

    0 讨论(0)
提交回复
热议问题