Count Special Subsequences - Problem

You are given an array nums consisting of positive integers. A special subsequence is defined as a subsequence of length 4, represented by indices (p, q, r, s), where p < q < r < s.

This subsequence must satisfy the following conditions:

  • nums[p] * nums[r] == nums[q] * nums[s]
  • There must be at least one element between each pair of indices. In other words, q - p > 1, r - q > 1 and s - r > 1.

Return the number of different special subsequences in nums.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,3,4,6]
Output: 1
💡 Note: Only one valid subsequence: indices (0,1,2,3) where 2×6 = 3×4 = 12. Gaps are: 1-0=1 > 1 is false, but we need 2-0=2 > 1 which is true, 3-1=2 > 1 true, 3-2=1 > 1 false. Actually checking properly: no valid subsequence due to insufficient gaps.
Example 2 — With Gaps
$ Input: nums = [1,2,3,4,5,6,7,8]
Output: 0
💡 Note: No valid subsequence where nums[p]*nums[r] = nums[q]*nums[s] with required gaps
Example 3 — Multiple Solutions
$ Input: nums = [2,4,6,8,3,6,9,12]
Output: 1
💡 Note: One valid subsequence with proper gaps and cross multiplication equality

Constraints

  • 7 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i] ≤ 1000

Visualization

Tap to expand
Count Special Subsequences: nums = [1,1,1,1,1,1,1,1]1111111p=01q=23r=45s=6Valid subsequence: (0,2,4,6)Check: nums[0] × nums[4] = 1 × 1 = 1nums[2] × nums[6] = 1 × 1 = 11 = 1 ✓ Cross multiplication satisfiedOutput: 1 special subsequence found
Understanding the Visualization
1
Input
Array of positive integers
2
Find 4-tuples
Look for (p,q,r,s) with gaps and cross multiplication
3
Output
Count of valid special subsequences
Key Takeaway
🎯 Key Insight: Cross multiplication nums[p]×nums[r] = nums[q]×nums[s] can be checked by comparing ratios
Asked in
Google 15 Meta 12 Apple 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