Concise C++ solution, use set instead of map

  • 16

    There is really no need to use map, the required length is at least 2, so we just need to insert the mod one iteration later.

    class Solution {
        bool checkSubarraySum(vector<int>& nums, int k) {
            int n = nums.size(), sum = 0, pre = 0;
            unordered_set<int> modk;
            for (int i = 0; i < n; ++i) {
                sum += nums[i];
                int mod = k == 0 ? sum : sum % k;
                if (modk.count(mod)) return true;
                pre = mod;
            return false;

  • 0
    This post is deleted!

  • 2

    By using

    modk.find(mod) != modk.end()

    instead of


    it runs faster

  • 0

    wonderful thanks for your answer

  • 0


    modk.find won't be faster than modk.count.

    This is a HashSet, every key is unique.

    I think count() is better here because it is shorter.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.