Given a list of integers from 1 to n with exactly one number missing, find and return the missing number. The parameter n represents the total count of numbers in the complete sequence. Use the mathematical sum formula for optimal O(n) time complexity and O(1) space complexity: sum of 1 to n = n*(n+1)/2.

Examples:

Input: nums = [1, 2, 4, 5], n = 5 Output: 3 Explanation: The sequence should be 1 to 5, but 3 is missing. Using formula: expected sum = 5*6/2 = 15, actual sum = 12, missing = 3 Input: nums = [2, 3, 4, 5, 6, 7, 8, 9, 10], n = 10 Output: 1 Explanation: The sequence should be 1 to 10, but 1 is missing. Expected sum = 10*11/2 = 55, actual sum = 54, missing = 1 Input: nums = [1, 2, 3, 4, 5, 6, 7, 8, 9], n = 10 Output: 10 Explanation: The last number in the sequence is missing
Apex Code Editor

Welcome to Lightning Challenge!

Create an Account

Sign up to track your progress, earn points, and compete with others. Your solutions will be saved automatically.

Create account

How It Works

  • • Write your solution in the code editor
  • • Connect your Salesforce org to test
  • • Submit to check if your solution passes
  • • Use hints if you get stuck

Contest Alert

🏆 #CodeEveryDay Feb 2026

Contest runs February 1 - 28. Complete challenges to climb the leaderboard!

Points are calculated for challenges completed during the contest period.