mediumTwo PointersPattern: Mixed

Min Length Bimodal Subsequence Solution

Problem Statement

Given an array of integers `scores`, where each score is either a positive integer or a negative integer, determine the minimum length of a subarray that contains at least one positive integer and one negative integer. If no such subarray exists, return -1.

Examples

Example 1:
Input:{"scores":[3,-1,2,-2]}
Output:2
Explanation: The subarray [3, -1] meets the condition with a length of 2.
Example 2:
Input:{"scores":[1,2,3]}
Output:-1
Explanation: No subarray contains both sweet and savory scores.

Constraints

  • 1 <= scores.length <= 10^5
  • -10^6 <= scores[i] <= 10^6
Time: O(n) Space: O(1)
The optimized approach uses a two-pointer technique to find the minimum length subarray in O(n) time complexity. It iterates through the array and keeps track of the minimum length subarray found so far.

Run, Test & Submit Code

Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.

Solve on Interactive Workspace

Tested Solutions

No solution code is currently loaded.
Complete this code in the workspace editor.