How to find a region of 2 (with.Java)
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.