Subsequences with a Unique Middle Mode II - Problem

Given an integer array nums, find the number of subsequences of size 5 of nums with a unique middle mode.

Since the answer may be very large, return it modulo 10^9 + 7.

Definitions:

  • A mode of a sequence is the element that appears the maximum number of times in the sequence.
  • A sequence has a unique mode if it has only one mode (no ties for most frequent).
  • A subsequence of size 5 has a unique middle mode if the middle element (at index 2) is the unique mode of the subsequence.

Note: A subsequence maintains the relative order of elements from the original array but doesn't need to be contiguous.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,1,3,1]
Output: 1
💡 Note: Only one subsequence possible (the entire array): [1,2,1,3,1]. Middle element is 1 (appears 3 times), other elements appear once each, so 1 is the unique mode.
Example 2 — No Valid Subsequences
$ Input: nums = [1,1,1,1,1]
Output: 0
💡 Note: All elements are the same, so no subsequence can have a unique mode - there are always ties.
Example 3 — Minimum Size
$ Input: nums = [1,2,3,4,5]
Output: 0
💡 Note: All elements are distinct, so in any subsequence of size 5, all elements appear once. No unique mode possible since middle element doesn't have higher frequency.

Constraints

  • 5 ≤ nums.length ≤ 2000
  • 1 ≤ nums[i] ≤ 105

Visualization

Tap to expand
Subsequences with Unique Middle Mode II INPUT Array nums: 1 i=0 2 i=1 1 i=2 3 i=3 1 i=4 Subsequence Size: 5 Middle element at index 2 must be unique mode Valid Subsequences: [1, 2, 1, 3, 1] Mode '1' appears 3 times at middle position Value Frequencies: 1: 3x | 2: 1x | 3: 1x ALGORITHM STEPS 1 Count Frequencies Track each element's count 2 Fix Middle Element Try each position as middle 3 Choose 2 Left, 2 Right Select elements both sides 4 Validate Unique Mode Middle must be only mode Combinatorial Counting C(left, 2) * C(right, 2) Subtract invalid cases: - Other elements as mode Result = Total - Invalid mod (10^9 + 7) FINAL RESULT Output: 3 Valid Subsequences: [1,2,1,3,1] - OK [1,1,1,2,3] - OK [2,1,1,1,3] - OK Verification: Middle '1' is unique mode in all 3 cases VERIFIED Key Insight: For a subsequence of size 5 to have a unique middle mode, the middle element must appear MORE times than any other element in the subsequence. Use combinatorics to count valid selections: fix middle, count ways to pick 2 from left and 2 from right, then subtract configurations where another element ties/wins. TutorialsPoint - Subsequences with a Unique Middle Mode II | Optimal Solution
Asked in
Google 15 Facebook 12 Amazon 8
8.5K Views
Medium Frequency
~35 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen