Created
January 2, 2022 02:25
-
-
Save ak9999/01531af5a6058fe7b163cc5e21c55056 to your computer and use it in GitHub Desktop.
Missing number problem from 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 = 1 | |
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) |
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
from missing_number_problem.missing_number import ( | |
find_missing_number_naive, | |
generate_input_array | |
) | |
def test_length_3(): | |
assert find_missing_number_naive([3,0,1], 3) == 2 | |
def test_two(): | |
assert find_missing_number_naive([0,1], 2) == 2 | |
def test_three(): | |
assert find_missing_number_naive([0], 1) == 1 | |
def test_four(): | |
assert find_missing_number_naive([9,6,4,2,3,5,7,0,1], 9) == 8 | |
def test_five(): | |
assert find_missing_number_naive(generate_input_array(10), 10) != -1 | |
def test_six(): | |
assert find_missing_number_naive(generate_input_array(100), 100) != None | |
def test_seven(): | |
import pytest | |
with pytest.raises(ValueError) as e: | |
missing_number(generate_array(105)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment