1. Nested Loops (Brute Force)
Intuition
Generate all subarrays of length >= 2 and check if their sum is divisible by k.
Algorithm
- 1. Loop i from 0 to N-2 as the starting index.
- 2. Initialize sum = nums[i].
- 3. Loop j from i+1 to N-1 as the ending index: - sum += nums[j] - if sum % k == 0, return true.
- 4. If no good subarray is found, return false.
Brute Force All Subarrays (Length >= 2) Modulo Scan
2 of 2 questions left todayPhase 1 — 25 is not a multiple of 6 Advance j to 2: Step 1: Subarray [23, 2] has sum 25
Phase 1 — 25 is not a multiple of 6 Advance j to 2: Step 1: Subarray [23, 2] has sum 25. 25 % 6 = 1. No match.
#include <iostream>#include <vector>using namespace std; // Brute Force Approach: Check all subarrays of length >= 2bool checkSubarraySum(const vector<int>& nums, int k) { int n = nums.size(); for (int i = 0; i < n - 1; i++) { long long sum = nums[i]; for (int j = i + 1; j < n; j++) { sum += nums[j]; if (sum % k == 0) { return true; } } } return false;} int main() { vector<int> nums = {23, 2, 4, 6, 7}; int k = 6; bool result = checkSubarraySum(nums, k); cout << "Output: " << (result ? "true" : "false") << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Two nested loops generate N*(N-1)/2 subarrays. Each takes O(1) arithmetic operations. - Space complexity:
O(1)— Only constant extra variables (i, j, sum) 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.