Introduction

Greetings! Welcome to this unit's lesson, where we’ll dive into a fascinating aspect of array manipulation. Have you ever considered traversing an array from the middle, alternating toward both ends simultaneously? That’s exactly what we’ll explore today.

By the end of this lesson, you’ll understand how to implement this unique traversal method in Ruby. Let’s jump right in!

Task Statement

You are tasked with creating a method that takes an array of integers and returns a new array. The new array is built by starting at the middle of the original array and alternating between elements to the left and right of the middle.

Here’s the specific behavior:

  • If the array has an odd length, the middle element is added first, followed by alternating elements to the left and right.
  • If the array has an even length, alternation begins with the left middle element, then the right middle element, and continues outward.

For example:

  • Given numbers = [1, 2, 3, 4, 5], the output should be [3, 2, 4, 1, 5].
  • For numbers = [1, 2, 3, 4, 5, 6], the output should be [3, 4, 2, 5, 1, 6].

This approach works for arrays of varying lengths, from 1 to 100,000. Let’s break down the solution step by step.

Step 1: Find the Middle
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal