Search code examples
javascriptalgorithmasymptotic-complexity

What is time complexity of this solution O(N) or O(LogN)?


https://codility.com/programmers/lessons/1-iterations/

Considering this:

if (largestHole > (bin.length - i) && subHole < (bin.length - i)) {
  break;
}

If the length of the largest hole so far is less than the length of the remaining digits to check it breaks the loop

This line let bin = parseInt(N, 10).toString(2); is to convert a number from base 10 to base 2 string, which is what I iterate over.

function solution(N) {
  let bin = parseInt(N, 10).toString(2);
  let subHole = 0;
  let largestHole = 0;
  for (var i = 0; i < bin.length; i++) {
    if (largestHole > (bin.length - i) && subHole < (bin.length - i)) {
      break;
    }
    if (bin[i] === '0') { subHole++; }
    else {
      if (subHole > largestHole) {
        largestHole = subHole;
      }
      subHole = 0;
    }
  }
  return largestHole;
}

https://codility.com/programmers/lessons/1-iterations/


Solution

  • Still O(n). The complexity doesn't take into account of coefficients. Also, a O(log n) function would be something like binary search.

    EDIT: a simple explanation of a O(log n) alogrithm: Take binary search for example. You have a number x from, say, 1 to 100, and it's hidden in an sorted array containing n numbers from 1 to 100. You start from the middle of the array, depending on the size of the middle number compared to x, you search the left half or the right half of the array. The process continues recursively, until you found the number.

    For example I want to find 5 in [1,3,5,6,7,9,10]. I start from the 4th place. It's 6, and its bigger than 5, so we seach the left half, from 1 to 5. Then, I check the middle position again in the narrowed range, which is 3. It's smaller than 5, so we search the right half. At this point we have only one number left - which is 5.

    The search keeps dividing the array in half, so the worst scenario would take log 2 n (base 2 logarithm of n). That's a O(log n) function.

    However, as I said, the coefficient of the complexity doesn't matter. For example Bubble sort usually takes approximately (n^2)/2 turns, but we simply count that as O(n^2), ignoring the 1/2 coefficient.