cppintermediate10 minutes

Fix the Logic Bug in the Array Frequency Counter

The given C++ function is intended to count the frequency of each integer in an input vector and return the result as a map. However, the current implementation produces incorrect frequency counts due to a logic bug. Your task is to identify and fix the bug so that the function returns accurate counts.

Challenge prompt

Given the broken C++ function that counts the frequency of integers in a vector, identify and fix the logic bug so the function works correctly. The function should take a vector<int> as input and return a map<int, int> where each key is a unique integer from the vector and its value is the frequency of that integer in the vector.

Guidance

  • Review how the frequency map is updated within the loop.
  • Check whether the existing counts are being correctly incremented for repeated elements.

Hints

  • Look at how the map is accessed and updated inside the loop; there might be an incorrect assignment instead of increment.
  • Consider what happens when the element is already present in the map and the current implementation overwrites rather than increments the count.

Starter code

#include <vector>
#include <map>

std::map<int, int> countFrequencies(const std::vector<int>& nums) {
    std::map<int, int> freq;
    for (int num : nums) {
        if (freq.find(num) != freq.end()) {
            freq[num] = 1; // Bug here: resets count instead of incrementing
        } else {
            freq[num] = 1;
        }
    }
    return freq;
}

Expected output

For input vector {4, 2, 4, 3, 2, 4}, the function should return a map with counts: {4:3, 2:2, 3:1}

Core concepts

map usageloopsconditional logicfrequency counting

Challenge a Friend

Send this duel to someone else and see if they can solve it.