DDSA Solutions

Longest Subarray Length

Time: O(n)
Space: O(n)
Advertisement

Intuition

Find length of longest subarray with equal number of 0s and 1s. Prefix sum + hashmap.

Algorithm

  1. 1Encode 0 as -1. Find longest subarray with sum 0 using prefix sum and first-occurrence hashmap.

Common Pitfalls

  • Same as LC 525. Map prefix sum to first index. When same prefix sum seen again: span is a valid subarray.
Longest Subarray Length.java
Java
// Approach: Sliding window with HashMap tracking first occurrence of prefix state.
// Time: O(n) Space: O(n)
import java.util.*;

class Solution {
    public static int longestSubarray(int[] arr) {
        int n = arr.length;
        int maxLen = 0;

        Stack<Integer> st = new Stack<>();

        for (int i = 0; i <= n; i++) {
            int nge = (i == n ? Integer.MAX_VALUE : arr[i]);

            while (!st.isEmpty() && arr[st.peek()] < nge) {
                int curr = arr[st.pop()];
                int len = st.isEmpty() ? i : i - st.peek() - 1;

                if (len >= curr)
                    maxLen = Math.max(maxLen, len);
            }

            st.push(i);
        }

        return maxLen;

    }
}
Advertisement
Was this solution helpful?