Skip to content
Problem 491 · LeetCode 491(opens in a new tab)

Non-decreasing Subsequences

MediumArrays

You are given an array of whole numbers, nums. A subsequence keeps some of the numbers in their original order, possibly with gaps. Call it non-decreasing when each number is at least as large as the one before it.

Return every different non-decreasing subsequence that has two or more numbers. Two subsequences that contain the same values in the same order count once, even if they come from different positions. The list can be in any order.

Example 1

Input:  nums = [1, 3, 2, 3]
Output: [[1, 3], [1, 3, 3], [1, 2], [1, 2, 3], [3, 3], [2, 3]]
Why:    [1, 3] can be built two ways but is listed once
2 more examples and the constraints

Example 2

Input:  nums = [5, 4, 3]
Output: []
Why:    every pair goes down

Example 3

Input:  nums = [2, 1, 2]
Output: [[2, 2], [1, 2]]
Why:    equal neighbours like 2, 2 are allowed

Constraints

  • 1 ≤ length of nums ≤ 15
  • −100 ≤ nums[i] ≤ 100

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Every subset, then dedupeO(2ⁿ · n)
  2. Backtracking with a used set per depthO(2ⁿ · n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 15 numbersVerdict
Every subset, then dedupeO(2ⁿ · n)
Builds every subset, then filters
Backtracking with a used set per depthO(2ⁿ · n)
Best; builds only the answers

n = how many numbers are in the array. The output itself can hold close to 2ⁿ sequences, so no method beats O(2ⁿ) in the worst case.

Edge cases to test

  • One number. [4] has no subsequence of length two: return [].
  • Strictly falling. [5, 4, 3] also gives [].
  • All equal. [7, 7, 7] gives [7, 7] and [7, 7, 7], each once.
  • Negative numbers. [-3, -3, 0] works the same: [-3, -3], [-3, -3, 0], [-3, 0].

Common mistakes

  • Sorting nums first to group duplicates, which changes which subsequences exist.
  • Using one used set for the whole search, which also blocks [7, 7].
  • Adding the path itself to the result instead of a copy, so every entry ends up empty.

How to talk through it

  1. 1Clarify. Does equal count as non-decreasing? Do repeated sequences from different positions count once? Any order?
  2. 2Give the subset idea. Every mask is a subsequence; check it and dedupe with a set. Say why it builds copies.
  3. 3Switch to backtracking. Extend the path only with numbers that keep it non-decreasing; record it at length two or more.
  4. 4Explain the used set. Per depth, not global, and why sorting is not allowed here.
  5. 5Test out loud. Run [2, 1, 2], an all-equal array and a falling one before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?