Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Dynamic Programming/Bitmask DP

Technique

Sum over Subsets (SOS) DP

For every mask compute an aggregate over all its submasks (or supermasks) in O(B * 2^B) by prefix-summing one bit dimension at a time.

Learn firstBitmask DPPrefix Sum
0%
mastery
0/4 solved
Practise nextLove-Hate
IdeaPracticePitfalls

Recognise it

The signal

for each x count y with y & x == y (or x & y == 0)

  1. 1Brute force

    Enumerate submasks of every mask: O(3^B).

  2. 2The observation

    Submask enumeration: each mask is a B-dimensional 0/1 coordinate, so prefix sums per dimension suffice.

  3. 3Why it works

    After processing bits 0..i, F[mask] sums over submasks that differ from mask only in bits 0..i.

Reach for it when

  • +values up to 220
  • +AND/OR convolutions

Not when

  • ×B > ~23 (memory/time)
  • ×aggregation is not associative/commutative

Practice

Next

Love-Hate

0/4 solved
  • SOS Bit ProblemCSESMedium
  • Love-HateCodeforces2400
  • Compatible NumbersCodeforces2200
  • And Subset CountCSESHard

Pitfalls

Misconceptions

  • !looping masks outside bits (must be bits outside)
Go deeper2 combinations · resources

Combinations

  • Sum over Subsets (SOS) DP+Bit Tricks & Bitmasking

    for each x count y with x | y == x, x & y == y, or x & y == 0

    Sum over Subsets (SOS) DP:
    aggregates over submasks for all masks
    Bit Tricks & Bitmasking:
    mask representation

    SOS Bit ProblemCompatible Numbers

  • Randomised Sampling Arguments+Sum over Subsets (SOS) DP

    find the largest set of items liked by at least half the people, with m <= 60 items but <= 15 liked per person

    Randomised Sampling Arguments:
    a random friend belongs to the optimal half-liked set with probability >= 1/2
    Sum over Subsets (SOS) DP:
    for that friend's <= 15 liked currencies, count supersets over masks

    Love-Hate

Resources

  • DP lecture notesErrichto · video
  • AtCoder Educational DP ContestAtCoder · sheet
  • Introduction to DPUSACO Guide · course
  • Dynamic Programming PatternsLeetCode discuss · article
  • Dynamic Programming playlistAditya Verma · video
  • Bitmask DPUSACO Guide · course
  • Digit DPCodeforces · blog
TodayReviewPatternsProblems