ProgrammingHard

To count occurrences of values up to 10^6 in O(n), which code is correct and fast enough?

  1. A. int cnt[1000001]; inside main with the array freed each time, then the loop
  2. B. static int cnt[1000001]; for (i = 0; i < n; i++) cnt[a[i]]++;
  3. C. for (i = 0; i < n; i++) for (j = 0; j < i; j++) if (a[i] == a[j]) ...
  4. D. for (i = 0; i < n; i++) cnt[i] = a[i] * a[i]

Correct answer: B. static int cnt[1000001]; for (i = 0; i < n; i++) cnt[a[i]]++;

A global or static array of 10^6 + 1 ints avoids the large stack allocation of a local array. The nested loops are quadratic, and the last version does not count at all.

More C Programming questions

Exams that ask this topic