Queries with Fixed Length


Problem Statement :


Consider an -integer sequence, . We perform a query on  by using an integer, , to calculate the result of the following expression:

In other words, if we let , then you need to calculate .

Given  and  queries, return a list of answers to each query.

Example


The first query uses all of the subarrays of length : . The maxima of the subarrays are . The minimum of these is .

The second query uses all of the subarrays of length : . The maxima of the subarrays are . The minimum of these is .

Return .



Function Description

Complete the solve function below.

solve has the following parameter(s):

int arr[n]: an array of integers
int queries[q]: the lengths of subarrays to query
Returns

int[q]: the answers to each query
Input Format

The first line consists of two space-separated integers, n  and q.
The second line consists of n space-separated integers, the elements of arr.
Each of the q  subsequent lines contains a single integer denoting the value of d for that query.



Solution :



title-img


                            Solution in C :

In C ++ :




#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

#define li long int
#define INT_MAX 1000000007
li tree[1000000];
li A[200000];

void build(int node, int start, int end)
{
    if(start == end)
    {
        tree[node] = A[start];
    }
    else
    {
        int mid = (start + end) / 2;
        build(2*node, start, mid);
        build(2*node+1, mid+1, end);

        tree[node] = max(tree[2*node] , tree[2*node+1]);
    }
}

int query(int node, int start, int end, int l, int r)
{
    if(r < start or end < l)
    {
        return 0;
    }
    if(l <= start and end <= r)
    {
        return tree[node];
    }

    int mid = (start + end) / 2;
    int p1 = query(2*node, start, mid, l, r);
    int p2 = query(2*node+1, mid+1, end, l, r);
    return max(p1 , p2);
}

int main() {
   
    li q,n,d;
    
    cin >> n >> q;
    
    for(int i=0;i<n;++i) cin >> A[i];
    
    build(1,0,n-1);
    
    while(q--)
        {
        
        cin >> d;
        
        li min=INT_MAX;
        for(int i=0;i<=n-d;++i)
        {
            li temp_max=query(1,0,n-1,i,i+d-1);
            
            if(temp_max<min) min = temp_max; 
            
        }
        
        cout<<min<<endl;
    }
    
    
    return 0;
}








In Java :





import java.util.Scanner;

public class Solution
{
  public static void main(String[] args)
  {
    Scanner scan = new Scanner(System.in);
    int dataCount = scan.nextInt();
    int queriesCount = scan.nextInt();
    int[] data = new int[dataCount];
    for (int i = 0; i < dataCount; ++i)
      data[i] = scan.nextInt();
    for (int i = 0; i < queriesCount; ++i)
      System.out.println(findMinMax(data, scan.nextInt()));
  }

  private static int findMinMax(int[] data, int range)
  {
    if (range >= data.length)
      return easyMax(data, 0, data.length);
    int maxV = easyMax(data, data.length - range, data.length);
    int minV = maxV;
    for (int i = data.length - range - 1; i >= 0; --i)
    {
      if (data[i] == data[i+range]) //nothing changed
        continue;
      if (data[i] > maxV)
        maxV = data[i];
      else if (data[i + range] == maxV)
        maxV = easyMax(data, i, i + range);
      if (maxV < minV)
        minV = maxV;
    }
    return minV;
  }

  private static int easyMax(int[] data, int fromInclusive, int toExclusive)
  {
    int pos = toExclusive;
    int max = data[--pos];
    while (--pos >= fromInclusive)
      if (data[pos] > max)
        max = data[pos];
    return max;
  }
}








In C :






#include <stdio.h>
#include <string.h>
#include <limits.h>
#include <stdlib.h>

struct queue{
    int front,rear,size;
    unsigned capacity;
    long *array;
    int *index;
};

struct queue *create(unsigned capacity){
    struct queue *q=(struct queue *)malloc(sizeof(struct queue));
    q->front=0;
    q->rear=capacity-1;
    q->size=0;
    q->capacity=capacity;
    q->array=(long *)malloc(q->capacity*sizeof(long));
    q->index=(int *)malloc(q->capacity*sizeof(int));
    for(int i=0;i<q->capacity;i++){
        q->array[i]=0;
        q->index[i]=0;
    }
    return q;
}

int full(struct queue* q){
    if(q->size==q->capacity)    return 1;
    else    return 0;
}

int empty(struct queue* q){
    if(q->size==0)  return 1;
    else    return 0;
}

void enque(struct queue* q, long x, int i){
    if(!full(q)){
        q->size++;
        q->rear=(q->rear+1)%(q->capacity);
        q->array[q->rear]=x;
        q->index[q->rear]=i;
    }
}

void deque(struct queue *q){
    if(!empty(q)){
        q->size--;
        q->front=(q->front+1)%(q->capacity);
    }
}

long top_array(struct queue *q){
    if(!empty(q))   return q->array[q->front];
    return INT_MAX;
}

int top_index(struct queue *q){
    if(!empty(q))   return q->index[q->front];
    return INT_MAX;
}

void deque_back(struct queue *q){
    if(!empty(q)){
        q->size--;
        q->rear=(q->rear-1);
        if(q->rear<0)   q->rear=q->capacity+q->rear;
    }
}

long bottom_array(struct queue *q){
    if(!empty(q))   return q->array[q->rear];
    return INT_MAX;
}

int main(){
    
    int n,Q,i,j,k;
    scanf("%d%d",&n,&Q);
    long *a=(long *)malloc(n*sizeof(long));
    for(i=0;i<n;i++){
        scanf("%li",&a[i]);
    }
    int d;
    
    
    
    for(i=0;i<Q;i++){
        long max,min=INT_MAX;
        scanf("%d",&d);
        struct queue *q=create(n);
        j=0;
        //printf("%d %d ",q->rear,q->size);
        while(j<d){
            if(empty(q))    enque(q,a[j],j); 
            else{
                while(a[j]>=bottom_array(q)){   deque_back(q);  }
                enque(q,a[j],j);
            }
            //for(k=0;k<n;k++){ printf("%li ",q->array[k]);  }
            //printf("%d ",bottom_array(q));
            j++;
        }
        min=top_array(q);
        
        
        
        while(j<n){
            while(j-top_index(q)<d && j<n){
                if(top_array(q)<min)    min=top_array(q);
                while(a[j]>=bottom_array(q)){
                    deque_back(q);
                }
                enque(q,a[j],j);
                j++;
            }
            if(j-top_index(q)==d && j<n){
                if(top_array(q)<min)    min=top_array(q);
                deque(q);
                while(a[j]>=bottom_array(q)){
                    deque_back(q);    
                }
                enque(q,a[j],j);
                j++;
            }
        }
        
        
        
        
        if(top_array(q)<min)    min=top_array(q);
        printf("%li\n",min);
        free(q);
    }
    
    
    
    
    
    return 0;
}









In Python3 :





from collections import deque
n, q = map(int, input().split())
a = list(map(int, input().split()))
for _ in range(q):
    d = int(input())
    l = deque()
    m = 0
    for i in range(d - 1, -1, -1):
        if m < a[i]:
            m = a[i]
            l.appendleft(i)
    for i in range(d, n):
        if l[0] + d <= i:
            l.popleft()
        while l and a[l[-1]] < a[i]:
            l.pop()
        l.append(i)
        m = min(m, a[l[0]])
    print(m)
                        








View More Similar Problems

Dynamic Array

Create a list, seqList, of n empty sequences, where each sequence is indexed from 0 to n-1. The elements within each of the n sequences also use 0-indexing. Create an integer, lastAnswer, and initialize it to 0. There are 2 types of queries that can be performed on the list of sequences: 1. Query: 1 x y a. Find the sequence, seq, at index ((x xor lastAnswer)%n) in seqList.

View Solution →

Left Rotation

A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. Given an integer, d, rotate the array that many steps left and return the result. Example: d=2 arr=[1,2,3,4,5] After 2 rotations, arr'=[3,4,5,1,2]. Function Description: Complete the rotateLeft function in the editor below. rotateLeft has the following parameters: 1. int d

View Solution →

Sparse Arrays

There is a collection of input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings. Return an array of the results. Example: strings=['ab', 'ab', 'abc'] queries=['ab', 'abc', 'bc'] There are instances of 'ab', 1 of 'abc' and 0 of 'bc'. For each query, add an element to the return array, results=[2,1,0]. Fun

View Solution →

Array Manipulation

Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each of the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array. Example: n=10 queries=[[1,5,3], [4,8,7], [6,9,1]] Queries are interpreted as follows: a b k 1 5 3 4 8 7 6 9 1 Add the valu

View Solution →

Print the Elements of a Linked List

This is an to practice traversing a linked list. Given a pointer to the head node of a linked list, print each node's data element, one per line. If the head pointer is null (indicating the list is empty), there is nothing to print. Function Description: Complete the printLinkedList function in the editor below. printLinkedList has the following parameter(s): 1.SinglyLinkedListNode

View Solution →

Insert a Node at the Tail of a Linked List

You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer. Insert this node at the tail of the linked list and return the head node of the linked list formed after inserting this new node. The given head pointer may be null, meaning that the initial list is empty. Input Format: You have to complete the SinglyLink

View Solution →