oneby7

Recursion and Backtracking Pick or skip

313. Does a Subsequence with Sum K Exist

Medium

You are given an array of integers nums and an integer k. Return true if some subsequence of nums adds up to exactly k, and false otherwise.

A subsequence is any selection of elements from nums, kept in their original order. The chosen elements do not have to be next to each other, and each element can be chosen at most once.

The subsequence must hold at least one element. The empty subsequence does not count, so for k = 0 you need a real selection of one or more elements that adds up to 0.

Example 1

Input: nums = [6, -4, 9, 2, -5], k = 1

Output: true

Explanation: Choosing 6 and −5, the first and the last elements, gives 6 + (−5) = 1. The elements between them are skipped.

Example 2

Input: nums = [3, 5, 1], k = 0

Output: false

Explanation: Every element is positive, so every non-empty subsequence adds up to at least 1. Only the empty subsequence adds up to 0, and it does not count.

Example 3

Input: nums = [1000000000, 1000000000, -7, 1000000000] k = 3000000000

Output: true

Explanation: Skipping −7 leaves three values that add up to 3000000000. That is more than a 32-bit integer can hold.

Check your understanding

Work out the answer for this input before you write any code.

nums = [4, 7], k = 0

Constraints

  • 1 ≤ nums.length ≤ 20
  • -109 ≤ nums[i] ≤ 109
  • -2 × 1010 ≤ k ≤ 2 × 1010

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.