Remove all negatives from the given Array
Last Updated :
20 Mar, 2023
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 :
- Create a vector newArr to store only positive elements.
- Now traverse the array arr, and push positive element in newArr.
- 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>
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=" ")
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;
}
Time Complexity: O(N)
Auxiliary Space: O(1)
Similar Reads
First subarray with negative sum from the given Array Given an array arr[] consisting of N integers, the task is to find the start and end indices of the first subarray with a Negative Sum. Print "-1" if no such subarray exists. Note: In the case of multiple negative-sum subarrays in the given array, the first subarray refers to the subarray with the l
15+ min read
Find pairs of Positive and Negative values present in given array Given an array of distinct integers, print all the pairs having both positive and negative values of a number that exists in the array. The pairs can be printed in any order. Examples: Input: arr[] = {1, -3, 2, 3, 6, -1}Output: -1 1 -3 3 Input: arr[] = {4, 8, 9, -4, 1, -1, -8, -9}Output: -4 4 -8 8 -
14 min read
Find the only positive or only negative number in the given Array Given an array arr[] of either entirely positive integers or entirely negative integers except for one number. The task is to find that number. Examples: Input: arr[] = {3, 5, 2, 8, -7, 6, 9}Output: -7Explanation: Except -7 all the numbers in arr[] are positive integers. Input: arr[] = {-3, 5, -9}Ou
9 min read
Find the resulting output array after doing given operations Given an array integers[] of integers of size N. Find the resulting output array after doing some operations: If the (i-1)th element is positive and ith element is negative then :If the absolute of (i)th is greater than (i-t)th, remove all the contiguous positive elements from left having absolute v
10 min read
Find all numbers in range [1, N] that are not present in given Array Given an array arr[] of size N, where arr[i] is natural numbers less than or equal to N, the task is to find all the numbers in the range [1, N] that are not present in the given array. Examples: Input: arr[ ] = {5, 5, 4, 4, 2}Output: 1 3Explanation: For all numbers in the range [1, 5], 1 and 3 are
4 min read