Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion q2.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,16 @@ def compressed_stack_length(lst):
0
"""
# TODO: Implement your solution here
pass
count = 0
for i in range(len(lst)):
if lst[i] == lst[i-1]:
count = count - 1
else:
count = count + 1
if count < 0:
return 0
else:
return count
Comment on lines +68 to +77

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

The current implementation has a critical logic flaw and does not correctly model the stack-like behavior described in the problem.

  1. Incorrect Comparison: The code compares lst[i] with lst[i-1], which is the previous element in the original input list. The requirement is to compare with the "most recent active number", which is the top of the conceptual stack.
  2. Edge Case i=0: When i=0, lst[i-1] accesses the last element of the list (lst[-1]), which is incorrect. The first element should always be added to the stack as there's nothing to cancel it with.

A simple counter is insufficient to solve this problem because you need to know what the last active number was. A list used as a stack is the ideal data structure for this.

Here is a corrected implementation that uses a stack to accurately track the active numbers:

    stack = []
    for num in lst:
        if stack and stack[-1] == num:
            stack.pop()
        else:
            stack.append(num)
    return len(stack)



if __name__ == "__main__":
Expand Down