Created
January 30, 2021 01:35
-
-
Save ak9999/44a77d30806a2868bdefdefa0b5f88de to your computer and use it in GitHub Desktop.
My answer to the missing number problem on Leetcode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://leetcode.com/problems/missing-number/ | |
import random | |
def generate_input_array(n: int) -> list: | |
if not (1 <= n <= 104): | |
raise ValueError('Given `n` does not fulfill 1 <= n <= 104') | |
nums = list() | |
while len(nums) != n: | |
temp = random.randint(0, n) | |
if temp not in nums: | |
nums.append(temp) | |
return nums | |
def find_missing_number_naive(nums: list, n: int) -> int: | |
for i in range(n + 1): | |
if i not in nums: | |
return i | |
return -1 | |
def find_missing_number_xor(nums: list, n: int) -> int: | |
missing = 0 | |
# XOR all values in range(0, n) | |
for i in range(0, n + 1): | |
missing ^= i | |
# XOR all values in the `nums` array | |
for i in nums: | |
missing ^= i | |
return missing | |
if __name__ == '__main__': | |
n = 10 | |
nums = generate_input_array(n) | |
assert len(nums) == n, "Expected length should be `n`" | |
print(sorted(nums)) | |
naive = find_missing_number_naive(nums, n) | |
assert naive != None, "Problem: given `nums` has no missing element." | |
print(f'Naive solution gives us: {naive}') | |
xor = find_missing_number_xor(nums, n) | |
print(f'The O(1) solution using XOR gives us: {xor}') | |
nums.append(xor) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment