Skip to content

Commit 75ea29a

Browse files
authored
Create missing-element-in-sorted-array.py
1 parent 763a9ec commit 75ea29a

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Time: O(logn)
2+
# Space: O(1)
3+
4+
class Solution(object):
5+
def missingElement(self, nums, k):
6+
"""
7+
:type nums: List[int]
8+
:type k: int
9+
:rtype: int
10+
"""
11+
def missing_count(nums, x):
12+
return (nums[x]-nums[0]+1)-(x-0+1)
13+
14+
def check(nums, x, k):
15+
return k <= missing_count(nums, x)
16+
17+
left, right = 0, len(nums)-1
18+
while left <= right:
19+
mid = left + (right-left)//2
20+
if check(nums, mid, k):
21+
right = mid-1
22+
else:
23+
left = mid+1
24+
assert(not check(nums, right, k))
25+
return nums[right] + (k-missing_count(nums, right))

0 commit comments

Comments
 (0)