Skip to content

Commit ad9f825

Browse files
committed
Add leetcode-meditations-missing-number.mdx
1 parent a25ffaf commit ad9f825

File tree

2 files changed

+194
-1
lines changed

2 files changed

+194
-1
lines changed
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
---
2+
title: "LeetCode Meditations: Missing Number"
3+
tags: [Computer Science, TypeScript, JavaScript]
4+
description: Solving the LeetCode Missing Number problem.
5+
slug: leetcode-meditations-missing-number
6+
date: 2024-12-24
7+
---
8+
9+
![Cover image](https://raw.githubusercontent.com/rivea0/leetcode-meditations-assets/main/src/2024-12-24/76-lm.png)
10+
11+
Let's start with the description for [this problem](https://leetcode.com/problems/missing-number):
12+
13+
> 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._
14+
15+
For example:
16+
17+
```
18+
Input: nums = [3, 0, 1]
19+
Output: 2
20+
21+
Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0, 3]. 2 is the missing number in the range since it does not appear in nums.
22+
```
23+
24+
Or:
25+
26+
```
27+
Input: nums = [0, 1]
28+
Output: 2
29+
30+
Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0, 2]. 2 is the missing number in the range since it does not appear in nums.
31+
```
32+
33+
Or:
34+
35+
```
36+
Input: nums = [9, 6, 4, 2, 3, 5, 7, 0, 1]
37+
Output: 8
38+
39+
Explanation: n = 9 since there are 9 numbers, so all numbers are in the range [0, 9]. 8 is the missing number in the range since it does not appear in nums.
40+
```
41+
42+
It's also stated that *all the numbers of `nums` are **unique**.*
43+
44+
---
45+
46+
One easy way to solve this is to get the total sum of the range, then subtract the sum of the given array. What is left will be the missing number.
47+
48+
It can be done using `reduce` to sum the numbers, like this:
49+
50+
```ts
51+
function missingNumber(nums: number[]): number {
52+
return Array.from({
53+
length: nums.length + 1
54+
}, (_, idx) => idx).reduce((acc, item) => acc + item, 0)
55+
- nums.reduce((acc, item) => acc + item, 0);
56+
}
57+
```
58+
59+
First, we create an array with values from `0` to `nums.length + 1` and get its sum, then subtract the sum of `nums` from it.
60+
61+
However, the time and space complexities will be $O(n)$ with this solution as we create an array for the range.
62+
63+
We can have a more (*storage-wise*) efficient solution using bit manipulation.
64+
In fact, we can use an [XOR](https://rivea0.github.io/blog/leetcode-meditations-chapter-14-bit-manipulation#bitwise-xor) operation to help us with that.
65+
66+
To remember, XOR results in 1 if both of the bits are different — that is, one of them is 0 and the other is 1.
67+
When we XOR a number with itself, it will result in 0, as all the bits are the same.
68+
69+
For example, 3 in binary is `11`, when we do `11 ^ 11` the result is `0`:
70+
71+
```ts
72+
const n = 3;
73+
const result = n ^ n; // 0
74+
```
75+
76+
In other words, <mark>an XOR operation of a number with itself will result in 0</mark>.
77+
78+
If we do XOR with each number in the array with the indices, eventually all of them will cancel out (result in 0), leaving only the missing number.
79+
80+
You might think that not all numbers are at their index, for example if `nums` is `[3, 0, 1]`, it is obvious that `3` does not even have an "index 3" that can be associated with it!
81+
82+
For that, we can start by initializing our result to `nums.length`. Now, even if the missing number is equal to `nums.length`, we are handling that edge case.
83+
84+
```ts
85+
let result = nums.length;
86+
```
87+
88+
Also, *XOR is commutative and associative*, so it's not important at which index a number appears (or doesn't have one, like in the example above) — they eventually will cancel out.
89+
90+
Now, with a `for` loop, we can do the XOR using the [bitwise XOR assignment operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_XOR_assignment):
91+
92+
```ts
93+
for (let i = 0; i < nums.length; i++) {
94+
result ^= i ^ nums[i];
95+
}
96+
```
97+
98+
And, the final result is the missing number. The solution overall looks like this:
99+
100+
```ts
101+
function missingNumber(nums: number[]): number {
102+
let result = nums.length;
103+
for (let i = 0; i < nums.length; i++) {
104+
result ^= i ^ nums[i];
105+
}
106+
107+
return result;
108+
}
109+
```
110+
111+
#### Time and space complexity
112+
113+
The time complexity is again $O(n)$ as we iterate through each number in the array, but the space complexity will be $O(1)$ as we don't have any additional storage need that will grow as the input size increases.
114+
115+
---
116+
117+
Next up, we will take a look at the final problem of the entire series, [Sum of Two Integers](https://leetcode.com/problems/sum-of-two-integers). Until then, happy coding.

public/feed.xml

Lines changed: 77 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,85 @@
44
<description><![CDATA[My blog, projects, etc.]]></description>
55
<link>https://rivea0.github.io</link>
66
<generator>RSS for Node</generator>
7-
<lastBuildDate>Mon, 23 Dec 2024 12:16:14 GMT</lastBuildDate>
7+
<lastBuildDate>Tue, 24 Dec 2024 13:24:18 GMT</lastBuildDate>
88
<atom:link href="https://rivea0.github.io/feed.xml" rel="self" type="application/rss+xml"/>
99
<language><![CDATA[en]]></language>
10+
<item>
11+
<title><![CDATA[LeetCode Meditations: Missing Number]]></title>
12+
<description><![CDATA[<p><img src="https://raw.githubusercontent.com/rivea0/leetcode-meditations-assets/main/src/2024-12-24/76-lm.png" alt="Cover image"></p>
13+
<p>Let&#39;s start with the description for <a href="https://leetcode.com/problems/missing-number" target="_blank" rel="noopener noreferrer">this problem</a>:</p>
14+
<blockquote>
15+
<p>Given an array <code>nums</code> containing <code>n</code> distinct numbers in the range <code>[0, n]</code>, return <em>the only number in the range that is missing from the array.</em></p>
16+
</blockquote>
17+
<p>For example:</p>
18+
<pre><code>Input: nums = [3, 0, 1]
19+
Output: 2
20+
21+
Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0, 3]. 2 is the missing number in the range since it does not appear in nums.
22+
</code></pre>
23+
<p>Or:</p>
24+
<pre><code>Input: nums = [0, 1]
25+
Output: 2
26+
27+
Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0, 2]. 2 is the missing number in the range since it does not appear in nums.
28+
</code></pre>
29+
<p>Or:</p>
30+
<pre><code>Input: nums = [9, 6, 4, 2, 3, 5, 7, 0, 1]
31+
Output: 8
32+
33+
Explanation: n = 9 since there are 9 numbers, so all numbers are in the range [0, 9]. 8 is the missing number in the range since it does not appear in nums.
34+
</code></pre>
35+
<p>It&#39;s also stated that <em>all the numbers of <code>nums</code> are <strong>unique</strong>.</em></p>
36+
<hr>
37+
<p>One easy way to solve this is to get the total sum of the range, then subtract the sum of the given array. What is left will be the missing number.</p>
38+
<p>It can be done using <code>reduce</code> to sum the numbers, like this:</p>
39+
<pre><code class="language-ts">function missingNumber(nums: number[]): number {
40+
return Array.from({
41+
length: nums.length + 1
42+
}, (_, idx) =&gt; idx).reduce((acc, item) =&gt; acc + item, 0)
43+
- nums.reduce((acc, item) =&gt; acc + item, 0);
44+
}
45+
</code></pre>
46+
<p>First, we create an array with values from <code>0</code> to <code>nums.length + 1</code> and get its sum, then subtract the sum of <code>nums</code> from it.</p>
47+
<p>However, the time and space complexities will be $O(n)$ with this solution as we create an array for the range.</p>
48+
<p>We can have a more (<em>storage-wise</em>) efficient solution using bit manipulation.<br>In fact, we can use an <a href="https://rivea0.github.io/blog/leetcode-meditations-chapter-14-bit-manipulation#bitwise-xor" target="_blank" rel="noopener noreferrer">XOR</a> operation to help us with that.</p>
49+
<p>To remember, XOR results in 1 if both of the bits are different — that is, one of them is 0 and the other is 1.<br>When we XOR a number with itself, it will result in 0, as all the bits are the same.</p>
50+
<p>For example, 3 in binary is <code>11</code>, when we do <code>11 ^ 11</code> the result is <code>0</code>:</p>
51+
<pre><code class="language-ts">const n = 3;
52+
const result = n ^ n; // 0
53+
</code></pre>
54+
<p>In other words, <mark>an XOR operation of a number with itself will result in 0</mark>.</p>
55+
<p>If we do XOR with each number in the array with the indices, eventually all of them will cancel out (result in 0), leaving only the missing number.</p>
56+
<p>You might think that not all numbers are at their index, for example if <code>nums</code> is <code>[3, 0, 1]</code>, it is obvious that <code>3</code> does not even have an &quot;index 3&quot; that can be associated with it!</p>
57+
<p>For that, we can start by initializing our result to <code>nums.length</code>. Now, even if the missing number is equal to <code>nums.length</code>, we are handling that edge case.</p>
58+
<pre><code class="language-ts">let result = nums.length;
59+
</code></pre>
60+
<p>Also, <em>XOR is commutative and associative</em>, so it&#39;s not important at which index a number appears (or doesn&#39;t have one, like in the example above) — they eventually will cancel out.</p>
61+
<p>Now, with a <code>for</code> loop, we can do the XOR using the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_XOR_assignment" target="_blank" rel="noopener noreferrer">bitwise XOR assignment operator</a>:</p>
62+
<pre><code class="language-ts">for (let i = 0; i &lt; nums.length; i++) {
63+
result ^= i ^ nums[i];
64+
}
65+
</code></pre>
66+
<p>And, the final result is the missing number. The solution overall looks like this:</p>
67+
<pre><code class="language-ts">function missingNumber(nums: number[]): number {
68+
let result = nums.length;
69+
for (let i = 0; i &lt; nums.length; i++) {
70+
result ^= i ^ nums[i];
71+
}
72+
73+
return result;
74+
}
75+
</code></pre>
76+
<h4>Time and space complexity</h4>
77+
<p>The time complexity is again $O(n)$ as we iterate through each number in the array, but the space complexity will be $O(1)$ as we don&#39;t have any additional storage need that will grow as the input size increases.</p>
78+
<hr>
79+
<p>Next up, we will take a look at the final problem of the entire series, <a href="https://leetcode.com/problems/sum-of-two-integers" target="_blank" rel="noopener noreferrer">Sum of Two Integers</a>. Until then, happy coding.</p>
80+
]]></description>
81+
<link>https://rivea0.github.io/blog/leetcode-meditations-missing-number</link>
82+
<guid isPermaLink="false">https://rivea0.github.io/blog/leetcode-meditations-missing-number</guid>
83+
<dc:creator><![CDATA[Eda Eren]]></dc:creator>
84+
<pubDate>Tue, 24 Dec 2024 00:00:00 GMT</pubDate>
85+
</item>
1086
<item>
1187
<title><![CDATA[LeetCode Meditations: Reverse Bits]]></title>
1288
<description><![CDATA[<p><img src="https://raw.githubusercontent.com/rivea0/leetcode-meditations-assets/main/src/2024-12-23/75-lm.png" alt="Cover image"></p>

0 commit comments

Comments
 (0)