0

Lets say we have a string n, which can either be populated with "a"s or "b"s ex: n = "aaabbbab", "ababababab" and so on. and we define a function called

HalfA(n):
  count a = 0;
  for each i in n:
    if n == 'a'
        i++;
     if i >= n.length/2
       return true 
  return false     

and if n has a uniform distribution, what is the average case complexity of halfA. Intuitively, I believe it to be len(n) but I'm not sure how to show this. And suppose a is more probable than b, and its not a uniform distribution, how do I calculate the average case then?

user65663
  • 149
  • 1
  • 1
  • 4
  • 1
    it's `len(n)`. in the absolute best case, every character is 'a'. In this case is would still be `O(len(n)/2) = O(len(n))` – Cruncher Oct 21 '13 at 14:22
  • Thanks. As I mentioned, I get that its len(n) but I'm not sure how to show it. What if it was not a uniform distribution, and p(a) = .8 and p(b) = .2 or something – user65663 Oct 21 '13 at 14:25
  • No matter which distribution you use, it will still take at least n/2 steps. And at most n steps. The distribution doesn't change much in this case. – Cruncher Oct 21 '13 at 14:26
  • A more interesting question, would be: "assume you have an infinite stream of characters, governed by distribution d. What is the time complexity to find n 'a's." Even in this case it's `O(n)` for all distributions(except for `p(a)=0`), but it's less intuitive – Cruncher Oct 21 '13 at 14:28
  • I agree that for best case, it doesnt matter what distribution it is, it'll take atleast n/2 steps to count n/2 times, but what about average case – user65663 Oct 21 '13 at 14:29
  • Average case is bounded by best case, and worst case. Both of which are O(n). It then follows that average case is O(n). That is `worst <= average <= best`. Worst and best are n, so we get `n <= ? <= n`. ? can only be one thing. – Cruncher Oct 21 '13 at 14:30

1 Answers1

1

For ANY distribution.

Best case: n = "a*". This will take len(n)/2 steps, so the best case is: O(len(n))

Worst case: n = "b*". This will take len(n) steps, because you have to go through the entire array. So worst case is O(len(n))

Average case is bounded by best case and worst case. That is, O(len(n)) <= average case <= O(len(n)). It follows that the average case complexity is O(len(n))

Cruncher
  • 7,641
  • 1
  • 31
  • 65