{"id":6141,"date":"2025-05-29T17:40:49","date_gmt":"2025-05-29T12:10:49","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=6141"},"modified":"2025-07-22T21:56:09","modified_gmt":"2025-07-22T16:26:09","slug":"missing-number","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/missing-number\/","title":{"rendered":"Missing Number"},"content":{"rendered":"\n<!-- Prism.js CSS and JS -->\n<link href=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/themes\/prism-tomorrow.css\" rel=\"stylesheet\" \/>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/prism.js\"><\/script>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/plugins\/autoloader\/prism-autoloader.min.js\"><\/script>\n\n<style>\n.wp_blog_code-tabs-container {\n    font-family: \"Segoe UI\", sans-serif !important;\n    max-width: 900px !important;\n    margin: 2rem auto !important;\n    border: 1px solid #ddd !important;\n    border-radius: 8px !important;\n    overflow: hidden !important;\n    background-color: white !important;\n}\n\n.wp_blog_code-tabs-header {\n    background: #f7f7f7 !important;\n    display: flex !important;\n    border-bottom: 1px solid #ddd !important;\n}\n\n.wp_blog_code-tab-button {\n    flex: 1 !important;\n    padding: 10px 15px !important;\n    border: none !important;\n    background: transparent !important;\n    cursor: pointer !important;\n    font-weight: bold !important;\n    transition: background 0.2s !important;\n    color: #242B33 !important;\n}\n\n.wp_blog_code-tab-button.active {\n    background: white !important;\n    border-bottom: 3px solid #0073aa !important;\n}\n\n.wp_blog_code-tab-content {\n    display: none !important;\n    padding: 20px !important;\n    background: #242B33 !important;\n}\n\n.wp_blog_code-tab-content > pre {\n    background: #242B33 !important;\n}\n\n.wp_blog_code-tab-content.active {\n    display: block !important;\n}\n\n.wp_blog_code-tab-content pre {\n    margin: 0 !important;\n    overflow-x: auto !important;\n}\n\n.wp_blog_explanation {\n    max-width: 900px !important;\n    margin: 2rem auto !important;\n    font-family: \"Segoe UI\", sans-serif !important;\n    line-height: 1.6 !important;\n    background: white !important;\n    color: black !important;\n    padding: 1rem !important;\n    border-radius: 8px !important;\n}\n\n.wp_blog_explanation h2 {\n    color: #0073aa !important;\n    font-size: 1.5rem !important;\n    margin-bottom: 0.5rem !important;\n}\n\n.wp_blog_explanation code {\n    background: #f1f1f1 !important;\n    padding: 2px 6px !important;\n    border-radius: 4px !important;\n    font-family: monospace !important;\n}\n\n.wp_blog_explanation h1,\n.wp_blog_explanation h2,\n.wp_blog_explanation h3,\n.wp_blog_explanation h4,\n.wp_blog_explanation h5,\n.wp_blog_explanation h6,\n.wp_blog_explanation p {\n    margin-top: 10px !important;\n    margin-bottom: 10px !important;\n}\n<\/style>\n\n<!-- \u2705 START: Blog Explanation -->\n<div class=\"wp_blog_explanation\">\n    <h2>Problem<\/h2>\n    <p>Given an array <code>nums<\/code> containing <code>n<\/code> distinct numbers in the range <code>[0, n]<\/code>, return the only number in the range that is missing from the array.<\/p>\n\n    <div>Example 1:<\/div>\n    <pre>\nInput: nums = [3,0,1]\nOutput: 2\nExplanation:\nn = 3 since there are 3 numbers, so all numbers are in the range [0,3]. \n2 is the missing number in the range since it does not appear in nums.\n    <\/pre>\n\n    <div>Example 2:<\/div>\n    <pre>\nInput: nums = [0,1]\nOutput: 2\nExplanation:\nn = 2 since there are 2 numbers, so all numbers are in the range [0,2]. \n2 is the missing number in the range since it does not appear in nums.\n    <\/pre>\n\n    <div>Example 3:<\/div>\n    <pre>\nInput: nums = [9,6,4,2,3,5,7,0,1]\nOutput: 8\nExplanation:\nn = 9 since there are 9 numbers, so all numbers are in the range [0,9]. \n8 is the missing number in the range since it does not appear in nums.\n    <\/pre>\n\n    <div>Constraints:<\/div>\n    <ul>\n      <li>n == nums.length<\/li>\n      <li>1 &lt;= n &lt;= 10<sup>4<\/sup><\/li>\n      <li>0 &lt;= nums[i] &lt;= n<\/li>\n      <li>All the numbers of nums are unique<\/li>\n    <\/ul>\n\n  \n        <h2>Approach 1 (Brute-force with sorting and comparison)<\/h2>\n        <ol>\n          <li>Sort the array.<\/li>\n          <li>Loop from index <code>1<\/code> to <code>n - 1<\/code>:<\/li>\n          <ul>\n            <li>If <code>nums[i] != nums[i-1] + 1<\/code>, return <code>nums[i-1] + 1<\/code> as the missing number.<\/li>\n          <\/ul>\n          <li>If no such mismatch is found:<\/li>\n          <ul>\n            <li>If <code>nums[0] != 0<\/code>, return <code>0<\/code>.<\/li>\n            <li>Else return <code>n<\/code>.<\/li>\n          <\/ul>\n        <\/ol>\n    \n        <h2>Dry Run<\/h2>\n        <p><strong>Input:<\/strong> <code>nums = [4, 2, 1, 0, 5]<\/code><\/p>\n        <p><strong>After Sorting:<\/strong> <code>nums = [0, 1, 2, 4, 5]<\/code><\/p>\n    \n        <div class=\"check\">Check:<\/div>\n        <div class=\"check\"><span>i = 1<\/span> \u2192 1 == 0 + 1 <span class=\"success\"><\/span><\/div>\n        <div class=\"check\"><span>i = 2<\/span> \u2192 2 == 1 + 1 <span class=\"success\"><\/span><\/div>\n        <div class=\"check\"><span>i = 3<\/span> \u2192 4 != 2 + 1 <span class=\"fail\"><\/span> \u2192 return <strong>3<\/strong><\/div>\n    \n        <p><strong>Output:<\/strong> <code>3<\/code><\/p>\n\n    \n            <h2>Time and Space Complexity<\/h2>\n            <p><strong>Time Complexity:<\/strong> O(n log n)<br \/>\n                Due to sorting the array.\n            <\/p>\n            <p><strong>Space Complexity:<\/strong> O(1)<br \/>\n                Sorting is done in-place, and only a few variables are used.\n            <\/p>\n         \n    \n<\/div>\n<!-- \u2705 END: Blog Explanation -->\n\n<!-- \u2705 START: Code Tabs -->\n<div class=\"wp_blog_code-tabs-container\">\n    <div class=\"wp_blog_code-tabs-header\">\n      <button class=\"wp_blog_code-tab-button active\" data-lang=\"js\">JavaScript<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"cpp\">C++<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"c\">C<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"java\">Java<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"py\">Python<\/button>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content active\" data-lang=\"js\">\n      <pre><code class=\"language-javascript\">var missingNumber = function(nums) {\n      nums.sort((a, b) => a - b);\n  \n      if (nums[0] !== 0) return 0;\n  \n      for (let i = 1; i < nums.length; i++) {\n          if (nums[i] !== nums[i - 1] + 1) {\n              return nums[i - 1] + 1;\n          }\n      }\n  \n      return nums.length;\n  };\n      <\/code><\/pre>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content\" data-lang=\"cpp\">\n      <pre><code class=\"language-cpp\">#include &lt;algorithm&gt;\n  class Solution {\n  public:\n      int missingNumber(vector&lt;int&gt;& nums) {\n          sort(nums.begin(), nums.end());\n  \n          if (nums[0] != 0) return 0;\n  \n          for (int i = 1; i &lt; nums.size(); i++) {\n              if (nums[i] != nums[i - 1] + 1) {\n                  return nums[i - 1] + 1;\n              }\n          }\n  \n          return nums.size();\n      }\n  };\n      <\/code><\/pre>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content\" data-lang=\"c\">\n      <pre><code class=\"language-c\">#include &lt;stdlib.h&gt;\n  int compare(const void* a, const void* b) {\n      return (*(int*)a - *(int*)b);\n  }\n  \n  int missingNumber(int* nums, int numsSize) {\n      qsort(nums, numsSize, sizeof(int), compare);\n  \n      if (nums[0] != 0) return 0;\n  \n      for (int i = 1; i &lt; numsSize; i++) {\n          if (nums[i] != nums[i - 1] + 1) {\n              return nums[i - 1] + 1;\n          }\n      }\n  \n      return numsSize;\n  }\n      <\/code><\/pre>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content\" data-lang=\"java\">\n      <pre><code class=\"language-java\">import java.util.Arrays;\n  class Solution {\n      public int missingNumber(int[] nums) {\n          Arrays.sort(nums);\n  \n          if (nums[0] != 0) return 0;\n  \n          for (int i = 1; i &lt; nums.length; i++) {\n              if (nums[i] != nums[i - 1] + 1) {\n                  return nums[i - 1] + 1;\n              }\n          }\n  \n          return nums.length;\n      }\n  }\n      <\/code><\/pre>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content\" data-lang=\"py\">\n      <pre><code class=\"language-python\">class Solution:\n      def missingNumber(self, nums):\n          nums.sort()\n  \n          if nums[0] != 0:\n              return 0\n  \n          for i in range(1, len(nums)):\n              if nums[i] != nums[i - 1] + 1:\n                  return nums[i - 1] + 1\n  \n          return len(nums)\n      <\/code><\/pre>\n    <\/div>\n  <\/div>\n  \n<!-- \u2705 END: Code Tabs -->\n\n<div class=\"wp_blog_explanation\">\n    <h2>Approach (Optimal using Sum Formula)<\/h2>\n\n    <div>\n      <p>The sum of numbers from <code>0<\/code> to <code>n<\/code> is given by the formula:<\/p>\n      <pre>total_sum = (n \u00d7 (n + 1)) \/ 2<\/pre>\n      <p>Steps:<\/p>\n      <ol>\n        <li>Calculate <span class=\"highlight\">total_sum<\/span> using the formula above.<\/li>\n        <li>Calculate the <span class=\"highlight\">sum of all elements<\/span> in the input array.<\/li>\n        <li>The <span class=\"highlight\">missing number<\/span> is <code>total_sum - sum_of_array<\/code>.<\/li>\n      <\/ol>\n    <\/div>\n\n    <h2>Dry Run<\/h2>\n\n    <div>\n      <p><strong>Input:<\/strong> <code>nums = [3, 0, 1]<\/code><\/p>\n      <p><strong>n:<\/strong> 3 (length of the array)<\/p>\n      <p><strong>total_sum:<\/strong> 3 \u00d7 (3 + 1) \/ 2 = <code>6<\/code><\/p>\n      <p><strong>sum_of_array:<\/strong> 3 + 0 + 1 = <code>4<\/code><\/p>\n      <p><strong>missing_number:<\/strong> 6 - 4 = <code>2<\/code><\/p>\n    <\/div>\n\n    <p><strong>Output:<\/strong> <code>2<\/code><\/p>\n\n   \n        <h2>Time and Space Complexity<\/h2>\n        <p><strong>Time Complexity:<\/strong> O(n)<br \/>\n            We traverse the array once to compute the sum.\n        <\/p>\n        <p><strong>Space Complexity:<\/strong> O(1)<br \/>\n            Only a few variables are used, no extra space proportional to input size.\n        <\/p>\n     \n    \n<\/div>\n<div class=\"wp_blog_code-tabs-container\">\n    <div class=\"wp_blog_code-tabs-header\">\n      <button class=\"wp_blog_code-tab-button active\" data-lang=\"js\">JavaScript<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"cpp\">C++<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"c\">C<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"java\">Java<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"py\">Python<\/button>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content active\" data-lang=\"js\">\n      <pre><code class=\"language-javascript\">\n  var missingNumber = function(nums) {\n      let n = nums.length;\n      let total_sum = (n * (n + 1)) \/ 2;\n      let sum_of_array = 0;\n  \n      for (let num of nums) {\n          sum_of_array += num;\n      }\n  \n      return total_sum - sum_of_array;\n  };\n      <\/code><\/pre>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content\" data-lang=\"cpp\">\n      <pre><code class=\"language-cpp\">\n  class Solution {\n  public:\n      int missingNumber(vector&lt;int&gt;& nums) {\n          int n = nums.size();\n          int total_sum = n * (n + 1) \/ 2;\n          int sum_of_array = 0;\n  \n          for (int num : nums) {\n              sum_of_array += num;\n          }\n  \n          return total_sum - sum_of_array;\n      }\n  };\n      <\/code><\/pre>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content\" data-lang=\"c\">\n      <pre><code class=\"language-c\">\n  int missingNumber(int* nums, int numsSize) {\n      int total_sum = numsSize * (numsSize + 1) \/ 2;\n      int sum_of_array = 0;\n  \n      for (int i = 0; i < numsSize; i++) {\n          sum_of_array += nums[i];\n      }\n  \n      return total_sum - sum_of_array;\n  }\n      <\/code><\/pre>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content\" data-lang=\"java\">\n      <pre><code class=\"language-java\">\n  class Solution {\n      public int missingNumber(int[] nums) {\n          int n = nums.length;\n          int total_sum = n * (n + 1) \/ 2;\n          int sum_of_array = 0;\n  \n          for (int num : nums) {\n              sum_of_array += num;\n          }\n  \n          return total_sum - sum_of_array;\n      }\n  }\n      <\/code><\/pre>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content\" data-lang=\"py\">\n      <pre><code class=\"language-python\">\n  class Solution:\n      def missingNumber(self, nums):\n          n = len(nums)\n          total_sum = n * (n + 1) \/\/ 2\n          sum_of_array = sum(nums)\n          return total_sum - sum_of_array\n      <\/code><\/pre>\n    <\/div>\n  <\/div>\n  \n\n<!-- \u2705 JS Tab Switch Logic -->\n<script>\ndocument.addEventListener('DOMContentLoaded', function () {\n    const buttons = document.querySelectorAll('.wp_blog_code-tab-button');\n    const contents = document.querySelectorAll('.wp_blog_code-tab-content');\n    buttons.forEach(button => {\n        button.addEventListener('click', () => {\n            const lang = button.getAttribute('data-lang');\n            buttons.forEach(btn => btn.classList.remove('active'));\n            button.classList.add('active');\n            contents.forEach(content => {\n                content.classList.toggle('active', content.getAttribute('data-lang') === lang);\n            });\n        });\n    });\n});\n<\/script>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Problem Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array. Example 1: Input: nums = [3,0,1] Output: 2 Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[176,175,811,810,174,172,173],"tags":[],"class_list":["post-6141","post","type-post","status-publish","format-standard","category-csharp","category-cplusplus","category-data-structures-and-algorithms","category-dsa","category-java","category-javascript","category-python"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/6141","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=6141"}],"version-history":[{"count":3,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/6141\/revisions"}],"predecessor-version":[{"id":6169,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/6141\/revisions\/6169"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=6141"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=6141"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=6141"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}