logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
instagramtwitterfacebookyoutubelinkedinmailgithubrss
Copyright © 2026 All rights reserved.
•
VIKI
Built with Vikramaditya Singh
Built with
VIKI - A posts created with Next.js and Tailwind.css
About
leetcode
Title
Table Of Contents
easy
13. Roman to Integer
14. Longest Common Prefix
20. Valid Parentheses
26. Remove Duplicates from Sorted Array
35. Search Insert Position
69. Sqrt(x)
70. Climbing Stairs
88. Merge Sorted Array (In-Place)
104. Maximum Depth of Binary Tree
118. Pascal's Triangle
121. Best Time to Buy and Sell Stock
205. Isomorphic Strings
242. Valid Anagram
283. Move Zeroes
345. Reverse Vowels of a String
605. Can Place Flowers
704. Binary Search
796. Rotate String
1071. Greatest Common Divisor of Strings
1299. Replace Elements with Greatest Element on Right Side
1431. Kids With the Greatest Number of Candies
1614. Maximum Nesting Depth of the Parentheses
1752. Check if Array Is Sorted and Rotated
1768. Merge Strings Alternately
1903. Largest Odd Number in String
2965. Find Missing and Repeated Values
hard
25. Reverse Nodes in k-Group
26. Remove Duplicates from Sorted Array
27. Remove Element
42. Trapping Rain Water
51. N-Queens
55. Jump Game
80. Remove Duplicates from Sorted Array II
88. Merge Sorted Array
121. Best Time to Buy and Sell Stock
122. Best Time to Buy and Sell Stock II
189. Rotate Array
274. H-Index
medium
2. Add Two Numbers
3. Longest Substring Without Repeating Characters
5. Longest Palindromic Substring
8. String to Integer (atoi)
11. Container With Most Water
15. 3Sum
17. Letter Combinations of a Phone Number
19. Remove Nth Node From End of List
22. Generate Parentheses
33. Search in Rotated Sorted Array
34. Find First and Last Position of Element in Sorted Array
48. Rotate Image
49. Group Anagrams
50. Pow(x, n)
53. Maximum Subarray
54. Spiral Matrix
56. Merge Intervals
61. Rotate List
73. Set Matrix Zeroes
74. Search a 2D Matrix
75. Sort Colors
78. Subsets
137. Single Number II
138. Copy List with Random Pointer
150. Evaluate Reverse Polish Notation
151. Reverse Words in a String
153. Find Minimum in Rotated Sorted Array
155. Min Stack
162. Find Peak Element
169. Majority Element
198. House Robber
207. Course Schedule
215. Kth Largest Element in an Array
227. Basic Calculator II
236. Lowest Common Ancestor of a Binary Tree
237. Delete Node in a Linked List
238. Product of Array Except Self
451. Sort Characters By Frequency
540. Single Element in a Sorted Array
560. Subarray Sum Equals K
636. Exclusive Time of Functions
875. Koko Eating Bananas
1011. Capacity To Ship Packages Within D Days
1101. The Earliest Moment When Everyone Become Friends
1283. Find the Smallest Divisor Given a Threshold
2140. Solving Questions With Brainpower
3169. Count Days Without Meetings
3481. Apply Substitutions
rotate-array-approach-1
189. Rotate Array (Approach 2 )
189. Rotate Array (Approach 1 )
number-of-islands-approach-1
200. Number of Islands (Approach 2)
200. Number of Islands (Approach 1)
meeting-rooms-ii-approach-1
253. Approach Using Priority Queue
253. Meeting Rooms II
misc
Calculate Floor & Ceiling
Find Nth Root Of M
Flatten A Linked List
Implement Lower Bound
Implement Upper Bound
Number of occurrence
take-u-forward
Recently Solved
arrays
The Ultimate Array Pattern Playbook
faqs-hard
Count Inversions in an Array
Find The Repeating And Missing Number
Majority Element II
Maximum Product Subarray
Merge Sorted Array (In-Place)
Reverse Pairs
faqs-medium
3. 3Sum
4. 4Sum
Maximum Subarray
Leaders in an Array
Majority Element
Next Permutation
Get specific element from Pascal's Triangle
Pascal's Triangle II (Row Generation)
Generate Pascal's Triangle (Full)
Spiral Matrix Traversal
Rearrange Array Elements by Sign
Rotate Image
Sort Colors (Dutch National Flag)
Two Sum
fundamentals
Check if Array is Sorted
Largest Element in an Array
Array Rotation (Left and Right)
Left Rotate Array by One
Linear Search
Max Consecutive Ones
Second Largest Element in an Array
Single Number
logic-building
Missing Number
Intersection of Two Sorted Arrays (with Duplicates)
Move Zeros to End
Remove Duplicates from Sorted Array
Union of Two Sorted Arrays
binary-search
About
d-arrays
Find Row With Maximum 1'S
Search In A 2D Matrix
faqs
Aggressive Cows
Allocate Books
Find Peak Element
Kth Element Of 2 Sorted Arrays
Minimise Max Distance to Gas Stations
Split Array - Largest Sum
fundamentals
Lower Bound
Binary Search
Upper Bound
logic-building
Count Occurrences in a Sorted Array
Find Minimum in Rotated Sorted Array
Find out how many times the array is rotated
Find First and Last Position of Element in Sorted Array
Floor and Ceil in Sorted Array
Kth Missing Positive Number
Search in Rotated Sorted Array
Search in Rotated Sorted Array II (With Duplicates)
Search Insert Position
Single Element in a Sorted Array
on-answers
Capacity To Ship Packages Within D Days
Find Nth Root of M
Find Square Root of a Number
Smallest Divisor Given a Threshold
Koko Eating Bananas (Minimum Rate)
Minimum Days to Make M Bouquets
Painter's Partition Problem
Split Array Largest Sum
hashing
Theory
faqs
Subarray Sum Equals K
Count Subarrays with Given XOR K
Largest Subarray with 0 Sum
Longest Consecutive Sequence
Longest Subarray with Sum K
recursion
faqs-medium
Combination Sum II (Unique Combinations)
Combination Sum (Unbounded)
Subset Sums
hard
Letter Combinations of a Phone Number
implementation-problems
Generate Parentheses
Power Function: pow(x, n)
Subsets (The Power Set)
subsequence-pattern-problems
Subsequence Sum Existence
Count All Subsequences With Sum K
sorting
Bubble Sort
Insertion Sort
Merge Sort
Quick Sort
Selection Sort
string
Isomorphic Strings
Largest Odd Number in String
Longest Common Prefix
Reverse Words in a String
Code Scratch›take u forward›recursion›subsequence pattern problems

Subsequence Sum Existence

# Question

Given an array numsnumsnums of nnn integers and a target kkk, return true if there exists a subsequence such that the sum of its elements equals kkk. Otherwise, return false.

# Solution 1: Top-Down (The Decision Tree)

Pattern: Backtracking with Memoization.

  • Intuition: We simulate every possible subsequence. If we hit the same (index, k) twice, we return the cached result.
  • Code Logic: solve(idx + 1, k) || solve(idx + 1, k - nums[idx])

# Solution 2: Bottom-Up (The Building Blocks)

Pattern: Tabulation.

  • Intuition: We fill a 2D grid. Each cell represents a "State" of reachability.
  • Decision: dp[i][j] = dp[i-1][j] || dp[i-1][j - nums[i-1]].

# Solution 3: Space Optimized (The Collapsed Row)

Pattern: 1D DP Array.

  • Intuition: Since we only ever look at the "previous" row, we use one array and update it in place.
  • The Catch: You must iterate backwards through the sums to prevent a single number from being "re-used" to reach a larger sum in the same iteration.

# Pattern

Dynamic Programming (0/1 Knapsack Variation) This problem is a classic "Subset Sum" problem where each element can either be included or excluded to reach a target value.

# How to Identify

  • Subsequence/Subset requirement: Looking for a combination of elements.
  • Fixed Target: The goal is a specific sum kkk.
  • Binary Choice: At each element, the only decision is: "Do I pick this or not?"

# Description

Step-by-step explanation:

  1. State Definition: We use a boolean array dp of size k+1k+1k+1, where dp[i] is true if a sum iii can be formed using a subset of elements seen so far.
  2. Base Case: dp[0] = true because a sum of 0 is always possible using an empty subsequence.
  3. Iterative Processing: For each number num in nums:
    • We iterate backwards through the dp array from kkk down to num.
    • Backwards Loop: This is critical. By going from k→numk \to numk→num, we ensure that each element is only used once. If we went forward, we would effectively solve the "Unbounded" version (reusing elements).
  4. Update Rule: dp[i] = dp[i] || dp[i - num]. If the sum i - num was possible, then adding the current num makes sum i possible.
  5. Early Exit: If dp[k] becomes true at any point, we return immediately.
# The Core DP Transition: dp[i] = dp[i - num]
# The Logical Meaning

This line represents the State Transition Equation. It connects a problem you've already solved to a slightly larger problem you're trying to solve now.

# The Components
  1. i: The target sum we are currently considering.
  2. num: The current element from the array we are "trying out."
  3. i - num: The "remainder." The sum we would need to have already formed to make i possible.
  4. dp[i - num]: A boolean check. "Is the remainder actually possible?"
# Why No "Else"?

You'll notice there is no else { dp[i] = false; }. This is because if dp[i] was already True (found by a different combination of numbers earlier), we don't want to overwrite it with False. Once a sum is reachable, it stays reachable.

# Concepts to Think About
  • Space Optimization: We only look at i - num, which is always a smaller index than i. This is why we can get away with a 1D array.
  • The "Take" Decision: This if statement represents the "Take" branch of your recursion. The "Don't Take" branch is handled automatically because if we don't enter the if, dp[i] simply keeps its previous value.

# The Intuition

Think of the dp array as a reachability map. Initially, only position 0 is reachable. When you encounter a number (e.g., 5), you look at all currently reachable spots and "jump" 5 units forward from them to mark new reachable spots. Repeating this for all numbers eventually tells you if position kkk is reachable.

# Complexity

LabelWorstAverage
Time ComplexityO(N⋅K)O(N \cdot K)O(N⋅K)O(N⋅K)O(N \cdot K)O(N⋅K)
Space ComplexityO(K)O(K)O(K)O(K)O(K)O(K)

# Time Complexity

We iterate through NNN elements, and for each, we scan up to KKK values in the dp array. Total operations ≈N×K\approx N \times K≈N×K.

# Space Complexity

We only maintain a single 1D array of size K+1K+1K+1. No recursion stack is used.

# Code

class Solution {
    public boolean checkSubsequenceSum(int[] nums, int k) {
        // dp[i] represents if sum 'i' is achievable
        boolean[] dp = new boolean[k + 1];
 
        // Base case: sum 0 is always possible
        dp[0] = true;
 
        for (int num : nums) {
            // Optimization: if num > k, it cannot contribute to sum k (assuming positive nums)
            if (num > k) continue;
 
            // Update dp table backwards to prevent using same element multiple times
            for (int i = k; i >= num; i--) {
                if (dp[i - num]) {
                    dp[i] = true;
                }
            }
 
            // Early exit
            if (dp[k]) return true;
        }
 
        return dp[k];
    }
}

# Caveats

  • Negative Values: If the array contains negative numbers, the target kkk is no longer a strict upper bound for the DP array. You would need to shift the range or use a HashSet to store possible sums.
  • Large KKK: If KKK is very large (e.g., 10910^9109), but NNN is small (≤40\le 40≤40), DP will fail due to memory. Use Meet-in-the-middle instead.

# Concepts to Think About

  • 0/1 Knapsack: This is exactly the same logic as the knapsack problem, where "weight" and "value" are the same.
  • Bit Manipulation (Ultimate Optimization): In Java, you can use java.util.BitSet. The update becomes bitset.or(bitset.shiftLeft(num)). This uses bitwise parallelism to speed up the O(K)O(K)O(K) loop by a factor of 64.
  • Reconstructing the Solution: To find which numbers form the sum, you would need the O(N⋅K)O(N \cdot K)O(N⋅K) 2D matrix to backtrack.
  • Space Optimization: Why backward? If you go forward: dp[5]dp[5]dp[5] becomes true from dp[0]dp[0]dp[0], then dp[10]dp[10]dp[10] becomes true from dp[5]dp[5]dp[5] in the same iteration, effectively using the number '5' twice.

# Why Bottom-Up Works (The Snapshot Rule)

# The Logic

Bottom-Up DP is just a way of saying: "If I have a set of possible sums, and I get a new number xxx, my new set of possible sums is (Old Sums) ∪\cup∪ (Old Sums + xxx)."

# Why the Backward Loop is Mandatory

  • 0/1 Knapsack (Use each once): We must update the array using only the "Old" information. By moving backwards (k→numk \to numk→num), we ensure that when we check dp[i-num], it hasn't been touched by the current number yet. It is a "clean" value from the previous iteration.
  • Unbounded Knapsack (Use many times): If the problem allowed you to use the same number infinitely, you would move forwards.

# Decision Choice

  • Recursive (Top-Down): Starts at the goal and asks "What do I need to get here?"
  • Iterative (Bottom-Up): Starts at 0 and asks "What can I reach from here?"

# Logical Follow-up

Question: What if KKK is 10910^9109 and NNN is 30? Solution: Use Meet-in-the-middle. Split the array into two halves of size 15. Generate all possible 2152^{15}215 sums for each half (Total ≈32,768\approx 32,768≈32,768 sums each). Sort one set and for each sum sss in the other set, binary search for k−sk-sk−s. Total time: O(2n/2⋅n)O(2^{n/2} \cdot n)O(2n/2⋅n).

Question: What if you can use each number an infinite number of times? Solution: This is the Coin Change variation. Change the inner loop to run forward from num to kkk. This allows the current number to be added repeatedly to previously formed sums in the same pass.

PreviousSubsets (The Power Set)NextCount All Subsequences With Sum K
CONTENTS
QuestionSolution 1: Top-Down (The Decision Tree)Solution 2: Bottom-Up (The Building Blocks)Solution 3: Space Optimized (The Collapsed Row)PatternHow to IdentifyDescriptionThe IntuitionComplexityCodeCaveatsConcepts to Think AboutWhy Bottom-Up Works (The Snapshot Rule)Logical Follow-up