Open In App

Remove all negatives from the given Array

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of size N, the task is to remove all negative elements from this array.

Examples:

Input: arr[] = {3, -4}
Output: {3}
Explanation: The only negative element of the array is -4.

Input: arr[] = {1, -3, 2}
Output: {1, 2}

 

Approach 1: The given problem can be solved using the following steps :

  1. Create a vector newArr to store only positive elements.
  2. Now traverse the array arr, and push positive element in newArr.
  3. Return newArr as the answer.

Below is the implementation of the above approach:

C++




// C++ code for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to remove the negative elements
void removeNegative(vector<int>& arr)
{
    vector<int> newArr;
 
    for (auto x : arr) {
        if (x >= 0) {
            newArr.push_back(x);
        }
    }
 
    for (auto x : newArr) {
        cout << x << ' ';
    }
}
 
// Driver Code
int main()
{
    vector<int> arr = { 1, -3, 2 };
    removeNegative(arr);
    return 0;
}


Java




// Java code for the above approach
import java.util.ArrayList;
 
class GFG {
 
  // Function to remove the negative elements
  static void removeNegative(int[] arr) {
    ArrayList<Integer> newArr = new ArrayList<Integer>();
 
    for (int x : arr) {
      if (x >= 0) {
        newArr.add(x);
      }
    }
 
    for (int x : newArr) {
      System.out.print(x + " ");
    }
  }
 
  // Driver Code
  public static void main(String args[]) {
    int[] arr = { 1, -3, 2 };
    removeNegative(arr);
  }
}
 
// This code is contributed by saurabh_jaiswal.


Python3




# Python code for the above approach
 
# Function to remove the negative elements
def removeNegative(arr):
    newArr = []
 
    for x in range(0, len(arr)):
        if (arr[x] >= 0):
            newArr.append(arr[x])
 
    for x in range(0, len(newArr)):
        print(newArr[x], end=' ')
 
# Driver Code
arr = [1, -3, 2]
removeNegative(arr)
 
# This code is contributed by Taranpreet


C#




// C# code for the above approach
using System;
using System.Collections;
 
class GFG {
 
  // Function to remove the negative elements
  static void removeNegative(int[] arr) {
    ArrayList newArr = new ArrayList();
 
    foreach (int x in arr) {
      if (x >= 0) {
        newArr.Add(x);
      }
    }
 
    foreach (int x in newArr) {
      Console.Write(x + " ");
    }
  }
 
  // Driver Code
  public static void Main() {
    int[] arr = { 1, -3, 2 };
    removeNegative(arr);
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript




<script>
        // JavaScript code for the above approach
 
        // Function to remove the negative elements
        function removeNegative(arr)
        {
            let newArr = [];
 
            for (let x of arr) {
                if (x >= 0) {
                    newArr.push(x);
                }
            }
 
            for (let x of newArr) {
                document.write(x + " ")
            }
        }
 
        // Driver Code
        let arr = [1, -3, 2];
        removeNegative(arr);
 
    // This code is contributed by Potta Lokesh
    </script>


 
 

Output

1 2 

 

Time Complexity: O(N)
Auxiliary Space: O(N)

 Approach 2: Using two pointers

This approach uses two pointers, one to iterate over the array and another to keep track of the next index to place a non-negative number.

C++




#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    int arr[] = { 2, 5, -6, 0, -1, 7, -9 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    int pos = 0;
    for(int i = 0; i < n; i++)
    {
        if(arr[i] >= 0)
        {
            arr[pos] = arr[i];
            pos++;
        }
    }
     
    // Printing the updated array without negatives
    for(int i = 0; i < pos; i++)
    {
        cout << arr[i] << " ";
    }
    return 0;
}


Java




/*package whatever //do not write package name here */
 
import java.util.*;
 
public class Main {
    public static void main(String[] args) {
        int[] arr = {2, 5, -6, 0, -1, 7, -9};
        int n = arr.length;
 
        int pos = 0;
        for (int i = 0; i < n; i++) {
            if (arr[i] >= 0) {
                arr[pos] = arr[i];
                pos++;
            }
        }
 
        // Printing the updated array without negatives
        for (int i = 0; i < pos; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}


C#




using System;
 
public class GFG{
 
    static public void Main (){
        int[] arr = { 2, 5, -6, 0, -1, 7, -9 };
            int n = arr.Length;
 
            int pos = 0;
            for(int i = 0; i < n; i++)
            {
                if(arr[i] >= 0)
                {
                    arr[pos] = arr[i];
                    pos++;
                }
            }
             
            // Printing the updated array without negatives
            for(int i = 0; i < pos; i++)
            {
                Console.Write(arr[i] + " ");
            }
         
    }
}


Javascript




let arr = [2, 5, -6, 0, -1, 7, -9];
let n = arr.length;
 
let pos = 0;
for (let i = 0; i < n; i++) {
  if (arr[i] >= 0) {
    arr[pos] = arr[i];
    pos++;
  }
}
 
// Printing the updated array without negatives
for (let i = 0; i < pos; i++) {
  console.log(arr[i] + " ");
}


Python3




# initializing list arr
arr = [2, 5, -6, 0, -1, 7, -9]
 
# finding the length of arr
n = len(arr)
 
# assigning a variable pos for storing the count of elements greater or equal to 0
pos = 0
for i in range(n):
    if arr[i] >= 0:
        arr[pos] = arr[i]
        pos += 1
 
# Printing the updated array without negatives
for i in range(pos):
    print(arr[i], end=" ")


Output

2 5 0 7 

Time Complexity: O(N)
Auxiliary Space: O(1)

Approach 3(For Java): Java’s lambda function removeIf() can be used as well to remove negative elements.

 

Java




// Java code for above approach
import java.util.*;
 
public class Solution {
 
    // Function to remove the
    // negative elements from the array
    public static ArrayList<Integer>
    remNeg(ArrayList<Integer> arr)
    {
        arr.removeIf(n -> n < 0);
        return arr;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        ArrayList<Integer> arr
            = new ArrayList<Integer>(
                Arrays.asList(1, -3, 2));
 
        arr = remNeg(arr);
        for (int i = 0; i < arr.size(); i++) {
            System.out.print(arr.get(i) + " ");
        }
    }
}


C#




// C# code for above approach
using System;
using System.Collections.Generic;
 
public class Solution {
 
  static bool isEven(int i)
  {
    return i < 0;
  }
 
  // Function to remove the
  // negative elements from the array
  static List<int>
    remNeg(List<int> arr)
  {
    arr.RemoveAll(isEven);
    return arr;
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    List<int> arr
      = new List<int>(new int[]{1, -3, 2});
 
    arr = remNeg(arr);
    for (int i = 0; i < arr.Count; i++) {
      Console.Write(arr[i] + " ");
    }
  }
}
 
// This code is contributed by shikhasingrajput


Javascript




<script>
// javascript code for above approach
 
    // Function to remove the
    // negative elements from the array
     function remNeg( arr) {
     for (var i = 0; i < arr.length; i++) {
            if(arr[i] < 0){
                arr.splice(i,1);
            }
        }
         
        return arr;
    }
 
    // Driver Code
        var arr = [1, -3, 2];
 
        arr = remNeg(arr);
        for (i = 0; i < arr.length; i++) {
            document.write(arr[i] + " ");
        }
 
// This code is contributed by Rajput-Ji
</script>


Python3




# Python code for the above Java code
from typing import List
 
# Function to remove the negative elements from the array
def remNeg(arr: List[int]) -> List[int]:
    arr = [x for x in arr if x >= 0]
    return arr
 
# Driver code
if __name__ == "__main__":
    arr = [1, -3, 2]
    arr = remNeg(arr)
    for i in arr:
        print(i, end=" ")


C++




#include <iostream>
#include <vector>
#include <algorithm>
 
using namespace std;
 
// Function to remove the negative elements from the vector
vector<int> remNeg(vector<int> arr)
{
    arr.erase(remove_if(arr.begin(), arr.end(), [](int n) {return n < 0;}), arr.end());
    return arr;
}
 
// Driver code
int main()
{
    vector<int> arr {1, -3, 2};
 
    arr = remNeg(arr);
    for (int i = 0; i < arr.size(); i++) {
        cout << arr[i] << " ";
    }
 
    return 0;
}


 
 

Output

1 2 

 

Time Complexity: O(N)
Auxiliary Space: O(1)

 



Last Updated : 20 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads