Skip to main content

Print alternate elements of an array DSA Problem

 

Print alternate elements of an array

SchoolAccuracy: 52.74%Submissions: 161K+Points: 0

Three 90 Challenge Extended On Popular Demand! Don't Miss Out Now 

banner

You are given an array A of size N. You need to print elements of A in alternate order (starting from index 0).

Example 1:

Input:
N = 4
A[] = {1, 2, 3, 4}
Output:
1 3

Example 2:

Input:
N = 5
A[] = {1, 2, 3, 4, 5}
Output:
1 3 5

Your Task:
Since this is a function problem, you just need to complete the provided function print() which takes A and n as input parameters and print the resultant array in the function itself. You have to print the final number of array ending with a space as Printing of newline character is taken care in driver code itself.

Constraints:
1 <= N <= 105
1 <= A<= 105

Expected Time Complexity: O(n)
Expected Auxiliary Space: O(1)



Ans: 
Used Approach: Iterative

Time Complexity of Approach: O(N)

Explain This Problem: In this problem we need to print element of Array by skiping 1 element 

Example: 1   2  3  4  5  6  7 

Output need: 1  3  5  7


Approach: 


class GfG

{

    public static void print(int arr[], int n)

    {

        // your code here

        ArrayList<Integer> list1 = new ArrayList<>(); 

        for(int i = 0 ; i < arr.length; i = i+2){

           list1.add(arr[i]);

    }

   for(int i = 0 ;i < list1.size(); i++){

       System.out.print(list1.get(i)+ " ");

   }

    

   

    }

   

}

Comments