Sign Up Sign Up


Have an account? Sign In Now

Sign In Sign In


Forgot Password?

Don't have account, Sign Up Here

Forgot Password Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.


Have an account? Sign In Now

You must login to ask a question.


Forgot Password?

Need An Account, Sign Up Here

You must login to add post.


Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

RTSALL Logo RTSALL Logo
Sign InSign Up

RTSALL

RTSALL Navigation

  • Home
  • Tools
    • Run Code
    • JSON Beautifier
    • Regex Tester
    • Diff Checker
    • JWT Decoder
    • UUID Generator
    • .htaccess Generator
    • YAML/JSON Converter
    • SQL Formatter
    • Cron Generator
    • JSON to CSV/Excel
    • System Design Estimator
  • DSA
    • All DSA Problems
    • Online C++ Runner
    • Arrays, Strings & Cache
    • Two Pointers & Sliding Window
    • Linked Lists & Custom Allocators
    • Stacks, Queues & Ring Buffers
    • Trees, BSTs & Indexes
    • Tries & Prefix Search
    • Heaps & Priority Schedulers
    • Hashing & Collision Resolution
    • Graphs & Network Topologies
    • Dynamic Programming
    • Advanced Bitmask & Tree DP
    • Greedy & Resource Allocation
    • Binary Search & State Spaces
    • Bit Manipulation & Low-Level
    • System-Scale & Probabilistic
  • AI Utilities
    • Token Counter
    • JSON Schema Compiler
    • Fine-Tuning JSONL Converter
    • Vector RAG Playground
    • Prompt Optimizer & Architect
    • LLM GPU VRAM Calculator
  • Finance Tools
    • Compound Interest Calculator
    • Simple Interest Calculator
    • Present Value (PV) Calculator
    • Future Value (FV) Calculator
    • NPV Calculator
    • IRR Calculator
    • CAGR Calculator
    • Dividend Income Calculator
    • Yield on Cost Calculator
    • Dividend Payout Ratio
    • WACC Calculator
    • CAPM & Cost of Equity
    • Cost of Debt Calculator
    • DCF Valuation Calculator
    • Enterprise Value Calculator
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Tools
    • Run Code
    • JSON Beautifier
    • Regex Tester
    • Diff Checker
    • JWT Decoder
    • UUID Generator
    • .htaccess Generator
    • YAML/JSON Converter
    • SQL Formatter
    • Cron Generator
    • JSON to CSV/Excel
    • System Design Estimator
  • DSA
    • All DSA Problems
    • Online C++ Runner
    • Arrays, Strings & Cache
    • Two Pointers & Sliding Window
    • Linked Lists & Custom Allocators
    • Stacks, Queues & Ring Buffers
    • Trees, BSTs & Indexes
    • Tries & Prefix Search
    • Heaps & Priority Schedulers
    • Hashing & Collision Resolution
    • Graphs & Network Topologies
    • Dynamic Programming
    • Advanced Bitmask & Tree DP
    • Greedy & Resource Allocation
    • Binary Search & State Spaces
    • Bit Manipulation & Low-Level
    • System-Scale & Probabilistic
  • AI Utilities
    • Token Counter
    • JSON Schema Compiler
    • Fine-Tuning JSONL Converter
    • Vector RAG Playground
    • Prompt Optimizer & Architect
    • LLM GPU VRAM Calculator
  • Finance Tools
    • Compound Interest Calculator
    • Simple Interest Calculator
    • Present Value (PV) Calculator
    • Future Value (FV) Calculator
    • NPV Calculator
    • IRR Calculator
    • CAGR Calculator
    • Dividend Income Calculator
    • Yield on Cost Calculator
    • Dividend Payout Ratio
    • WACC Calculator
    • CAPM & Cost of Equity
    • Cost of Debt Calculator
    • DCF Valuation Calculator
    • Enterprise Value Calculator
  • About Us
  • Blog
  • Contact Us

Dynamic Programming: 1D, 2D & Grid

Knapsack problems, sequence alignment, interval DP, rolling memory reductions, and state-machine transitions.

Share
  • Facebook
0 Followers
4 Answers
2 Questions
Home/Data Structures & Algorithms/Dynamic Programming: 1D, 2D & Grid
  • Recent Questions
  • Most Answered
  • Answers
  • No Answers
  • Most Visited
  • Most Voted
  • Random
  1. Asked: September 11, 2026In: Data Structures & Algorithms, Dynamic Programming: 1D, 2D & Grid

    Why does Patience Sorting solve Longest Increasing Subsequence in O(N log N) instead of O(N^2)?

    Abhay Tiwari
    Abhay Tiwari Begginer
    Added an answer on September 11, 2026 at 9:52 am

    This is one of the most common points of confusion when studying LIS. Let's clear up the mystery of why the tails array works even though its contents look 'wrong'. 1. What does the `tails` array actually represent? In Patience Sorting (inspired by solitaire card games): tails[k] stores the SMALLESTRead more

    This is one of the most common points of confusion when studying LIS. Let’s clear up the mystery of why the tails array works even though its contents look ‘wrong’.

    1. What does the `tails` array actually represent?

    In Patience Sorting (inspired by solitaire card games):

    tails[k] stores the SMALLEST ending value of an increasing subsequence of length k + 1 found so far.

    Why do we care about the smallest ending value? Because in an increasing subsequence, the smaller the number you end with, the easier it is for future numbers to be bigger than it! You want to keep your options as open as possible.


    2. The Step-by-Step Card Dealing Analogy

    Suppose our array is: [10, 9, 2, 5, 3, 7, 101, 18].

    1. See 10: tails = [10] (Best subsequence of len 1 ends with 10).
    2. See 9: 9 < 10. Replace 10 with 9: tails = [9] (Ending with 9 is strictly better than ending with 10).
    3. See 2: 2 < 9. Replace 9 with 2: tails = [2].
    4. See 5: 5 > 2! Extend! tails = [2, 5] (Best len 1 ends in 2, best len 2 ends in 5).
    5. See 3: 3 < 5. Replace 5 with 3: tails = [2, 3] (Now best len 2 ends in 3!).
    6. See 7: 7 > 3! Extend! tails = [2, 3, 7] (Len 3).
    7. See 101: Extend! tails = [2, 3, 7, 101] (Len 4).
    8. See 18: 18 < 101. Replace 101 with 18: tails = [2, 3, 7, 18].

    Total length of tails is 4. The answer is 4!


    3. Why the array contents might look scrambled, but length is ALWAYS correct

    Imagine if after [2, 3, 7, 18] we saw 1. We would replace 2 with 1, resulting in tails = [1, 3, 7, 18].

    Notice that [1, 3, 7, 18] might not be a valid subsequence from the original array. And that doesn’t matter!

    Replacing 2 with 1 only prepares the board for a hypothetical future subsequence that starts with 1. It does not change the fact that a valid subsequence of length 4 ([2, 3, 7, 18]) was already locked in!

    The length of tails only increases when a number is strictly greater than ALL existing tail values. Replacements never shrink the array length!


    Clean Python 3.12 Implementation with bisect_left

    from bisect import bisect_left
    
    def length_of_lis(nums: list[int]) -> int:
        """Calculates length of LIS in O(N log N) time and O(N) space."""
        tails = []
    
        for x in nums:
            # Binary search: find first element in tails >= x
            idx = bisect_left(tails, x)
            
            if idx == len(tails):
                # x is strictly greater than all existing tails -> extend length!
                tails.append(x)
            else:
                # Found smaller tail candidate -> update in-place
                tails[idx] = x
    
        return len(tails)
    

    Complexity Breakdown

    • Time Complexity: O(N log N). We iterate through N elements, and for each element we perform binary search over tails (at most length N). N * log(N). For 100,000 elements, this finishes in 0.02 seconds (compared to ~45 seconds for O(N^2)).
    • Space Complexity: O(N) to hold the tails array.
    See less
    • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
  2. Asked: September 11, 2026In: Data Structures & Algorithms, Dynamic Programming: 1D, 2D & Grid

    0/1 Knapsack: Why does reverse iteration turn O(N*W) space into O(W) space?

    Anonymous
    Anonymous Begginer
    Added an answer on September 11, 2026 at 9:52 am

    This is one of the most fundamental 'aha!' moments in dynamic programming. Let's walk through the memory mechanics so you never forget it. 1. The 2D State Transition In the classic 0/1 Knapsack, the formula is: dp[i][w] = max( dp[i-1][w], // Option A: Skip item i (take answer from previous row) dp[iRead more

    This is one of the most fundamental ‘aha!’ moments in dynamic programming. Let’s walk through the memory mechanics so you never forget it.

    1. The 2D State Transition

    In the classic 0/1 Knapsack, the formula is:

    dp[i][w] = max(
        dp[i-1][w],                         // Option A: Skip item i (take answer from previous row)
        dp[i-1][w - weight[i]] + value[i]   // Option B: Take item i (add its value to PREVIOUS row at smaller weight)
    )
    

    Notice the critical detail: in Option B, dp[i-1][w - weight[i]] comes from row i-1 (before item i was even considered). That is what guarantees you only take item i at most once.


    2. Compressing to a 1D Array

    Notice that to compute row i, you only ever look at row i-1. You don’t need rows i-2, i-3, etc. So we can just reuse a single 1D array: dp[w].

    What happens if you iterate FORWARD (w = weight[i] to W)?

    Suppose item 1 has weight = 2, value = 10 and capacity is 6.

    • At w = 2: dp[2] = dp[0] + 10 = 10.
    • At w = 4: dp[4] = dp[4 - 2] + 10 = dp[2] + 10 = 10 + 10 = 20! (Wait, you just reused item 1 twice!)
    • At w = 6: dp[6] = dp[4] + 10 = 30! (You used item 1 three times!)

    Because you updated smaller weights first, larger weights read the already updated values from the current item. That turns it into Unbounded Knapsack (infinite items)!

    What happens if you iterate BACKWARD (w = W down to weight[i])?

    • At w = 6: reads dp[4] (which is still 0 from the previous item!). dp[6] = 0 + 10 = 10.
    • At w = 4: reads dp[2] (which is still 0!). dp[4] = 0 + 10 = 10.
    • At w = 2: reads dp[0] (which is 0!). dp[2] = 0 + 10 = 10.

    By sweeping backwards, whenever you query w - weight[i], that smaller index has not yet been touched for the current item. It still holds the pristine value from item i-1!


    Production Python 3.12 Implementation

    def knapsack_01(weights: list[int], values: list[int], capacity: int) -> int:
        """Solves 0/1 Knapsack with O(W) auxiliary memory."""
        dp = [0] * (capacity + 1)
    
        for w_i, v_i in zip(weights, values):
            # Sweep backwards from capacity down to the item's weight
            for w in range(capacity, w_i - 1, -1):
                dp[w] = max(dp[w], dp[w - w_i] + v_i)
    
        return dp[capacity]
    

    Summary Rule of Thumb

    • 0/1 Knapsack (items used at most once) → Iterate Backward (W → weight).
    • Unbounded Knapsack / Coin Change (items can be reused infinitely) → Iterate Forward (weight → W).
    See less
    • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp

Sidebar

Ask A Question
  • Popular
  • Answers
  • Queryiest

    What is a database?

    • 3 Answers
  • Anonymous

    How to rotate an array in-place with O(1) space and ...

    • 3 Answers
  • hannah

    What steps can businesses take to identify the most valuable ...

    • 2 Answers
  • Vikram
    aarav0 added an answer Direct Technical Solution: Unlike IVFFlat (which partitions vector spaces with… September 11, 2026 at 9:57 pm
  • Abhishek
    Abhishek added an answer Direct Technical Solution: In C++20, range view adaptors (like std::views::filter,… September 11, 2026 at 9:57 pm
  • Sneha Patel
    Anonymous added an answer Direct Technical Solution: torch.cuda.empty_cache() releases only cached (unallocated) blocks back… September 11, 2026 at 9:57 pm

Top Members

Queryiest

Queryiest

  • 201 Questions
  • 295 Points
Enlightened
Anonymous

Anonymous

  • 11 Questions
  • 42 Points
Begginer
paperubofficial

paperubofficial

  • 0 Questions
  • 22 Points
Begginer

Trending Tags

ai asp.net aws basics aws certification aws console aws free tier aws login aws scenario-based questions c++ career cyber security cyber security interview git java javascript jobs jquery net core net core interview questions sql

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • DSA Problems
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • New Questions
  • Trending Questions
  • Must read Questions
  • Hot Questions

Footer

About Us

  • Meet The Team
  • Blog
  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy
  • Disclaimer
  • Terms & Conditions

Help

  • Knowledge Base
  • Support

Follow

© 2023-25 RTSALL. All Rights Reserved