1. Brute Force (Nested Loop with Zero Counter)
Intuition
Try every possible starting index i. Expand rightwards with index j. Count how many zeros appear. If zeros <= 1, valid 1s length is j - i + 1 - zeros. Update max length.
Algorithm
- Step 1: Initialize
maxLen = 0. - Step 2: For each i from 0 to n - 1:
- - Initialize
zeros = 0. - - For each j from i to n - 1:
- - If
nums[j] == 0,zeros++. - - If
zeros > 1, break. - -
maxLen = max(maxLen, j - i). - Step 3: Return
maxLen.
Brute Force (Nested Loop with Zero Counter) Trace
2 of 2 questions left todayPhase 1 — Setup: Left pointer L anchors at 0
Phase 1 — Setup: Left pointer L anchors at 0. Scanner pointer R starts traversing the array.
#include <iostream>#include <vector>#include <algorithm> class Solution {public: int longestSubarray(std::vector<int>& nums) { int n = nums.size(); int maxLen = 0; for (int i = 0; i < n; i++) { int zeros = 0; for (int j = i; j < n; j++) { if (nums[j] == 0) zeros++; if (zeros > 1) break; maxLen = std::max(maxLen, j - i); } } return maxLen; }}; int main() { Solution sol; std::vector<int> nums = {1, 1, 0, 1}; std::cout << "Max 1s: " << sol.longestSubarray(nums) << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Time complexity for Brute Force (Nested Loop with Zero Counter). - Space complexity:
O(1)— Space complexity for Brute Force (Nested Loop with Zero Counter).
Why Brute Force Doesn't Scale:
For N = 100,000, N2 = 1010 operations, taking over 10 seconds. Two-pointer sliding window guarantees that each element is touched at most twice, completing in 200,000 operations (< 5 ms).
For N = 100,000: Brute force takes ~10 billion operations; Sliding window takes ~200,000 operations.