Efficient way to count occurrences of a key in a sorted array

后端 未结 10 1523
粉色の甜心
粉色の甜心 2021-01-30 23:49

This was asked in on-site Microsoft interview.

Count the number of occurrences of a given key in an array.

I answered linear search because the elements may be s

10条回答
  •  有刺的猬
    2021-01-31 00:19

    For unsorted array there is not much we can do other than linear search.

    For sorted array you can do it in O(logN) using a slightly modified binary search:

    • Find the index of first occurrence of key, call it f.
    • Find the index of last occurrence of key, call it l.
    • If the key exists in the array l-f+1 is the answer.

    Finding the first occurrence:

    arr[i] is the first occurrence of key iff

    • arr[i] == key and either
      • i == 0 ( it's the first element of the array) or
      • arr[i-1] != key (it's not the first element of the array and element to it's left is different)

    You can slightly modify the binary search to find the first occurrence.
    In a binary search you terminate the search when you find arr[mid] == key.
    Modify the condition such that you terminate the search when you find the first occurrence instead of any occurrence.

    Algorithm:

    low = 0
    high = arrSize - 1 
    
    while low <=  high
    
      mid = (low + high) / 2
    
      //if arr[mid] == key         // CHANGE
      if arr[mid] == key AND ( mid == 0 OR arr[mid-1] != key )
        return mid
      //else if ( key < arr[mid] ) // CHANGE
      else if ( key <= arr[mid] ) 
        high = mid - 1
      else
        low = mid + 1        
      end-if
    
    end-while
    
    return -1
    

    Similarly you can find the last occurrence.

提交回复
热议问题