700712. Alternates in an Array

Basic

Alternates in an Array

Slug: print-alternate-elements-of-an-array

Difficulty: Basic

Topic Tags: Arrays, Data Structures

Company Tags: None

Summary

The problem is about printing alternate elements of an array. Given an integer array and its size, we need to print the first element, then the third, then the fifth, and so on until we reach the end of the array.

Detailed Explanation

To solve this problem, we can iterate over the array with two pointers, incrementing one pointer while keeping the other pointer constant. We'll print each element pointed by the second pointer.

Here's a step-by-step breakdown:

  1. Initialize two pointers, i and j, to 0.
  2. Start iterating until j reaches the end of the array.
  3. In each iteration:
    • Print the element at index j.
    • Increment i by 2 (since we're printing every other element).
    • If i is less than or equal to the size of the array, increment j by 1; otherwise, break the loop.
  4. Stop when j reaches the end of the array.

Time complexity: O(n), where n is the size of the array. Space complexity: O(1), since we're not using any extra space.

Optimized Solutions

Java

View on GeeksforGeeks
public class Main {
    public static void printAlternateElements(int[] arr) {
        for (int i = 0, j = 0; j < arr.length; j += (i = i + 2)) {
            System.out.println(arr[j]);
        }
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        printAlternateElements(arr);
    }
}

DevExCode

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

© 2026 DevExCode. All rights reserved.