Chapter 12
Greedy Algorithms & Bit Manipulation
2 topics · 2 sections · beginner-friendly study notes · Updated
Greedy algorithms make the locally best choice at each step and are correct when the greedy-choice property and optimal substructure hold (activity selection, intervals, Huffman).
Bit manipulation uses bitwise operators for O(1) tricks such as XOR to find unique elements and masks to represent subsets.
Greedy gives simple optimal O(n log n) solutions to scheduling problems; bit tricks give O(1) space answers and compact states in DP.
CPU/meeting scheduling, Huffman compression, MST (Kruskal/Prim), flags and permissions, hashing, cryptography, bitmask DP.
Activity Selection & Intervals
Activity selection: given n activities with start and finish times, choose the maximum number of mutually non-overlapping ones. Greedy: sort by finish time and repeatedly take the next activity whose start >= last chosen finish. Time O(n log n), optimal by an exchange argument.
In short: Always pick the activity that ends earliest so you leave the most room for others.
Think about it
Interval and scheduling greedy problems are interview staples; GATE asks which greedy strategy is optimal.
Why earliest finish (not earliest start or shortest duration): exchange argument - any optimal solution can have its first activity replaced by the earliest-finishing one without causing conflicts, then recurse on the rest.
Earliest start and shortest duration have counter-examples.
Merge intervals: sort by start, extend the current interval if next.
start <= cur.
end, else push: O(n log n).
Insert interval: linear scan.
Minimum removals to make intervals non-overlapping = n - (max non-overlapping set), via the same earliest-finish greedy.
Minimum arrows to burst balloons = max set of non-overlapping intervals (greedy by end).
Meeting rooms II / minimum platforms: sort starts and ends separately and sweep, or use a min-heap of end times: O(n log n).
Weighted interval scheduling (values on activities) is NOT greedy - use DP with binary search, O(n log n).
Job sequencing with deadlines: sort by profit descending, place each job in the latest free slot before its deadline (use DSU for near-linear).
Fractional knapsack: sort by value/weight ratio.
Huffman coding: repeatedly merge the two least-frequency nodes with a min-heap: O(n log n), produces optimal prefix code.
Kruskal (sort edges + union-find) and Prim are greedy and correct due to the cut property.
Dijkstra is greedy with non-negative weights.
Counter-example for greedy: coin system {1,3,4}, amount 6.
Check closed vs half-open intervals: [1,2] and [2,3] touch - decide whether touching counts as overlap and use >= or > consistently.
Key points
- Greedy-choice property: A locally optimal choice can be extended to a global optimum.
- Exchange argument: Proof by swapping optimal solution elements for the greedy choice without loss.
- Sweep line: Process sorted events (starts/ends) in order.
- Weighted interval scheduling: dp[i] =
max(dp[i-1], w[i] + dp[p(i)]) wherep(i)is the last compatible job (binary search). - Huffman: n symbols need n-1 merges; no code is a prefix of another.
Read more
Example
CodeGreedy classics:
import heapq
def max_activities(acts): # acts = [(start, finish)]
acts.sort(key=lambda a: a[1]) # earliest finish first
cnt, last_end = 0, float('-inf')
for s, f in acts:
if s >= last_end:
cnt += 1; last_end = f
return cnt
def merge_intervals(iv):
iv.sort()
out = [iv[0]] if iv else []
for s, e in iv[1:]:
if s <= out[-1][1]: out[-1][1] = max(out[-1][1], e)
else: out.append([s, e])
return out
def min_meeting_rooms(iv): # = minimum platforms
iv.sort(); h = []
for s, e in iv:
if h and h[0] <= s: heapq.heapreplace(h, e)
else: heapq.heappush(h, e)
return len(h)
def fractional_knapsack(items, W): # items = [(value, weight)]
items.sort(key=lambda t: t[0] / t[1], reverse=True)
total = 0.0
for v, w in items:
take = min(w, W)
total += v * take / w; W -= take
if W == 0: break
return total
def huffman_cost(freqs):
heapq.heapify(freqs); cost = 0
while len(freqs) > 1:
a, b = heapq.heappop(freqs), heapq.heappop(freqs)
cost += a + b; heapq.heappush(freqs, a + b)
return costBit Manipulation & XOR Tricks
Bitwise operators act on binary representations: AND (&), OR (|), XOR (^), NOT (~), left shift (<<, multiply by 2^k) and right shift (>>, floor divide by 2^k). XOR satisfies a ^ a = 0, a ^ 0 = a, commutative and associative, which makes it ideal for cancelling pairs.
In short: Work directly on the 0/1 bits of numbers; XOR cancels equal values.
Think about it
O(1)-space tricks and bitmask subset states are favoured in interviews; GATE tests operator results and identities.
Core idioms (bit i counted from 0): test (x >> i) & 1; set x | (1 << i); clear x & ~(1 << i); toggle x ^ (1 << i).
x & (x-1) clears the lowest set bit (loop count = popcount, Brian Kernighan; also power-of-two test: x > 0 and x & (x-1) == 0).
x & -x isolates the lowest set bit (two's complement: -x = ~x + 1).
Even/odd: x & 1.
Multiply/divide by 2: x << 1, x >> 1.
Mask of k ones: (1 << k) - 1.
XOR applications: single number where every other appears twice: XOR all, O(n) time O(1) space; two single numbers: XOR all gives a^b, take the lowest set bit as a splitting mask, XOR within the two groups; missing number in 0..
n: XOR indices and values (or n(n+1)/2 - sum); swap without temp: a ^= b; b ^= a; a ^= b (fails if both refer to the same memory); find the duplicate with a given parity; gray code g = n ^ (n >> 1).
Subsets of n items: for mask in range(1 << n): item i is in the subset if mask >> i & 1 - 2^n subsets, enabling bitmask DP (TSP in O(n^2 2^n)).
Iterate all submasks of m: sub = (sub - 1) & m.
Counting set bits of 0..
n: dp[i] = dp[i >> 1] + (i & 1).
Reverse bits, hamming distance (popcount(a ^ b)), and total Hamming distance (per-bit count of ones times zeros).
Pitfalls: operator precedence (== binds tighter than & in C/Java: write (x & 1) == 1), arithmetic vs logical right shift for negatives (Python ints are unbounded and >> is arithmetic; Java has >>>), overflow in fixed-width languages when shifting into the sign bit, ~x = -x - 1 in Python so mask with & 0xFFFFFFFF for 32-bit unsigned semantics.
XOR of 1..
n follows a cycle of 4: n%4 = 0 -> n, 1 -> 1, 2 -> n+1, 3 -> 0.
Key points
- Mask: Integer whose bits select or clear parts of another integer.
- Popcount: Number of set bits (Hamming weight).
- Two's complement: -x = ~x + 1; used to represent negative integers.
- Bitmask DP: Use an integer as a subset state.
- a ^ a = 0, a ^ 0 = a; XOR of all elements where pairs cancel leaves the single number.
- x & (x-1) clears the lowest set bit; x & -x extracts it; power of two iff x and (x-1) share no bits.
Read more
Example
CodeBit tricks and XOR identities:
def get_bit(x, i): return (x >> i) & 1
def set_bit(x, i): return x | (1 << i)
def clear_bit(x, i): return x & ~(1 << i)
def toggle_bit(x, i): return x ^ (1 << i)
def popcount(x): # Kernighan, O(set bits)
c = 0
while x:
x &= x - 1; c += 1
return c
def is_power_of_two(x): return x > 0 and x & (x - 1) == 0
def single_number(nums): # every other appears twice
r = 0
for x in nums: r ^= x
return r
def two_single_numbers(nums):
xor = 0
for x in nums: xor ^= x # = a ^ b
low = xor & -xor # a bit where a and b differ
a = b = 0
for x in nums:
if x & low: a ^= x
else: b ^= x
return a, b
def missing_number(nums): # 0..n with one missing
r = len(nums)
for i, x in enumerate(nums): r ^= i ^ x
return r
def all_subsets(items):
n = len(items)
return [[items[i] for i in range(n) if mask >> i & 1]
for mask in range(1 << n)]
def count_bits_upto(n): # popcount for 0..n in O(n)
dp = [0] * (n + 1)
for i in range(1, n + 1): dp[i] = dp[i >> 1] + (i & 1)
return dp
def xor_upto(n): # XOR of 1..n in O(1)
return [n, 1, n + 1, 0][n % 4]Solved examples
Activities (start, finish): (1,4), (3,5), (0,6), (5,7), (3,9), (5,9), (6,10), (8,11). Maximum compatible set?
Count
Formula Applied:—Approach note: Compare start with the last chosen FINISH.
Array [4, 1, 2, 1, 2] and [1, 2, 1, 3, 2, 5]: find the unique element(s).
Unique numbers
Formula Applied:—Approach note: The split bit exists because a != b.
Why does greedy fail for weighted activity selection with (start, end, weight): (0,10,100), (0,4,30), (5,10,30)?
Counter-example
Formula Applied:—Approach note: Always hunt for a small counter-example before trusting a greedy rule.
Activity selection: intervals [1,4], [3,5], [0,6], [5,7], [8,9], [5,9]. How many activities does the classic earliest-finish greedy pick?
Count
Formula Applied:—Approach note: Always take the compatible job that finishes earliest.
Real-world applications
Using Greedy Algorithms & Bit Manipulation in real projects
CPU/meeting scheduling, Huffman compression, MST (Kruskal/Prim), flags and permissions, hashing, cryptography, bitmask DP.
Common mistakes
❌ Myth: Greedy always gives the optimal answer when it looks reasonable.
Why this is wrong: Optimality requires the greedy-choice property; many problems (0/1 knapsack, arbitrary coin change, weighted intervals) lack it.
✅ Verified Truth: Prove with an exchange argument or find a counter-example; otherwise use DP.
⚠️ Exam Tip: Coins {1,3,4}, amount 6 is the standard counter-example.
❌ Myth: Sorting activities by start time (or duration) also yields the maximum set.
Why this is wrong: A long early activity can block many later ones.
✅ Verified Truth: Only earliest FINISH time is optimal.
⚠️ Exam Tip: Sort key matters: finish time for selection, start time for merging.
❌ Myth: x & 1 == 1 is a safe odd test in every language.
Why this is wrong: In C/Java == has higher precedence than &, giving x & (1 == 1).
✅ Verified Truth: Write (x & 1) == 1 with parentheses.
⚠️ Exam Tip: GATE operator-precedence trap.
Revision notes
Greedy algorithms make the locally best choice at each step and are correct when the greedy-choice property and optimal substructure hold (activity selection, intervals, Huffman). Bit manipulation uses bitwise operators for O(1) tricks such as XOR to find unique elements and masks to represent subsets.
High-Yield Quick Revision Points
- Greedy needs greedy-choice + optimal substructure; prove by exchange or find counter-example
- Activity selection: sort by finish, take start >= last finish; merge intervals: sort by start
- Weighted intervals, 0/1 knapsack, arbitrary coins: DP not greedy
- x&(x-1) clears lowest set bit; x&-x isolates it; power of two: x>0 and x&(x-1)==0
- XOR: a^a=0, a^0=a; single number, missing number; subsets via masks 0..2^n-1
Practice questions
Activity selection greedy sorts by:
x & (x - 1) does what?
Time complexity of finding a single number among pairs using XOR:
Which problem is solved optimally by greedy by value/weight ratio?
Number of subsets enumerated by bitmask loop for n items:
Number of merges Huffman coding performs for n symbols: