educative.io

Educative

What if we have ZERO

This solution would give exception
Exception in thread "main" java.lang.ArithmeticException: / by zero

For the following test data
nums: [2, 5, 0, 10]
target = 0

That solution doesn’t complete all test cases.

I noticed the same problem in the provided solution. It would be totally reasonable if the problem statement said 0s would not appear in the input but it didn’t. And the solution to use the sliding window + two pointer pattern would be a lot more complex when dealing with 0s. This is why in my solution I just used a simple brute force approach that did 3 nested iterations, also because asymptotically, it has the same performance characteristics as the solution with the sliding window and two pointers, while gracefully handling zero inputs, and being conceptually simpler.

Related topic

The problem did say that there will not be any zero in the input:

Given an array with positive numbers and a target number

It is always a good idea to ask questions and clear things from the interviewer, for example, if someone doesn’t know if zero is included in positive numbers or not.

3 Likes