878832. Find if +ve, -ve or 0
Find if +ve, -ve or 0
Summary
Given an integer array, determine whether all elements are positive, negative, or zero. Write a function that takes an array as input and returns a string indicating whether the array contains only positive numbers, only negative numbers, or a mix of both.
Detailed Explanation
The problem involves analyzing an integer array to determine its characteristics. We can solve this by iterating through the array once and checking the sign of each element. If all elements are the same sign (positive or negative), we return a corresponding message. If not, we return "mix" to indicate that there is a mix of both positive and negative numbers.
Here's a step-by-step breakdown of the solution:
- Initialize a variable
signto store the sign of the first element. - Iterate through the array starting from the second element (index 1).
- For each element, check its sign. If it is different from the initial sign, update
signto "mix". - After iterating through the entire array, return a message based on the value of
sign.- If
signis positive, return "positive". - If
signis negative, return "negative". - If
signis "mix", return "mix".
- If
Time complexity: O(n), where n is the length of the input array. We only need to iterate through the array once.
Space complexity: O(1). We only use a constant amount of space to store the sign variable.
Optimized Solutions
Java
java
public String findSign(int[] arr) {
int sign = 0;
for (int num : arr) {
if (num > 0) {
sign = 1;
} else if (num < 0) {
return "mix";
}
}
return sign == 0 ? "zero" : sign == 1 ? "positive" : "negative";
}
Python
python
def find_sign(arr):
sign = 0
for num in arr:
if num > 0:
sign = 1
elif num < 0:
return "mix"
return "zero" if sign == 0 else "positive" if sign == 1 else "negative"
C++
cpp
#include <iostream>
using namespace std;
string findSign(int arr[], int n) {
int sign = 0;
for (int i = 0; i < n; i++) {
if (arr[i] > 0) {
sign = 1;
} else if (arr[i] < 0) {
return "mix";
}
}
return sign == 0 ? "zero" : sign == 1 ? "positive" : "negative";
}
JavaScript
javascript
function findSign(arr) {
let sign = 0;
for (let num of arr) {
if (num > 0) {
sign = 1;
} else if (num < 0) {
return "mix";
}
}
return sign === 0 ? "zero" : sign === 1 ? "positive" : "negative";
}
Not available