00:00

Problem Statement

Input/Output Examples

Visual Explanation

Because exactly one number is missing, the difference between the expected and the actual sum can only be that number. Using a long keeps the expected sum from overflowing for large n.

Approaches

Both approaches use constant extra memory. One uses arithmetic; the other uses XOR, which cannot overflow.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the size of the range. Both approaches read the array once and keep one or two numbers.

Interview Tips and Recommended Approach

  • Watch for overflow. n * (n + 1) / 2 in int overflows long before memory runs out.
  • Explain XOR cancellation; it is a common follow-up question.
  • Check the assumptions. These methods need exactly one missing number and no duplicates.
  • Know the related problems: two missing numbers, or the first missing positive in an arbitrary array.

Recommended Approach: Sum Formula

Why: it is a one-line idea with constant memory, easy to prove correct, and the long removes the overflow risk.