Given a list of integers nums and an integer k, return the total number of contiguous subarrays whose elements sum to exactly k. The list may contain negative numbers. Return 0 for null or empty input.

Examples:

Input: nums = [1, 1, 1], k = 2 Output: 2 Explanation: [1,1] at indices 0-1 and [1,1] at indices 1-2 both sum to 2 Input: nums = [1, 2, 3], k = 3 Output: 2 Explanation: [3] at index 2 and [1,2] at indices 0-1 both sum to 3 Input: nums = [1, -1, 0], k = 0 Output: 3 Explanation: [1,-1] sums to 0, [1,-1,0] sums to 0, and [0] sums to 0, giving 3 subarrays total Input: nums = [1, 2, 3], k = 7 Output: 0 Explanation: No contiguous subarray sums to 7 Input: nums = null, k = 5 Output: 0 Explanation: Null input returns 0
Apex Code Editor

Welcome to Lightning Challenge!

How It Works

  • • Write your solution in the code editor
  • • Connect your Salesforce org to test
  • • Submit to check if your solution passes
  • • Use hints if you get stuck

Contest Alert

🏆 #CodeEveryDay September 2026 (Sep 16–30)Sponsored by FLXBL

Contest runs September 16 - 30. Complete challenges to climb the leaderboard!

Prizes 1 & 2: Salesforce certification exam voucher — won by random drawing, where every point is a ticket. see all prizes

Only the 15 daily challenges shown during this contest count toward points. Earlier dailies don't carry over.

Wally can't hear you

Please sign in to access the AI Assistant

Sign In