ProgrammingHard
To count occurrences of values up to 10^6 in O(n), which code is correct and fast enough?
- A. int cnt[1000001]; inside main with the array freed each time, then the loop
- B. static int cnt[1000001]; for (i = 0; i < n; i++) cnt[a[i]]++;
- C. for (i = 0; i < n; i++) for (j = 0; j < i; j++) if (a[i] == a[j]) ...
- 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
- A recursive depth-first search could recurse 10^6 levels deep on a path-shaped graph. Which approach is correct and safe?
- A string of up to 10^6 characters is read with fgets. Which buffer declaration is correct?
- A loop walks a string with for (i = 0; i < strlen(s); i++) on a string of length 10^6. What is the total cost?
- A binary search on the answer in [1, 10^18] computes mid = (lo + hi) / 2 with long long. Is this safe?
- A sum of n = 10^5 terms is stored in a double. Is this a safe choice for exact integer sums up to 10^14?
- A loop reads n numbers and stores them in int a[n] as a VLA of size up to 10^6 inside main. What is the main risk?