1. Nested Loops All Subarrays
Intuition
Iterate through all possible subarrays (i..j), compute their sum, and increment count if sum == k.
Algorithm
- 1. Initialize count = 0.
- 2. For i from 0 to n-1: - currentSum = 0 - For j from i to n-1: - currentSum += nums[j] - If currentSum == k: count++.
- 3. Return count.
Brute Force All Subarrays Sum Calculation
2 of 2 questions left todayPhase 1 — MATCH 1 FOUND
Phase 1 — MATCH 1 FOUND! count = 1: Subarray [0..1]: Elements [1, 2] sum to 3. Count increments to 1.
import java.util.*; public class Main { public static class Solution { public int subarraySum(int[] nums, int k) { int count = 0; for (int start = 0; start < nums.length; start++) { int sum = 0; for (int end = start; end < nums.length; end++) { sum += nums[end]; if (sum == k) count++; } } return count; } } public static void main(String[] args) { Solution sol = new Solution(); int[] nums = {1, 2, 3, -2, 1}; int k = 3; System.out.println("Subarray count: " + sol.subarraySum(nums, k)); }}Time & Space Complexity
- Time complexity:
O(N^2)— Evaluates all N*(N+1)/2 subarrays in O(N2) time. - Space complexity:
O(1)— Auxiliary space is O(1).
Why Brute Force Doesn't Scale:
For N = 105, quadratic O(N2) approaches require ~1010 operations, exceeding the standard 1-second CPU budget.
The optimal approach processes N elements in a single or logarithmic pass, completing in under 10ms with minimal memory footprint.