Print alternate elements of an array

Print the alternate elements of the array

Example 1:

Input: 
N = 6
Arr[] = {14, 48, 9, 17, 35, 1}
Output: 14 9 35

Example 2:

Input: 
N = 4
Arr[] = {10, 5, 10}
Output: 10 10

 


method 1:

Java implementation:

class codemummy
{
    public static void print(int arr[], int n)
    {
      for(int i=0;i<n;i++){
          if(i%2==0){
           System.out.print(arr[i]+" ");
          }
      }
    }
}

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


c++ implementation:

#include <iostream>

void print(int arr[], int n) {
    for (int i = 0; i < n; i++) {
        if (i % 2 == 0) {
            std::cout << arr[i] << " ";
        }
    }
}

Time Complexity: O(1) 
space Complexity: O(1)


python implementation:

def print(arr, n):
    for i in range(n):
        if i % 2 == 0:
            print(arr[i], end=" ")

Time Complexity: O(1) 
space Complexity: O(1)




method 2:

java implementation:

class codemummy
{
    public static void print(int arr[], int n)
    {
      for(int i=0;i<n;i=i+2){
           System.out.print(arr[i]+" ");
      }
    }
}

 Time Complexity: O(n/2)=>O(n)
Auxiliary Space: O(1).



c++ implementation:

void print(int arr[], int n) {
    for (int i = 0; i < n; i += 2) {
        cout << arr[i] << " ";
    }
}

Time Complexity: O(n/2)=>O(n)
space Complexity: O(1)


python implementation:

def print(arr, n):
    for i in range(0, n, 2):
        print(arr[i], end=' ')
Time Complexity: O(n/2)=>O(n)
space Complexity: O(1)

No comments

darkmode