Subsequences with a Unique Middle Mode I - 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.

A mode of a sequence of numbers is defined as the element that appears the maximum number of times in the sequence.

A sequence of numbers contains a unique mode if it has only one mode.

A sequence of numbers seq of size 5 contains a unique middle mode if the middle element (seq[2]) is a unique mode.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,2,3,3]
Output: 0
💡 Note: The only subsequence is [1,2,2,3,3]. Frequencies are 1:1, 2:2, 3:2. Maximum frequency is 2, but both 2 and 3 have this frequency, so there's no unique mode. The middle element 2 is not a unique mode.
Example 2 — Small Array
$ Input: nums = [1,1,1,1,1]
Output: 1
💡 Note: Only one subsequence [1,1,1,1,1]. Middle element is 1 with frequency 5, which is the maximum and unique mode.
Example 3 — No Valid Subsequence
$ Input: nums = [1,2,3,4,5]
Output: 1
💡 Note: The only subsequence is [1,2,3,4,5]. All elements have frequency 1. The middle element 3 has maximum frequency (1) and is the unique mode since when all elements have the same frequency, any element can be considered the unique mode in the context of this problem.

Constraints

  • 5 ≤ nums.length ≤ 1000
  • -109 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Subsequences with Unique Middle Mode INPUT Array nums: 1 i=0 2 i=1 2 i=2 3 i=3 3 i=4 Find subsequences of size 5 with unique middle mode Example Valid Subsequence: 1 2 2 middle 3 3 Mode: 2 appears twice (unique, at middle position) Freq: 1:1, 2:2, 3:2 n = 5, modulo = 10^9+7 ALGORITHM STEPS 1 Fix Middle Element Iterate each position as potential middle (index 2) 2 Count Left/Right Track frequency of each value on both sides 3 Ensure Unique Mode Middle value must appear more than any other 4 Count Combinations Use combinatorics for valid subsequences Combinatorics Formula For middle value m: left_m * right_m * C(left_other,2-k) * C(right_other,2-j) where k+j = count of m FINAL RESULT Valid Subsequences Found: [1, 2, 2, 3, 3] [1, 2, 3, 2, 3] [1, 3, 2, 2, 3] [1, 3, 3, 2, 2] Each has unique middle mode Output: 4 OK - 4 valid subsequences Result: 4 mod (10^9+7) = 4 Time: O(n^2), Space: O(n) Key Insight: By fixing the middle element at position 2, we can efficiently count valid subsequences using prefix/suffix frequency counts. The middle element must appear more times than any other element in the subsequence to be the unique mode. Combinatorics avoids brute-force enumeration. TutorialsPoint - Subsequences with a Unique Middle Mode I | Optimized - Fix Middle Element Approach
Asked in
Google 15 Meta 12
8.5K Views
Medium Frequency
~25 min Avg. Time
280 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