Problem: Given an array of size N, print the sorted sub sets of size K with consecutive elements.
N = 10, K = 4
8 4 7 5 1 10 3 9 2 6
Output:
4 5 7 8, 1 4 5 7, 1 5 7 10, 1 3 5 10, ...
Approach 1: Sort all the sub sets and print.
Complexity Analysis:
Copy K elements: O((N - K + 1) * (K)) // No of sub sets * size of sub sets
Sort sub set: Using STL, the worst case time to sort a sub set is O(K log K).
Thus, O((N - K + 1) * (K) + (N - K + 1) * (K log K))
Approach 2: From the output sequence, the consecutive sub sets differ by 2 elements. Therefore for the second sub set, Delete the first element and insert the K + 1 th element at the right position.
Complexity Analysis:
Create the first sub set: K
Remove and Insert - linear search (Should this be optimized!): K
Thus, O(K + (N - K + 1) * (K))
I would like to know if the second approach is faster? Is there a significant gain? Is it worthy of not using the STL implementation? Can this be further improved? Is there any other approach? and any suggestions for STL containers for implementation.