#3395

Subsequences with a Unique Middle Mode I

Hard
ArrayHash TableMathCombinatoricsHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Instead of generating all combinations, we can directly count valid subsequences by iterating through the array and using frequency counts to determine valid configurations around each potential middle mode.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count the frequency of each number in the array.
  2. 2Step 2: For each unique number, consider it as the middle mode and calculate how many valid combinations can be formed with it as the middle element.
  3. 3Step 3: Use combinatorial mathematics to count how many ways we can select elements on the left and right of the middle mode.
solution.py18 lines
1# Full working Python code
2from collections import Counter
3from math import comb
4
5def count_unique_middle_mode_subsequences(nums):
6    mod = 10**9 + 7
7    freq = Counter(nums)
8    count = 0
9    for mid in freq:
10        if freq[mid] < 3:
11            continue
12        left_count = sum(v for k, v in freq.items() if k < mid)
13        right_count = sum(v for k, v in freq.items() if k > mid)
14        mid_count = freq[mid]
15        # Choose 2 from mid_count and 1 from left and right
16        count += comb(mid_count, 3) * comb(left_count, 1) * comb(right_count, 1)
17        count %= mod
18    return count

Complexity note: The optimal solution runs in O(n) because we only traverse the array a couple of times to build frequency counts and calculate combinations.

  • 1The middle element must be the unique mode, meaning it must appear more than any other element in the subsequence.
  • 2Using combinatorial counting allows us to efficiently calculate the number of valid subsequences without generating them.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.