1. All Subarrays Evaluation (Brute Force)
Intuition
Calculate the total sum modulo p. Let rem = total % p. If rem == 0, return 0 immediately. Otherwise, test all pairs (i, j) with 0 <= i <= j < n. Compute subSum = sum(nums[i..j]). If subSum % p == rem and j - i + 1 < n, update minLen = min(minLen, j - i + 1).
When to apply: Use to verify the problem statement logic on small arrays before introducing modular arithmetic hash maps.
All Subarrays Removal (O(N^2) Time)
2 of 2 questions left todayTarget remainder to remove is targetRem = 4
Target remainder to remove is targetRem = 4.
public class Main { public static class Solution { public int minSubarray(int[] nums, int p) { long total = 0; for (int x : nums) total += x; int rem = (int)(total % p); if (rem == 0) return 0; int n = nums.length; int minLen = n; for (int i = 0; i < n; i++) { long sum = 0; for (int j = i; j < n; j++) { sum += nums[j]; if (sum % p == rem && (j - i + 1) < n) { minLen = Math.min(minLen, j - i + 1); } } } return minLen == n ? -1 : minLen; } } public static void main(String[] args) { Solution sol = new Solution(); int[] nums = {3, 1, 4, 2}; int p = 6; System.out.println("Min Subarray Length: " + sol.minSubarray(nums, p)); }}Time & Space Complexity
- Time complexity:
O(n^2)— Evaluating all O(n2) subarrays with running sum takes O(n2) time. - Space complexity:
O(1)— O(1) auxiliary variables for pointers and sum trackers.
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.