75-days-dsa-challenge

Ninja technique🥷 to ACE DSA Interviews.

View the Project on GitHub

560. Subarray Sum Equals K (Medium)

Brute force (TLE)

class Solution {
public:
    int subarraySum(vector<int>& nums, int k)
    {
        int n = nums.size();
        int cnt = 0;
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j <= n; j++) {
                int sm = 0;
                for (int k = i; k < j; k++)
                    sm += nums[k];
                if (sm == k)
                    cnt++;
            }
        }
        return cnt;
    }
};

prefix sum (TLE)

class Solution {
public:
    int subarraySum(vector<int>& nums, int k)
    {
        int n = nums.size();
        // prefix sum
        vector<int> prefix(n + 1, 0);
        for (int i = 0; i < n; i++)
            prefix[i + 1] = prefix[i] + nums[i];
        int ans = 0;
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j <= n; j++) {
                if (prefix[j] - prefix[i] == k)
                    ans++;
            }
        }
        return ans;
    }
};

Running sum (TLE)

class Solution {
public:
    int subarraySum(vector<int>& nums, int k)
    {
        int n = nums.size();
        int ans = 0;
        for (int i = 0; i < n; i++) {
            int sum = 0;
            for (int j = i; j < n; j++) {
                sum += nums[j];
                if (sum == k)
                    ans++;
            }
        }
        return ans;
    }
};

Using hashmap (AC)

class Solution {
public:
    int subarraySum(vector<int>& nums, int k)
    {
        int n = nums.size();
        int sm = 0;
        int ans = 0;
        unordered_map<int, int> mp;
        mp[0] = 1; // getting 0 sum is always possible
        for (int i = 0; i < n; ++i) {
            sm += nums[i];
            if (mp.count(sm - k)) ans += mp[sm - k];
            mp[sm]++;
        }
        return ans;
    }
};