GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — coding-problems/Arrays/find_one_missing_number.py at master · vedsgit/coding-problems Expand file tree/ Copy pathfind_one_missing_number.pyMore file actions 40 lines (31 loc) · 940 Bytes / Copy pathfind_one_missing_number.pyFile metadata and controls40 lines (31 loc) · 940 Bytes 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 ''' Find the missing number in a sequence Find the only missing integer in a sequence, all numbers are integers and they're smaller or equal to N+1 (N is length of the array). Input: [2, 1, 4] Output: 3 ========================================= Searching for 1 unknown, math problem. Use the sum formula for the first N numbers to compute the whole sum of the sequence. After that sum all elements from the array, and when you subtract those 2 numbers, you'll get the missing number. Sum formula = N*(N+1)/2 Time Complexity: O(N) Space Complexity: O(1) ''' ############ # Solution # ############ def missing_number(nums): s = sum(nums) n = len(nums) + 1 # sum formula (sum of the first n numbers) = (N*(N+1))/2 return n * (n + 1) // 2 - s ########### # Testing # ########### # Test 1 # Correct result => 4 print(missing_number([2, 3, 1])) # Test 2 # Correct result => 3 print(missing_number([2, 1, 4])) |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |