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:
- Initialize two pointers,
iandj, to 0. - Start iterating until
jreaches the end of the array. - In each iteration:
- Print the element at index
j. - Increment
iby 2 (since we're printing every other element). - If
iis less than or equal to the size of the array, incrementjby 1; otherwise, break the loop.
- Print the element at index
- Stop when
jreaches 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
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);
}
}