700889. Reverse an Array
Reverse an Array
Slug: reverse-an-array Difficulty: Easy Id: 700889 Topic Tags: Arrays, Data Structures Company Tags: Bloomberg, Facebook, TCS, Adobe, Google, Infosys, Capgemini, Morgan Stanley, Amazon, Microsoft, Apple, Yahoo, PayPal, Uber
Summary
The problem of reversing an array is a classic algorithmic challenge. Given an array of integers, the task is to rearrange its elements in reverse order, maintaining their original values. This problem requires understanding basic array manipulation techniques and implementation skills.
Detailed Explanation
To solve this problem, we can iterate through the input array from both ends (start and end) simultaneously. The first element of the reversed array will be the last element of the original array, the second element will be the second-to-last element, and so on. This approach ensures that all elements are correctly positioned in reverse order.
Here's a step-by-step breakdown:
- Initialize two pointers:
startat the beginning of the array andendat the end. - While
startis less than or equal toend, swap the elements at these positions. - Increment
startand decrementendfor the next iteration. - Repeat steps 2-3 until
startbecomes greater thanend.
Time complexity: O(n), where n is the length of the input array, since we visit each element once.
Space complexity: O(1), as we only use a constant amount of space to store the pointers and do not create any new data structures.
Optimized Solutions
Java
public static void reverseArray(int[] arr) {
int start = 0;
int end = arr.length - 1;
while (start <= end) {
// Swap elements at positions `start` and `end`
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}