703300. Print an array in Pendulum Arrangement
Easy
Print an Array in Pendulum Arrangement
Summary
Given an array, print its elements in a pendulum arrangement. This means that each element is printed followed by the next and then the previous element until the end of the array is reached.
Detailed Explanation
The algorithm for this problem involves printing the array elements in an alternating pattern. We start from the first element and then move to the last, then back to the second-to-last, and so on. This process continues until we have processed all the elements in the array.
Here's a step-by-step breakdown of the solution:
- Initialize two pointers,
leftandright, to the start and end of the array respectively. - Print the element at the left pointer (
arr[left]). - Move the right pointer one step to the left (
right = right - 1). - Print the element at the right pointer (
arr[right]). - Move the left pointer one step to the right (
left = left + 1). - Repeat steps 2-5 until
leftmeetsright.
Time complexity: O(n), where n is the size of the array. Space complexity: O(1), as we only use a constant amount of space.
Optimized Solutions
Java
public void printPendulumArray(int[] arr) {
int left = 0;
int right = arr.length - 1;
while (left < right) {
System.out.print(arr[left] + " ");
right--;
if (right > left) {
System.out.print(arr[right] + " ");
}
left++;
}
}