{"id":6136,"date":"2025-05-29T17:30:02","date_gmt":"2025-05-29T12:00:02","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=6136"},"modified":"2025-05-29T18:30:31","modified_gmt":"2025-05-29T13:00:31","slug":"single-number","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/single-number\/","title":{"rendered":"\u00a0Single 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 a non-empty array of integers <code>nums<\/code>, every element appears twice except for one. Find that single one.<\/p>\n    <p><strong>You must implement a solution with a linear runtime complexity and use only constant extra space.<\/strong><\/p>\n\n    <h2>Examples<\/h2>\n    <ul>\n        <li><strong>Input:<\/strong> nums = [2, 2, 1] \u2192 <strong>Output:<\/strong> 1<\/li>\n        <li><strong>Input:<\/strong> nums = [4, 1, 2, 1, 2] \u2192 <strong>Output:<\/strong> 4<\/li>\n        <li><strong>Input:<\/strong> nums = [1] \u2192 <strong>Output:<\/strong> 1<\/li>\n    <\/ul>\n\n    <h2>Constraints<\/h2>\n    <ul>\n        <li>1 \u2264 nums.length \u2264 3 \u00d7 10<sup>4<\/sup><\/li>\n        <li>-3 \u00d7 10<sup>4<\/sup> \u2264 nums[i] \u2264 3 \u00d7 10<sup>4<\/sup><\/li>\n        <li>Each element appears twice except one that appears only once.<\/li>\n    <\/ul>\n\n    <h2>Approach 1: Brute Force (Hash Map)<\/h2>\n    <ol>\n        <li>Create an empty hash map to store counts of each element.<\/li>\n        <li>Loop through the array, update the count for each element.<\/li>\n        <li>Loop again to find the element with count 1 and return it.<\/li>\n    <\/ol>\n\n    <h3>Dry Run<\/h3>\n    <p><strong>Input:<\/strong> [4, 1, 2, 1, 2]<\/p>\n    <p><strong>Step 1: Counting frequency<\/strong><\/p>\n    <ul>\n        <li>Insert 4 \u2192 hash[4] = 1<\/li>\n        <li>Insert 1 \u2192 hash[1] = 1<\/li>\n        <li>Insert 2 \u2192 hash[2] = 1<\/li>\n        <li>Update 1 \u2192 hash[1] = 2<\/li>\n        <li>Update 2 \u2192 hash[2] = 2<\/li>\n    <\/ul>\n    <p><strong>Step 2: Find element with count 1<\/strong><\/p>\n    <ul>\n        <li>4 \u2192 hash[4] = 1 \u2192 <strong>Return 4<\/strong><\/li>\n    <\/ul>\n    <h2>Time and Space Complexity<\/h2>\n    <p><strong>Time Complexity:<\/strong> O(n)<br \/>\n    We traverse the array twice: once for counting and once for checking.<\/p>\n    <p><strong>Space Complexity:<\/strong> O(n)<br \/>\n    The hash map may store counts for up to <code>n<\/code> elements in the worst case.<\/p>\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 singleNumber = function(nums) {\n    let hash = {};\n    for (let i = 0; i &lt; nums.length; i++) {\n        if (!hash[nums[i]]) {\n            hash[nums[i]] = 1;\n        } else {\n            hash[nums[i]]++;\n        }\n    }\n    for (let i = 0; i &lt; nums.length; i++) {\n        if (hash[nums[i]] === 1) {\n            return nums[i];\n        }\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;vector&gt;\n#include &lt;unordered_map&gt;\nusing namespace std;\n\nclass Solution {\npublic:\n    int singleNumber(vector&lt;int&gt;& nums) {\n        unordered_map&lt;int, int&gt; hash;\n        for (int num : nums) {\n            hash[num]++;\n        }\n        for (int num : nums) {\n            if (hash[num] == 1)\n                return num;\n        }\n        return -1;\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;stdio.h&gt;\n\nint singleNumber(int* nums, int numsSize) {\n    for (int i = 0; i &lt; numsSize; i++) {\n        int count = 0;\n        for (int j = 0; j &lt; numsSize; j++) {\n            if (nums[j] == nums[i]) count++;\n        }\n        if (count == 1) return nums[i];\n    }\n    return -1;\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.HashMap;\n\npublic class Solution {\n    public int singleNumber(int[] nums) {\n        HashMap&lt;Integer, Integer&gt; hash = new HashMap&lt;&gt;();\n        for (int num : nums) {\n            hash.put(num, hash.getOrDefault(num, 0) + 1);\n        }\n        for (int num : nums) {\n            if (hash.get(num) == 1) {\n                return num;\n            }\n        }\n        return -1;\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 singleNumber(self, nums):\n        hash = {}\n        for num in nums:\n            hash[num] = hash.get(num, 0) + 1\n        for num in nums:\n            if hash[num] == 1:\n                return num<\/code><\/pre>\n    <\/div>\n<\/div>\n<!-- \u2705 END: Code Tabs -->\n\n<div class=\"wp_blog_explanation\">\n        <h2 class=\"check\">Approach 2 &#8211; Optimal using XOR<\/h2>\n        <p>XOR of two same numbers is 0: <code>a ^ a = 0<\/code><\/p>\n        <p>XOR of a number with 0 is the number itself: <code>a ^ 0 = a<\/code><\/p>\n        <p>So, if all elements occur twice except one, XOR-ing all gives that unique number.<\/p>\n    \n        <h2>Dry Run<\/h2>\n        <p><strong>Input:<\/strong> [2, 3, 5, 2, 3]<\/p>\n        <p>Start <code>xor = 0<\/code><\/p>\n        <div class=\"code\">\n          xor = 0 ^ 2 = 2<br\/>\n          xor = 2 ^ 3 = 1<br\/>\n          xor = 1 ^ 5 = 4<br\/>\n          xor = 4 ^ 2 = 6<br\/>\n          xor = 6 ^ 3 = 5\n        <\/div>\n        <p class=\"check\"> Final answer: 5<\/p>\n       \n            <h2>Time and Space Complexity<\/h2>\n            <p><strong>Time Complexity:<\/strong> O(n)<br \/>\n                where n is the number of elements in the array\n            <\/p>\n            <p><strong>Space Complexity:<\/strong> O(1)<br \/>\n                no extra space used\n            <\/p>\n         \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 singleNumber = function(nums) {\n      let xor = 0;\n      for (let i = 0; i < nums.length; i++) {\n          xor = xor ^ nums[i];\n      }\n      return xor;\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 singleNumber(vector<int>& nums) {\n          int xorVal = 0;\n          for (int num : nums) {\n              xorVal ^= num;\n          }\n          return xorVal;\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 singleNumber(int* nums, int numsSize) {\n      int xor = 0;\n      for (int i = 0; i < numsSize; i++) {\n          xor ^= nums[i];\n      }\n      return xor;\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  public class Solution {\n      public int singleNumber(int[] nums) {\n          int xor = 0;\n          for (int num : nums) {\n              xor ^= num;\n          }\n          return xor;\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 singleNumber(self, nums):\n          xor = 0\n          for num in nums:\n              xor ^= num\n          return xor\n      <\/code><\/pre>\n    <\/div>\n  <\/div>\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 a non-empty array of integers nums, every element appears twice except for one. Find that single one. You must implement a solution with a linear runtime complexity and use only constant extra space. Examples Input: nums = [2, 2, 1] \u2192 Output: 1 Input: nums = [4, 1, 2, 1, 2] \u2192 Output:<\/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":[811,810],"tags":[],"class_list":["post-6136","post","type-post","status-publish","format-standard","category-data-structures-and-algorithms","category-dsa"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/6136","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=6136"}],"version-history":[{"count":3,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/6136\/revisions"}],"predecessor-version":[{"id":6170,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/6136\/revisions\/6170"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=6136"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=6136"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=6136"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}