Queries with Fixed Length

  • + 0 comments

    Java, linear time complexity

    public static List<Integer> solve(List<Integer> arr, List<Integer> queries) {
            List<Integer> results = new ArrayList<>();
    
            for (int d : queries) {
                int minMax = Integer.MAX_VALUE;
    
                Deque<Integer> window = new LinkedList<>();
    
                for (int i = 0; i < d; i++) {
                    while (!window.isEmpty() && arr.get(i) >= arr.get(window.peekLast())) {
                        window.removeLast();
                    }
                    window.addLast(i);
                }
    
                for (int i = d; i <= arr.size(); i++) {
                    minMax = Math.min(minMax, arr.get(window.peekFirst()));
    
                    while (!window.isEmpty() && window.peekFirst() <= i - d) {
                        window.removeFirst();
                    }
    
                    if (i < arr.size()) {
                        while (!window.isEmpty() && arr.get(i) >= arr.get(window.peekLast())) {
                            window.removeLast();
                        }
                        window.addLast(i);
                    }
                }
    
                results.add(minMax);
            }
            return results;
        }