You are given an array of size N
. You need to print elements for the given array in an alternate order, starting from index 0.
Input:
arr = {11,12,13,14}
Output:
Since we need to start from index 0
, we print 11
, skip 12
, and print 13
.
Initialize the array arr
with input numbers as 11, 12, 13, 14, 15
.
Find array length n
, with length
property on the array.
Use the for
loop to traverse the array.
Start with index 0
, go until the last element, and increment index by 2
every time to skip alternate elements.
Print element.
When the loop ends, we will have printed all the alternate elements in the array.
class Solution {public static void main( String args[] ) {//initialize arrayint[] arr = {11, 12, 13, 14, 15};//array lengthint n = arr.length;// loop through the array and increment by 2for(int i=0; i<n; i = i+2){//print elementSystem.out.println(arr[i]);}}}
This solution takes $O(n)$ time complexity, as we traverse elements in the array once.
The solution then takes $O(1)$ space complexity, as we are not taking extra space to solve this problem aside from the input array.