O(n) time 7 line code in Java

  • 4

    Simple math : summation of first n natural numbers are n*(n+1)/2.

    public class Solution {
        public int missingNumber(int[] nums) {
            int n = nums.length;
            int expectedSum = n*(n+1)/2;
            int actualSum = 0;
            for(int i=0; i<n; i++){
                actualSum+= nums[i];
            return (expectedSum-actualSum);

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.