Review the answer
Read · 1 of 4
Problem first, then code
Read the problem's rules before the code: what's allowed in the input, and what exactly must come out. Then run the checklist against the code.
AI solutions to famous problems are usually close to right. The bugs hide in the details the problem statement was careful about.
Read this lesson as text
Three solutions an AI might give. Which ones would you ship?
Problem first, then code
Read the problem's rules before the code: what's allowed in the input, and what exactly must come out. Then run the checklist against the code.
AI solutions to famous problems are usually close to right. The bugs hide in the details the problem statement was careful about.
Two Sum
n, target = map(int, input().split())
nums = list(map(int, input().split()))
seen = set(nums)
print("YES" if any(target - x in seen for x in nums) else "NO")Print YES if numbers at two different positions add up to the target. Would you ship this?
- Yes, it's correct
- No: a number can pair with itself, so
5with target10says YES - No: it's too slow for 100,000 numbers
Show the answer
No: a number can pair with itself, so 5 with target 10 says YES. All numbers go into the set up front, so 10 - 5 finds the same 5. Check against numbers seen *before* the current one instead.
Valid brackets
s = input()
stack = []
pairs = {")": "(", "]": "[", "}": "{"}
for c in s:
if c in "([{":
stack.append(c)
elif stack.pop() != pairs[c]:
print("NO")
break
else:
print("YES" if not stack else "NO")Print YES if every bracket is closed in the right order. Would you ship this?
- Yes, it's correct
- No: it crashes when a closing bracket comes first, like
)( - No: it says YES for
(]
Show the answer
No: it crashes when a closing bracket comes first, like )(. With )(, the stack is empty when ) arrives and pop() crashes. Check not stack before popping.
Best stretch
n = int(input())
nums = list(map(int, input().split()))
best = cur = nums[0]
for x in nums[1:]:
cur = max(x, cur + x)
best = max(best, cur)
print(best)Print the biggest sum of a run of neighbouring numbers (at least one number). Would you ship this?
- Yes, it's correct
- No: it's wrong when every number is negative
- No: it's wrong for a single number
Show the answer
Yes, it's correct. This is Kadane's algorithm, and it starts from the first number rather than 0, so all-negative and single-number inputs work. Checked against trying every run.