Bird
Raised Fist0

Consider the following buggy code for partitioning labels. Which line contains the subtle bug that can cause incorrect partitions?

medium🐞 Bug Identification Q14 of Q15
Greedy Algorithms - Partition Labels
Consider the following buggy code for partitioning labels. Which line contains the subtle bug that can cause incorrect partitions?
def partitionLabels(s):
    last = [0] * 26
    for i, c in enumerate(s):
        last[ord(c) - ord('a')] = i
    res = []
    start = 0
    end = 0
    for i, c in enumerate(s):
        end = last[ord(c) - ord('a')]  # Bug here: missing max()
        if i == end:
            res.append(end - start + 1)
            start = i + 1
    return res
ALine 3: Updating last occurrence map
BLine 13: Calculating partition size with end - start + 1
CLine 8: Initializing end to 0
DLine 11: Updating end without taking max
Step-by-Step Solution
Solution:
  1. Step 1: Understand role of end variable

    End must track the furthest last occurrence of any character seen so far to avoid premature partitioning.
  2. Step 2: Identify bug in updating end

    Assigning end directly to last occurrence of current character without max() loses track of previous furthest last occurrence, causing incorrect partitions.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Missing max() causes partitions to cut too early [OK]
Quick Trick: Always update end = max(end, last[c]) [OK]
Common Mistakes:
MISTAKES
  • Forgetting max() when updating partition end
  • Off-by-one errors in partition size calculation
  • Not precomputing last occurrences
Trap Explanation:
PITFALL
  • Assigning end directly looks simpler but breaks correctness on overlapping characters.
Interviewer Note:
CONTEXT
  • Tests ability to spot subtle greedy update bugs that break correctness.
Master "Partition Labels" in Greedy Algorithms

3 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Greedy Algorithms Quizzes