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:

  1. Initialize two pointers, left and right, to the start and end of the array respectively.
  2. Print the element at the left pointer (arr[left]).
  3. Move the right pointer one step to the left (right = right - 1).
  4. Print the element at the right pointer (arr[right]).
  5. Move the left pointer one step to the right (left = left + 1).
  6. Repeat steps 2-5 until left meets right.

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

View on GeeksforGeeks
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++;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.