BudiBadu Logo

Missing Seat Number

Array Easy 8 views
Like12

Imagine a theater where seats are tagged 0 to n. Guests file in with tickets in random order, but one chair remains vacant. Your task in Missing Seat Number is to spot exactly which number is absent from the scanned list. Exactly one label from the complete range is missing.

The "secret sauce" is Summation Math. A fast way is to calculate the "expected" sum of the full range $0..n$ using $n(n+1)/2$, then subtract the sum of numbers you actually have. The difference is your missing seat! This approach is incredibly efficient, running in linear O(n) time with minimal memory. You should handle cases where the missing seat is 0, the final seat n, or any number in between. This puzzle celebrates careful observation and reconciling partial evidence into a complete picture for the theater staff!

Keep the algorithm focused on one clear invariant and update path so correctness is easy to verify from left to right. This reduces accidental branching errors and helps ensure the final output stays consistent with the problem contract across random and adversarial test shapes.

Examples

Example 1
Input
nums = [3,0,1]
Output
2
Explanation

Seats 0 through 3 exist, and 2 is the missing label.

Example 2
Input
nums = [0,1]
Output
2
Explanation

The full range is 0, 1, 2; the last seat is missing.

Example 3
Input
nums = [9,6,4,2,3,5,7,0,1]
Output
8
Explanation

Among seats 0 through 9, the label 8 never appears.

Algorithm Flow

Recommendation Algorithm Flow for Missing Seat Number - Budibadu
Recommendation Algorithm Flow for Missing Seat Number - Budibadu

Best Answers

java
class Solution {
    public int missing_number(Object nums) {
        if (nums instanceof int[]) {
            int[] arr = (int[]) nums;
            int n = arr.length;
            int expected = n * (n + 1) / 2;
            int sum = 0;
            for(int x : arr) sum += x;
            return expected - sum;
        } else if (nums instanceof java.util.List) {
            java.util.List<?> list = (java.util.List<?>) nums;
            int n = list.size();
            int expected = n * (n + 1) / 2;
            int sum = 0;
            for(Object x : list) sum += (Integer)x;
            return expected - sum;
        }
        return 0;
    }
}