703795. Query and Array

Easy

Query and Array

Slug: query-and-array4947

Difficulty: Easy

Id: 703795

Topic Tags: Arrays, Bit Magic, Data Structures

Company Tags: None

Summary

Given an array arr of size n, write a function to find the number of queries that can be made without violating any constraints. A query is considered valid if the difference between the maximum and minimum values in the subarray from index i to j (both inclusive) does not exceed k. The function should return the total number of valid queries.

Detailed Explanation

To solve this problem, we can use a simple brute-force approach. We iterate over all possible query ranges [i, j] and check if the difference between the maximum and minimum values in the subarray does not exceed k.

Here's a step-by-step breakdown:

  1. Initialize a variable queries to store the total number of valid queries.
  2. Iterate over all possible query ranges [i, j].
  3. For each query range, calculate the maximum and minimum values in the subarray using two pointers max and min, initialized at indices i and j respectively.
  4. Update the maximum value if the current element is greater than max, or update the minimum value if the current element is smaller than min.
  5. Check if the difference between max and min does not exceed k. If it does, increment the queries variable.
  6. Return the total number of valid queries.

Time complexity: O(n^2) due to the nested loops. Space complexity: O(1) as we only use a few extra variables.

Optimized Solutions

Java

View on GeeksforGeeks
public int queryAndArray(int[] arr, int k) {
    int n = arr.length;
    int queries = 0;
    for (int i = 0; i < n; i++) {
        int max = arr[i];
        int min = arr[i];
        for (int j = i; j < n; j++) {
            max = Math.max(arr[j], max);
            min = Math.min(arr[j], min);
            if (max - min <= k) {
                queries++;
            }
        }
    }
    return queries;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.