Contents

Querying sequences and intervals 1 (with.Java)

   Oct 6, 2023     2 min read

We’ve been learning about sequences and interval queries.

We’ll do this by solving coding test questions, 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].

For each query, add 1 to arr[i] for all i such that s ≤ i ≤ e, in order.

Complete the solution function to return arr after processing the queries according to the above rules.

Example input and output
arrqueriesresult
[0, 1, 2, 3, 4][[0, 1],[1, 2],[2, 3]][1, 3, 4, 4, 4, 4]

My solution to the problem

class Solution {
    public int[] solution(int[] arr, int[][] queries) {
        int[] answer = arr;
        int idx = 0;
        for(int i = 0; i < queries.length; i++){
            for(int j = queries[i][0]; j <= queries[i][1]; j++){
                answer[j] += 1;
            }
        }
        } return answer;
    }
}
solution description

int[] answer = arr;: Initialize the resulting array answer to arr. This way, answer will point to the same array as arr.

for(int i = 0; i < queries.length; i++) : Iterate over the array queries, processing each query.

for(int j = queries[i][0]; j <= queries[i][1]; j++) : Iterate over the range for each query, incrementing the elements of the answer array within that range by 1.

return answer;: After processing all the queries, return the changed answer array.

This code does the job of incrementing the elements of arr by 1 that correspond to the ranges in the queries array.

But be careful, because the answer array references the arr array, this action also affects the arr array.

So if you want to store the result in a new array without changing the arr array, you need to create a new array and make changes to it.