Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

LeetCode: Missing Element in Sorted Array

Posted on August 5, 2019July 26, 2020 by braindenny

Missing Element in Sorted Array



Similar Problems:

  • CheatSheet: Leetcode For Code Interview
  • CheatSheet: Common Code Problems & Follow-ups
  • Tag: #binarysearch

Given a sorted array A of unique numbers, find the K-th missing number starting from the leftmost number of the array.

Example 1:

Input: A = [4,7,9,10], K = 1
Output: 5
Explanation: 
The first missing number is 5.

Example 2:

Input: A = [4,7,9,10], K = 3
Output: 8
Explanation: 
The missing numbers are [5,6,8,...], hence the third missing number is 8.

Example 3:

Input: A = [1,2,4], K = 3
Output: 6
Explanation: 
The missing numbers are [3,5,6,7,...], hence the third missing number is 6.

Note:

  1. 1 <= A.length <= 50000
  2. 1 <= A[i] <= 1e7
  3. 1 <= K <= 1e8

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


  • Solution:
// https://code.dennyzhang.com/missing-element-in-sorted-array
// Basic Ideas: binary search
//   Evaluate the left half or the right half
// Complexity: Time O(log(n)), Space O(1)
func missingElement(nums []int, k int) int {
    totalMiss := (nums[len(nums)-1]-nums[0]+1)-len(nums)
    if totalMiss < k {
        return nums[len(nums)-1]+k-totalMiss
    }
    left, right := 0, len(nums)-1
    for left+1<right {
        mid := (right-left)/2+left
        cnt := (nums[mid]-nums[left])-(mid-left)
        if cnt >= k {
            // search left part
            right = mid
        } else {
            // search right part
            left = mid
            k -= cnt
        }
    }
    // left.right
    return nums[left]+k
}
linkedin
github
slack

Post Views: 0
Posted in MediumTagged binarysearch

Post navigation

LeetCode: Maximum Average Subarray II
LeetCode: K-th Smallest Prime Fraction

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #blog #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum binarysearch editdistance hashmap intervaldp knapsack monotone oodesign presum rectangle redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • a
  • a
  • a
  • a
  • a

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.