Contents

How to find a region of 2 (with.Java)

   Sep 24, 2023     2 min read

In this article, How to find the area of 2 (with.Java)

We’re going to go through a series of coding test problems, looking back at the problems we solved and learning about other ways to solve them.

Let’s start with the problem

Problem

You are given an array of integers, arr. Complete a solution function that returns the smallest contiguous subarray that contains all the 2s in arr.

However, if arr contains no 2s, return [-1].

Example input and output

arr: [1, 2, 1, 4, 5, 2, 9]

result: [2, 1, 4, 5, 2]

The only indices with a 2 are indices 1 and 5, so this returns a partial array of indices 1 through 5, [2, 1, 4, 5, 2].

My solution to the problem

import java.util.*;
class Solution {
    public int[] solution(int[] arr) {
        int startIndex = -1;
        int endIndex = -1;

        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == 2) {
                if (startIndex == -1) {
                    startIndex = i;
                }
                endIndex = i;
            }
        }

        if (startIndex == -1 || endIndex == -1) {
            return new int[]{-1};
        }

        int[] answer = new int[endIndex - startIndex + 1];
        for (int j = 0; j < answer.length; j++) {
            answer[j] = arr[startIndex + j];
        }

        } return answer;
    }
}
Explanation of the solution

Initializing variables: startIndex and endIndex are initialized to -1 each. These values indicate that β€˜2’ has not yet been found.

Find the location of β€˜2’: Traverse the given array arr to find the location of β€˜2’.

startIndex stores the index of the first found β€˜2’.

endIndex stores the index of the last β€˜2’ found.

This means that at the end of the iteration, startIndex and endIndex represent the location of the first β€˜2’ and the last β€˜2’ in the array.

Handling when no β€˜2’ is found: If either startIndex or endIndex is -1, it is assumed that no β€˜2’ is found and [-1] is returned.

Create a partial array: Create a partial array between startIndex and endIndex.

The length of the answer array is (endIndex - startIndex + 1), which means it will contain elements from startIndex to endIndex.

Each element in the partial array copies a value from the original array starting at startIndex and ending at endIndex.

Result: Returns the created partial array answer. This array contains all elements between the first β€˜2’ and the last β€˜2’ in arr.