1. Check All Subarrays (Brute Force)
Intuition
Run two nested loops from start 0 to n-1 and end start to n-1. Accumulate elements in sum. If sum % k == 0 (with proper handling for negative numbers), increment the counter.
When to apply: Use to understand the baseline problem statement before optimizing.
Brute Force Subarray Inspection Trace
2 of 2 questions left todayArray: [4, 5, 0, -2, -3, 1], k = 5
Array: [4, 5, 0, -2, -3, 1], k = 5. Outer start = 0.
public class Main { public static class Solution { public int subarraysDivByK(int[] nums, int k) { int count = 0; for (int i = 0; i < nums.length; i++) { int sum = 0; for (int j = i; j < nums.length; j++) { sum += nums[j]; if (sum % k == 0) count++; } } return count; } } public static void main(String[] args) { Solution sol = new Solution(); int[] nums = {4, 5, 0, -2, -3, 1}; int k = 5; System.out.println("Subarrays divisible: " + sol.subarraysDivByK(nums, k)); }}Time & Space Complexity
- Time complexity:
O(n^2)— Nested loops examine all n*(n+1)/2 subarrays with O(1) accumulation. - Space complexity:
O(1)— Only scalar counters are used.
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.