703049. Reverse sub array
Basic
Reverse Sub Array
Slug: reverse-sub-array5620
Difficulty: Basic
Id: 703049
Topic Tags: Arrays, Data Structures
Company Tags: Amazon
Summary
Given an array and a start index, reverse the subarray from that start index to the end of the array. The problem is about manipulating arrays in-place, which involves modifying the original array without creating a new one.
Detailed Explanation
To solve this problem, we can iterate through the array starting from the given start index to the end of the array. For each element, we swap it with the corresponding element at the end of the array minus the distance from the start index. We continue this process until we have processed the entire subarray.
Here's a step-by-step breakdown of the solution:
- Start at the given start index
i. - Calculate the distance
distbetween the current position and the end of the array. - Swap the element at the current position with the element
distpositions away from the end of the array. - Move to the next position by incrementing
iand decrementingdist. - Repeat steps 2-4 until we have processed the entire subarray.
Optimized Solutions
Java
public static void reverseSubArray(int[] arr, int start) {
int n = arr.length;
for (int i = start; i < n; i++) {
int j = n - 1 - (i - start);
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}