Querying Sequences and Intervals 2(with.Java)
In this article, we learned about Querying sequences and intervals 2 (with.Java)
We’re going to learn as we go along by solving coding test problems, reflecting on the problems we solved, and exploring other ways to solve them. Let’s start with the problem.
Problem
You are given an array of integers arr and a two-dimensional array of integers queries. The elements of queries, each representing one query, are of the form [s, e, k].
For each query, in order, find the smallest arr[i] greater than k for all i such that s ≤ i ≤ e.
Complete the solution function, which returns an array containing the answers to each query in order. However, if the answer to a particular query does not exist, store -1.
Example input and output
arr: [0, 1, 2, 4, 3] queries: [[0, 4, 2],[0, 3, 2],[0, 2, 2]] result: [3, 4, -1]
The first query has a range of 0, 1, 2, 4, and 3, with 3 being the smallest value that is greater than 2. The second query has a range of 0, 1, 2, 4, where the smallest value greater than 2 is 4. The third query has a range of 0, 1, and 2, none of which are greater than 2. Therefore, it returns [3, 4, -1].
My solution to the problem
import java.util.*;
class Solution {
public int[] solution(int[] arr, int[][] queries) {
int[] result = new int[queries.length];
for(int i = 0; i < queries.length; i++){
ArrayList<Integer> temp = new ArrayList<Integer>();
int compare = Integer.MAX_VALUE;
for(int j = queries[i][0]; j <= queries[i][1]; j++){
if(arr[j] > queries[i][2]){
temp.add(arr[j]);
}
}
if(temp.isEmpty()){
result[i] = -1;
} else {
for(int k = 0; k < temp.size(); k++){
if(compare > temp.get(k)){
compare = temp.get(k);
}
}
} result[i] = compare;
}
}
} return result;
}
}
solution description
public int[] solution(int[] arr, int[][] queries): A function that takes two arrays arr and queries as input and solves the problem. Returns an array of integers as the result. int[] result = new int[queries.length];: Initializes an integer array result to the length of the queries array to store the result. An array to store the result value for each queries element. for(int i = 0; i < queries.length; i++) { … }: Executes a loop for each element of the queries array. ArrayList
In other words, this code does the job of finding values that fit a certain range and condition in the given array arr and storing them in the result array.