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:
Sort an array without changing position of negative numbers
Next article icon

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

Last Updated : 16 Oct, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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: -7
Explanation: Except -7 all the numbers in arr[] are positive integers. 

Input: arr[] = {-3,  5,  -9}
Output: 5

 

Brute Force Approach:

A brute force approach to solve this problem would be to iterate over each element of the array and check whether it is positive or negative. We can keep track of the number of positive and negative elements in the array. Once we have this information, we can simply return the element that is different from the others.

Below is the implementation of the above approach: 

C++




#include <iostream>
using namespace std;
 
int find(int* a, int N)
{
    int i, pos_count = 0, neg_count = 0;
    for (i = 0; i < N; i++) {
        if (a[i] > 0) {
            pos_count++;
        }
        else {
            neg_count++;
        }
    }
    if (pos_count == 1) {
        for (i = 0; i < N; i++) {
            if (a[i] > 0) {
                return a[i];
            }
        }
    }
    else if (neg_count == 1) {
        for (i = 0; i < N; i++) {
            if (a[i] < 0) {
                return a[i];
            }
        }
    }
    return -1;
}
 
int main()
{
    int arr[] = { 3, 5, 2, 8, -7, 6, 9 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    cout << find(arr, N);
 
    return 0;
}
 
 

Java




import java.util.*;
 
public class Main {
     
    public static int find(int[] a, int N) {
        int pos_count = 0, neg_count = 0;
        for (int i = 0; i < N; i++) {
            if (a[i] > 0) {
                pos_count++;
            }
            else {
                neg_count++;
            }
        }
        if (pos_count == 1) {
            for (int i = 0; i < N; i++) {
                if (a[i] > 0) {
                    return a[i];
                }
            }
        }
        else if (neg_count == 1) {
            for (int i = 0; i < N; i++) {
                if (a[i] < 0) {
                    return a[i];
                }
            }
        }
        return -1;
    }
 
    public static void main(String[] args) {
        int[] arr = { 3, 5, 2, 8, -7, 6, 9 };
        int N = arr.length;
 
        System.out.println(find(arr, N));
    }
}
 
 

Python3




def find(a, N):
    pos_count = 0
    neg_count = 0
    for i in range(N):
        if a[i] > 0:
            pos_count += 1
        else:
            neg_count += 1
    if pos_count == 1:
        for i in range(N):
            if a[i] > 0:
                return a[i]
    elif neg_count == 1:
        for i in range(N):
            if a[i] < 0:
                return a[i]
    return -1
 
arr = [3, 5, 2, 8, -7, 6, 9]
N = len(arr)
print(find(arr, N))
 
 

C#




using System;
 
public class Program
{
    public static int Find(int[] a, int N)
    {
        // Count the number of positive and negative elements in the array.
        int posCount = 0;
        int negCount = 0;
        for (int i = 0; i < N; i++)
        {
            if (a[i] > 0)
            {
                posCount++;
            }
            else
            {
                negCount++;
            }
        }
 
        // If there is exactly one positive element, return it.
        if (posCount == 1)
        {
            for (int i = 0; i < N; i++)
            {
                if (a[i] > 0)
                {
                    return a[i];
                }
            }
        }
 
        // If there is exactly one negative element, return it.
        if (negCount == 1)
        {
            for (int i = 0; i < N; i++)
            {
                if (a[i] < 0)
                {
                    return a[i];
                }
            }
        }
 
        // If there is no single element, return -1.
        return -1;
    }
 
    public static void Main()
    {
        int[] arr = { 3, 5, 2, 8, -7, 6, 9 };
        int N = arr.Length;
 
        Console.WriteLine(Find(arr, N));
    }
}
 
// This code is contributed by shivamgupta310570
 
 

Javascript




function find(a, N) {
    let pos_count = 0;
    let neg_count = 0;
    for (let i = 0; i < N; i++) {
        if (a[i] > 0) {
            pos_count++;
        } else {
            neg_count++;
        }
    }
    if (pos_count === 1) {
        for (let i = 0; i < N; i++) {
            if (a[i] > 0) {
                return a[i];
            }
        }
    } else if (neg_count === 1) {
        for (let i = 0; i < N; i++) {
            if (a[i] < 0) {
                return a[i];
            }
        }
    }
    return -1;
}
 
const arr = [3, 5, 2, 8, -7, 6, 9];
const N = arr.length;
console.log(find(arr, N));
 
 
Output
-7   

Time Complexity: O(N^2)

Space Complexity: O(1)

Approach: The given problem can be solved by just comparing the first three numbers of arr[]. After that apply Linear Search and find the number. Follow the steps below to solve the problem. 

  • If the size of arr[] is smaller than 3, then return 0.
  • Initialize the variables Cp and Cn.
  • Where Cp = Count of positive integers and Cn = Count of negative integers.
  • Iterate over the first 3 element
    • If (arr[i]>0), Increment Cp by 1.
    • Else Increment Cn by 1.
  • Cp can be 2 or 3 and similarly, Cn can also either 2 or 3.
  • If Cp<Cn, then the single element is positive, apply linear search and find it.
  • If Cn<Cp, then the single element is negative, apply linear search and find it.

Below is the implementation of the above approach: 

C++




// C++ program for the above approach
#include <iostream>
using namespace std;
 
// Function to return the single element
int find(int* a, int N)
{
    // Size can not be smaller than 3
    if (N < 3)
        return 0;
 
    // Initialize the variable
    int i, Cp = 0, Cn = 0;
 
    // Check the single element is
    // positive or negative
    for (i = 0; i < 3; i++) {
 
        if (a[i] > 0)
            Cp++;
        else
            Cn++;
    }
 
    // Check for positive single element
    if (Cp < Cn) {
        for (i = 0; i < N; i++)
            if (a[i] > 0)
                return a[i];
    }
 
    // Check for negative single element
    else {
        for (i = 0; i < N; i++)
            if (a[i] < 0)
                return a[i];
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 3, 5, 2, 8, -7, 6, 9 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    cout << find(arr, N);
}
 
 

Java




// Java program for the above approach
import java.util.*;
public class GFG {
 
// Function to return the single element
static int find(int []a, int N)
{
    // Size can not be smaller than 3
    if (N < 3)
        return 0;
 
    // Initialize the variable
    int i, Cp = 0, Cn = 0;
 
    // Check the single element is
    // positive or negative
    for (i = 0; i < 3; i++) {
 
        if (a[i] > 0)
            Cp++;
        else
            Cn++;
    }
 
    // Check for positive single element
    if (Cp < Cn) {
        for (i = 0; i < N; i++)
            if (a[i] > 0)
                return a[i];
    }
 
    // Check for negative single element
    else {
        for (i = 0; i < N; i++)
            if (a[i] < 0)
                break;
    }
    return a[i];
}
 
// Driver Code
public static void main(String args[])
{
    int []arr = { 3, 5, 2, 8, -7, 6, 9 };
    int N = arr.length;
    System.out.println(find(arr, N));
}
}
 
// This code is contributed by Samim Hossain Mondal.
 
 

Python3




# python program for the above approach
 
# Function to return the single element
def find(a, N):
 
    # Size can not be smaller than 3
    if (N < 3):
        return 0
 
    # Initialize the variable
    Cp = 0
    Cn = 0
 
    # Check the single element is
    # positive or negative
    for i in range(0, 3):
 
        if (a[i] > 0):
            Cp += 1
        else:
            Cn += 1
 
        # Check for positive single element
    if (Cp < Cn):
        for i in range(0, N):
            if (a[i] > 0):
                return a[i]
 
        # Check for negative single element
    else:
        for i in range(0, N):
            if (a[i] < 0):
                return a[i]
 
# Driver Code
if __name__ == "__main__":
 
    arr = [3, 5, 2, 8, -7, 6, 9]
    N = len(arr)
 
    print(find(arr, N))
 
    # This code is contributed by rakeshsahni
 
 

C#




// C# program for the above approach
using System;
class GFG {
 
// Function to return the single element
static int find(int []a, int N)
{
    // Size can not be smaller than 3
    if (N < 3)
        return 0;
 
    // Initialize the variable
    int i, Cp = 0, Cn = 0;
 
    // Check the single element is
    // positive or negative
    for (i = 0; i < 3; i++) {
 
        if (a[i] > 0)
            Cp++;
        else
            Cn++;
    }
 
    // Check for positive single element
    if (Cp < Cn) {
        for (i = 0; i < N; i++)
            if (a[i] > 0)
                return a[i];
    }
 
    // Check for negative single element
    else {
        for (i = 0; i < N; i++)
            if (a[i] < 0)
                break;
    }
    return a[i];
}
 
// Driver Code
public static void Main()
{
    int []arr = { 3, 5, 2, 8, -7, 6, 9 };
    int N = arr.Length;
    Console.Write(find(arr, N));
}
}
 
// This code is contributed by Samim Hossain Mondal.
 
 

Javascript




<script>
// Javascript program for the above approach
 
// Function to return the single element
function find(a, N)
{
    // Size can not be smaller than 3
    if (N < 3)
        return 0;
 
    // Initialize the variable
    let i, Cp = 0, Cn = 0;
 
    // Check the single element is
    // positive or negative
    for (i = 0; i < 3; i++) {
 
        if (a[i] > 0)
            Cp++;
        else
            Cn++;
    }
 
    // Check for positive single element
    if (Cp < Cn) {
        for (i = 0; i < N; i++)
            if (a[i] > 0)
                return a[i];
    }
 
    // Check for negative single element
    else {
        for (i = 0; i < N; i++)
            if (a[i] < 0)
                return a[i];
    }
}
 
// Driver Code
let arr = [ 3, 5, 2, 8, -7, 6, 9 ];
let N = arr.length;
 
document.write(find(arr, N));
 
// This code is contributed Samim Hossain Mondal.
</script>
 
 
Output
-7   

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

 



Next Article
Sort an array without changing position of negative numbers
author
akashjha2671
Improve
Article Tags :
  • Arrays
  • DSA
  • School Programming
Practice Tags :
  • Arrays

Similar Reads

  • Find ratio of zeroes, positive numbers and negative numbers in the Array
    Given an array a of integers of size N integers, the task is to find the ratio of positive numbers, negative numbers and zeros in the array up to four decimal places. Examples: Input: a[] = {2, -1, 5, 6, 0, -3} Output: 0.5000 0.3333 0.1667 There are 3 positive, 2 negative, and 1 zero. Their ratio wo
    7 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
  • Only integer with positive value in positive negative value in array
    Given an array of N integers. In the given, for each positive element 'x' there exist a negative value '-x', except one integer whose negative value is not present. That integer may occur multiple number of time. The task is find that integer. Examples: Input : arr[] = { 1, 8, -6, -1, 6, 8, 8 } Outp
    8 min read
  • Find the maximum among the count of positive or negative integers in the array
    Given a sorted array arr[] consisting of N integers, the task is to find the maximum among the count of positive or negative integers in the array arr[]. Examples: Input: arr[] = {-9, -7, -4, 1, 5, 8, 9}Output: 4Explanation:The count of positive numbers is 4 and the count of negative numbers is 3. S
    9 min read
  • Sort an array without changing position of negative numbers
    Given an array arr[] of N integers, the task is to sort the array without changing the position of negative numbers (if any) i.e. the negative numbers need not be sorted. Examples: Input: arr[] = {2, -6, -3, 8, 4, 1} Output: 1 -6 -3 2 4 8 Input: arr[] = {-2, -6, -3, -8, 4, 1} Output: -2 -6 -3 -8 1 4
    5 min read
  • Rearrange Array in negative numbers, zero and then positive numbers order
    Given an arr[ ] of size N, containing positive, negative integers and one zero. The task is to rearrange the array in such a way that all negative numbers are on the left of 0 and all positive numbers are on the right. Note: It is not mandatory to maintain the order of the numbers. If there are mult
    6 min read
  • 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
  • Check if a number is positive, negative or zero using bit operators
    Given a number N, check if it is positive, negative or zero without using conditional statements.Examples: Input : 30 Output : 30 is positive Input : -20 Output : -20 is negative Input: 0 Output: 0 is zero The signed shift n>>31 converts every negative number into -1 and every other into 0. Wh
    5 min read
  • Segregate positive and negative numbers
    Given an array arr[] of integers, the task is to rearrange the array so that all negative numbers appear before all positive numbers. Examples: Input: arr[] = [12, 11, -13, -5, 6, -7, 5, -3, -6]Output: [-13, -5, -7, -3, -6, 12, 11, 6, 5]Explanation: All negative elements [-13, -5, -7, -3, -6] were a
    9 min read
  • Largest number having both positive and negative values present in the array
    Given an array arr[] consisting of N integers, the task is to find the largest number K (> 0) such that both the values K and -K are present in the given array arr[]. If no such number exists, then print -1. Examples: Input: arr[] = {3, 2, -2, 5, -3}Output: 3 Input: arr[] = {1, 2, 3, -4}Output: -
    14 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