Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Find the only positive or only negative number in the given Array
Next article icon

Remove all negatives from the given Array

Last Updated : 20 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
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)

 



Next Article
Find the only positive or only negative number in the given Array

S

smiti139
Improve
Article Tags :
  • Arrays
  • DSA
  • Misc
Practice Tags :
  • Arrays
  • Misc

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
  • Remove leading zeros from an array
    Given an array of N numbers, the task is to remove all leading zeros from the array. Examples: Input : arr[] = {0, 0, 0, 1, 2, 3} Output : 1 2 3 Input : arr[] = {0, 0, 0, 1, 0, 2, 3} Output : 1 0 2 3 Approach: Mark the first non-zero number's index in the given array. Store the numbers from that ind
    7 min read
  • Check if all array elements can be removed by the given operations
    Given an array arr[] containing distinct elements, the task is to check if all array elements can be removed by the selecting any two adjacent indices such that arr[i] < arr[i+1] and removing one of the two elements or both at each step. If it is possible, then print "Yes". Otherwise, print "No".
    4 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
  • Check if every row in given Matrix contains all the integers from 1 to N
    Given a matrix arr[][] of size M*N containing only positive integers, the task is to check if every row contains all the integers from 1 to N. Examples: Input: arr[][] = {{1, 4, 2, 3}, {2, 3, 4, 1}, {3, 4, 2, 1}}Output: YesExplanation: Every row contains all the numbers from 1 to 4 Input: arr[][] =
    6 min read
  • Find the Maximum Alternate Subsequence Sum from a given array
    Given an array arr[] of size n having both positive and negative integer excluding zero. Find the maximum sum of maximum size alternate subsequence of a given sequence that is, in a subsequence sign of each adjacent element is opposite for example if the first one is positive then the second one has
    5 min read
  • Remove All Occurrences of an Element in an Array
    Given an integer array arr[] and an integer ele the task is to the remove all occurrences of ele from arr[] in-place and return the number of elements which are not equal to ele. If there are k number of elements which are not equal to ele then the input array arr[] should be modified such that the
    6 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
    11 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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences