Bird
Raised Fist0

Which line contains a subtle bug that causes incorrect results when the input has consecutive equal elements?

medium🔍🐞 Bug Finding Q7 of Q15
Greedy Algorithms - Wiggle Subsequence
Examine the following Python code snippet for the wiggle subsequence problem. Which line contains a subtle bug that causes incorrect results when the input has consecutive equal elements? ```python def wiggleMaxLength(nums): if not nums: return 0 count = 1 last_diff = 0 for i in range(1, len(nums)): diff = nums[i] - nums[i-1] if (diff > 0 and last_diff <= 0): count += 1 last_diff = diff elif (diff < 0 and last_diff >= 0): count += 1 last_diff = diff return count ```
ANo handling for diff == 0 case
BLine with 'elif (diff < 0 and last_diff >= 0):' condition
CInitialization of 'last_diff = 0'
DLine with 'if (diff > 0 and last_diff <= 0):' condition
Step-by-Step Solution
Solution:
  1. Step 1: Understand the code

    The code updates count when the difference changes sign.
  2. Step 2: Identify the bug

    When diff == 0 (equal consecutive elements), it neither updates count nor last_diff, but also doesn't skip properly.
  3. Step 3: Consequence

    Failing to handle diff == 0 can cause incorrect counting or missed wiggles.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Check input with equal elements [OK]
Quick Trick: Check for zero difference handling in conditions [OK]
Common Mistakes:
MISTAKES
  • Ignoring zero difference leads to incorrect wiggle count
  • Assuming last_diff initialization fixes all cases
  • Misplacing conditions for sign changes
Trap Explanation:
PITFALL
  • Ignoring zero difference looks like correct logic but misses edge cases
Interviewer Note:
CONTEXT
  • Tests ability to spot subtle bugs in sign-based logic
Master "Wiggle Subsequence" 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