LeetCode 1613: Find the Missing IDs

Database

Problem Description

Explanation:

Given an array of distinct integers representing the IDs of workers, where each worker's ID is between 0 and n-1 inclusive, with one ID missing, we need to find and return the missing ID.

To solve this problem efficiently, we can use the XOR operation. Since XOR of a number with itself is 0, if we XOR all the given IDs and then XOR the result with all the IDs from 0 to n, the missing ID will be left in the final result.

: :

Solutions

public int missingID(int[] ids) {
    int missing = ids.length;
    for (int i = 0; i < ids.length; i++) {
        missing = missing ^ i ^ ids[i];
    }
    return missing;
}

Loading editor...