Non-decreasing Subsequences - Problem

Given an integer array nums, your task is to find all unique non-decreasing subsequences that contain at least two elements. A subsequence is a sequence that can be derived from the original array by deleting some or no elements without changing the order of the remaining elements.

For example, in array [4, 6, 7, 7], valid subsequences include [4, 6], [4, 7], [6, 7], [6, 7, 7], [4, 6, 7], and many more. However, [7, 4] would not be valid since it's decreasing.

Key Points:

  • Subsequences must be non-decreasing (each element โ‰ฅ previous element)
  • Must contain at least 2 elements
  • Return all unique subsequences (no duplicates)
  • Order of results doesn't matter

Input & Output

example_1.py โ€” Basic case
$ Input: [4, 6, 7, 7]
โ€บ Output: [[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]
๐Ÿ’ก Note: All possible non-decreasing subsequences with at least 2 elements. Note that [4,6,7] appears only once even though there are two 7s, because we want unique subsequences.
example_2.py โ€” Simple case
$ Input: [4, 4, 3, 2, 1]
โ€บ Output: [[4,4]]
๐Ÿ’ก Note: Only [4,4] forms a valid non-decreasing subsequence with at least 2 elements. Other combinations would be decreasing.
example_3.py โ€” Edge case
$ Input: [1, 2, 3]
โ€บ Output: [[1,2],[1,2,3],[1,3],[2,3]]
๐Ÿ’ก Note: All elements are in ascending order, so we get all possible combinations of length 2 or more.

Constraints

  • 1 โ‰ค nums.length โ‰ค 15
  • -100 โ‰ค nums[i] โ‰ค 100
  • The number of unique subsequences will not exceed 215
  • Order of result doesn't matter

Visualization

Tap to expand
Optimal: Backtracking with Local DeduplicationArray: [4, 6, 7, 7] โ†’ Track used values at each level[]used: {}[4]used: {4}[6]used: {6}[7]used: {7}[4,6][4,7][6,7][7,7]โœ“ validโœ“ validโœ“ validโœ“ validKey Innovation: Local Setsโ€ข At each recursion level, track used valuesโ€ข Prevents duplicate subsequences naturallyโ€ข No need for global deduplicationโ€ข More efficient than hash set approachTime: O(2^n), Space: O(n) recursionOptimal for this specific problem!Results[4,6], [4,6,7], [4,6,7,7], [4,7], [4,7,7][6,7], [6,7,7], [7,7]Total: 8 unique subsequencesNo duplicates generated!
Understanding the Visualization
1
Start Building
Begin with empty subsequence, consider each element
2
Local Check
At each level, use set to track tried values
3
Add & Recurse
Include element if valid and not tried at this level
4
Collect Results
Save subsequences with length โ‰ฅ 2
Key Takeaway
๐ŸŽฏ Key Insight: Use local sets at each recursion level to prevent duplicate subsequences from being generated, eliminating the need for expensive global deduplication.
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28 Apple 22
89.5K Views
Medium-High Frequency
~25 min Avg. Time
2.3K 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