Buffer Overflow Error while using Iterators in C++

Viewed 92

It is a question of leetcode : https://leetcode.com/explore/learn/card/fun-with-arrays/521/introduction/3237/

Given an array nums of integers, return how many of them contain an even number of digits. When I am attempting it without using iterators all test cases are passed, while using the iterator approach as shown below it is showing Buffer Overflow Error, although any custom test case is getting passed.

Can you tell why this iterator approach is failing, why this overflow error is occurring and how to rectify it ? Buffer Overflow Message

class Solution {
    
    int calculate_digit(int n){
        int count = 0;
        while(n){
            n = int(n/10);
                count++;
        }
        return count;
    }
        
public:
    
    int findNumbers(vector<int>& nums) {
        int check;
        vector<int>::iterator it;
        for (auto it = nums.begin(); it != nums.end(); ++it){
            check = calculate_digit(*it);
            if(check%2 != 0)
                nums.erase(it);            
        }
        
        return nums.size()-1;
        
    }
};
1 Answers

There are only three conditions (based on the constraints) that'd make the count to be incremented. We can just check for those (O(N) time O(1) memory):

// The following block might slightly improve the execution time;
// Can be removed;
static const auto __optimize__ = []() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    std::cout.tie(nullptr);
    return 0;
}();

// Most of headers are already included;
// Can be removed;
#include <cstdint>
#include <vector>

static const struct Solution {
    static const int findNumbers(
        std::vector<int>& nums
    ) {
        std::size_t count = 0;

        for (std::size_t index = 0; index < std::size(nums); ++index) {
            const auto& num = nums[index];

            if (
                (9 < num && num < 100) ||
                (999 < num && num < 10000) ||
                (num == 100000)
            ) {
                count++;
            }
        }

        return count;
    }
};
Related