BeginnerMath for DSAUsed everywhere

Powers of two you should know by heart

2¹⁰ ≈ 1 thousand, 2²⁰ ≈ 1 million, 2³⁰ ≈ 1 billion, 2³¹ − 1 is the int limit. They turn into quick decisions.

The idea

2ⁿ doubles every step, so it explodes: 2¹⁰ = 1,024 ≈ 10³. Every 10 more doublings multiply by about a thousand. That gives instant estimates: 2²⁰ ≈ 10⁶, 2³⁰ ≈ 10⁹.

Use it both ways. A set of n items has 2ⁿ , so trying all of them is fine for n ≤ 20 and hopeless for n = 40. And a 32-bit signed int holds up to 2³¹ − 1 = 2,147,483,647.

Worked example

Can I try every subset?

  1. n = 15 → 2¹⁵ ≈ 32,000 subsets: easily fine.
  2. n = 20 → 2²⁰ ≈ 1 million: fine.
  3. n = 40 → 2⁴⁰ ≈ 10¹²: far too slow. Think DP or meet-in-the-middle.

Pseudocode

The steps in plain words. ← means “set to”; indentation shows what's inside what.

for mask from 0 to 2ⁿ − 1:
subset ← every nums[i] whose bit i is set in mask
record subset
2¹⁰ ≈ 10³ 2²⁰ ≈ 10⁶ 2³⁰ ≈ 10⁹

See it run

The worked example, step by step, beside the Python. The highlighted line is the one running.

Step-by-step

nums = [a, b, c]

nums

0a
1b
2c

Solution · Pythonline 4

def all_subsets(nums):
n = len(nums)
result = []
for mask in range(1 << n): # 0 .. 2^n - 1
result.append([nums[i] for i in range(n) if mask >> i & 1])
return result

Step 1 of 10· line 4

n items have 2ⁿ subsets: 1 << 3 = 8. Count from 0 to 7: bit i of the count says whether item i is in.

Generating all subsets is O(n · 2ⁿ).

How to spot it

  • Constraints like n ≤ 20 (subsets are fine) or values up to 2³¹ − 1 (watch for ).

Common mistakes

  • Confusing 2ⁿ with n²: for n = 30 that's a billion versus 900.
  • Summing two ints near 2³¹ in Java/C++ without a long.

Where it comes up

Go further