6 May 2024 Shift 1 — Count Subarrays with Sum = K

M · mediumP · Verified PYQAmbiguous I/Oarrays

Given a sequence of integers “nums” and an integer K, find the total count of contiguous subarrays whose elements sum equals exactly K. Input: comma-separated integers followed by comma then K value.

1 <= len(nums) <= 2\*10\*\*4, -1000 <= nums[i] <= 1000
Input
1 2 3 4 5 -4 -3 ,10
Output
2
The I/O format for this question is intentionally ambiguous — TCS NQT sometimes omits full specs. Practice parsing.
Use prefix sum + hashmap. For each index, check count of (prefix_sum - K) in map. O(N) time.
Subarrays summing to 10: [1,2,3,4] and [3,4,5,-4,-3+10... check carefully with prefix sum]
← 3 May 2024 Shift 1 — Sorting Algorithm (Bubble Sort)6 May 2024 Shift 2 — First Non-Repeating Character →
Report an issue with this question