Hi, I had the Amazon OA and the first question was the following and I would like to know if anyone has a solution, I have this part of the code that works but however it did not pass all the Tests. Thank you and I hope it helps someone else.
For given array of integers, perform operations on the array. Return the resulting array after all operations have been applied in the orden given. Each operation contains two indices. Reverse the subarray between those zero-based indices, inclusive.
Example:
arr= [9,8,7,6,5,4,3,2,1,0]
operations = [[0,9], [4,5], [3,6], [2,7], [1,8], [0,9]]
class Result {
/*
* Complete the 'performOperations' function below.
*
* The function is expected to return an INTEGER_ARRAY.
* The function accepts following parameters:
* 1. INTEGER_ARRAY arr
* 2. 2D_INTEGER_ARRAY operations
*/
public static List<Integer> performOperations(List<Integer> arr, List<List<Integer>> operations) {
// My code start here
for (List<Integer> operation : operations) {
int left = operation.get(0);
int right = operation.get(1);
// Reverse the subarray between left and right (inclusive)
reverseSubarray(arr, left, right);
}
return arr;
}
private static void reverseSubarray(List<Integer> arr, int left, int right) {
while (left < right) {
int temp = arr.get(left);
arr.set(left, arr.get(right));
arr.set(right, temp);
left++;
right--;
}
// My code finish here
}
}public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int arrCount = Integer.parseInt(bufferedReader.readLine().trim());
List<Integer> arr = new ArrayList<>();
for (int i = 0; i < arrCount; i++) {
int arrItem = Integer.parseInt(bufferedReader.readLine().trim());
arr.add(arrItem);
}
int operationsRows = Integer.parseInt(bufferedReader.readLine().trim());
int operationsColumns = Integer.parseInt(bufferedReader.readLine().trim());
List<List<Integer>> operations = new ArrayList<>();
for (int i = 0; i < operationsRows; i++) {
String[] operationsRowTempItems = bufferedReader.readLine().replaceAll("\\s+$", "").split(" ");
List<Integer> operationsRowItems = new ArrayList<>();
for (int j = 0; j < operationsColumns; j++) {
int operationsItem = Integer.parseInt(operationsRowTempItems[j]);
operationsRowItems.add(operationsItem);
}
operations.add(operationsRowItems);
}
List<Integer> result = Result.performOperations(arr, operations);
for (int i = 0; i < result.size(); i++) {
bufferedWriter.write(String.valueOf(result.get(i)));
if (i != result.size() - 1) {
bufferedWriter.write("\n");
}
}
bufferedWriter.newLine();
bufferedReader.close();
bufferedWriter.close();
}
}