703484. Positive and negative elements
Positive and Negative Elements
Slug: positive-and-negative-elements4613 Difficulty: Basic Id: 703484 Topic Tags: Arrays, Data Structures Company Tags: Amazon
Summary
The problem is about finding the count of positive and negative elements in an array. This involves iterating through the array, checking each element's sign, and updating the counts accordingly.
Detailed Explanation
To solve this problem, we can start by initializing two variables, pos_count to store the count of positive elements and neg_count to store the count of negative elements. Then, iterate through the array using a for loop or other suitable method. For each element in the array:
- Check if the element is positive (greater than 0).
- If it's positive, increment
pos_count. - If it's negative (less than 0), increment
neg_count.
Finally, return the counts of positive and negative elements.
Here's a step-by-step breakdown of the solution:
pos_count = 0
neg_count = 0
for each element in array:
if element > 0:
pos_count++
else if element < 0:
neg_count++
return pos_count, neg_count
Time complexity: O(n), where n is the length of the input array. We need to iterate through each element once.
Space complexity: O(1), as we only use a constant amount of space to store the counts.
Optimized Solutions
Java
public static int[] positiveAndNegativeElements(int[] arr) {
int posCount = 0;
int negCount = 0;
for (int num : arr) {
if (num > 0) {
posCount++;
} else if (num < 0) {
negCount++;
}
}
return new int[]{posCount, negCount};
}