I came across this solution, and this, which uses the sliding window technique, and the method for int[] A = {1, 2, 1, 2, 3};
and K=2
looks like this:-
As shown in the picture above it get the sub-array with elements
[1, 2]
[1, 2, 1]
[2, 1]
[2, 1, 2]
[1, 2]
[2, 3]
However I fail to understand how to get the subarray with the elements {1, 2, 1, 2}
As, the subarrays formed with exactly two elements are:-
[1, 2]
[1, 2, 1]
[2, 1]
[2, 1, 2]
[1, 2]
[2, 3]
[1, 2, 1, 2]
this is my solution
import java.util.*;
public class Main {
public static void main(String[] args) {
int[] A = {1, 2, 1, 2, 3};
int K = 2;
HashMap<Integer, Integer> map = new HashMap<>();
ArrayList<Integer> list = new ArrayList<>();
for(int i = 0;i<A.length; i++){
map.put(A[i], map.getOrDefault(A[i], 0) + 1);
list.add(A[i]);
if(map.size() == K) System.out.println(list);
while(map.get(list.get(0)) > 1 || map.size() > K){
map.put(list.get(0), map.get(list.get(0)) - 1);
if (map.get(list.get(0)) == 0) map.remove(list.get(0));
list.remove(0);
if(map.size() == K) System.out.println(list);
}
}
}
}
which gives the output
[1, 2]
[1, 2, 1]
[2, 1]
[2, 1, 2]
[1, 2]
[2, 3]
But I am failing to understand how to include {1, 2, 1, 2}
with this method.
Where am I going wrong !