Missing number(s) Interview Question Redux

后端 未结 8 975
轮回少年
轮回少年 2021-01-30 07:14

The common interview problem of determining the missing value in a range from 1 to N has been done a thousand times over. Variations include 2 missing values up to K missing val

8条回答
  •  半阙折子戏
    2021-01-30 07:52

    If there are total N elements where each number x is such that 1 <= x <= N then we can solve this in O(nlogn) time complexity and O(1) space complexity.

    1. First sort the array using quicksort or mergesort.
    2. Scan through the sorted array and if the difference between previously scanned number, a and current number, b is equal to 2 (b - a = 2), then the missing number is a+1. This can be extended to condition where (b - a > 2).

    Time complexity is O(nlogn)+O(n) almost equal to O(nlogn) when N > 100.

提交回复
热议问题