Data Structures & AlgorithmsHard
What is the length of the longest contiguous subarray of 3 -2 0 4 -1 0 2 -5 in which the number of positive elements equals the number of negative elements?
- A. 4
- B. 8
- C. 6
- D. 3
Correct answer: B. 8
Map positive → +1, negative → −1 and zero → 0; the whole array has 3 positives and 3 negatives, so its sum is 0 and the answer is 8. Treating zeros as negatives gives 4, ignoring the zeros gives 6, and 3 is the number of positives.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- A window with at most K replacements (or at most K zeros) is found with two pointers. Why is it safe for the left pointer to only move…
- In 'product of array except self', why does a single zero need special handling?
- Why does counting subarrays with sum exactly k, when elements can be NEGATIVE, use a hash map of prefix sums and not a sliding window?
- When counting pairs with a given sum in a sorted array using two pointers, why is sorting essential?
- The 3-sum two-pointer method skips a value when it equals the previous value. Why?
- What is the lexicographically smallest array of length n with positive integers and total sum S (S ≥ n)?