githubEdit

25. Longest Subarray with Majority Greater than K

βœ… GFG solution to Longest Subarray with Majority Greater than K: find longest subarray where count of elements > k exceeds count of elements ≀ k using prefix sum transformation. πŸš€

The problem can be found at the following link: πŸ”— Question Linkarrow-up-right

🧩 Problem Description

Given an array arr[] and an integer k, find the length of longest subarray in which the count of elements greater than k is more than the count of elements less than or equal to k.

πŸ“˜ Examples

Example 1

Input: arr[] = [1, 2, 3, 4, 1], k = 2
Output: 3
Explanation: The subarray [2, 3, 4] or [3, 4, 1] satisfy the given condition, 
and there is no subarray of length 4 or 5 which will hold the given condition, 
so the answer is 3.

Example 2

Input: arr[] = [6, 5, 3, 4], k = 2
Output: 4
Explanation: In the subarray [6, 5, 3, 4], there are 4 elements > 2 and 0 elements <= 2, 
so it is the longest subarray.

Example 3

πŸ”’ Constraints

  • $1 \le \text{arr.size()} \le 10^6$

  • $1 \le \text{arr}[i] \le 10^6$

  • $0 \le k \le 10^6$

βœ… My Approach

The optimal solution uses Prefix Sum Transformation with Hash Map:

Transform and Conquer

  1. Key Transformation:

    • Transform the problem: treat elements > k as +1 and elements <= k as -1.

    • We need subarrays where sum of transformed values > 0.

    • This means more +1s than -1s, i.e., count(elements > k) > count(elements <= k).

  2. Prefix Sum Strategy:

    • Maintain running sum of transformed values.

    • If sum > 0 at position i, entire prefix [0, i] is valid.

    • Otherwise, look for a previous position with sum - 1.

  3. Hash Map Logic:

    • Store first occurrence of each prefix sum value.

    • For current position with sum s, if we find position with sum s-1:

      • Subarray from that position to current has sum = 1 > 0 βœ“

    • Track maximum length found.

  4. Algorithm Steps:

    • For each element, add +1 if arr[i] > k, else add -1.

    • If cumulative sum > 0, update answer to i + 1.

    • Else check if sum - 1 exists in map, update answer accordingly.

    • Store first occurrence of current sum.

Mathematical Insight: If prefixSum[j] - prefixSum[i] > 0, then subarray [i+1, j] has more elements > k than elements <= k.

πŸ“ Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(n), where n is the size of the array. We make a single pass through the array, and each hash map operation (lookup and insert) takes O(1) average time.

  • Expected Auxiliary Space Complexity: O(n), as in the worst case, all prefix sum values could be unique, requiring O(n) space in the hash map to store all distinct prefix sums.

πŸ§‘β€πŸ’» Code (C++)

chevron-right⚑ View Alternative Approaches with Code and Analysishashtag

πŸ“Š 2️⃣ Explicit Prefix Sum Tracking

πŸ’‘ Algorithm Steps:

  1. Maintain explicit transformation of array elements.

  2. Store prefix sum at each position with hash map.

  3. Check for sum > 0 and sum - 1 conditions separately.

  4. Track maximum valid subarray length.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n) - Single pass with hash operations

  • Auxiliary Space: πŸ’Ύ O(n) - Hash map storage

βœ… Why This Approach?

  • More explicit transformation logic

  • Easier to understand the -1/+1 mapping

  • Clear conditional structure

πŸ“Š 3️⃣ Brute Force Approach

πŸ’‘ Algorithm Steps:

  1. Generate all possible subarrays using nested loops.

  2. For each subarray, count elements > k and elements <= k.

  3. If count(> k) > count(<= k), update maximum length.

  4. Return the maximum length found.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(nΒ²) - Two nested loops

  • Auxiliary Space: πŸ’Ύ O(1) - Constant space

βœ… Why This Approach?

  • Simple and straightforward

  • No complex data structures

  • Good for understanding the problem

Note: This approach results in Time Limit Exceeded (TLE) for large inputs (fails ~1110/1115 test cases due to time constraints).

πŸ“Š 4️⃣ Two-Pass with Transformation Array

πŸ’‘ Algorithm Steps:

  1. Create transformed array where arr[i] = 1 if arr[i] > k, else -1.

  2. Find longest subarray in transformed array with sum > 0.

  3. Use hash map to track prefix sums efficiently.

  4. Return maximum length found.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n) - Two linear passes

  • Auxiliary Space: πŸ’Ύ O(n) - Transformation array + hash map

βœ… Why This Approach?

  • Clear separation of transformation and processing

  • Explicit intermediate representation

  • Educational value in problem decomposition

πŸ†š πŸ” Comparison of Approaches

πŸš€ Approach

⏱️ Time Complexity

πŸ’Ύ Space Complexity

βœ… Pros

⚠️ Cons

🎯 Prefix Sum Transform

🟒 O(n)

🟑 O(n)

πŸš€ Optimal single pass

πŸ’Ύ Hash map overhead

πŸ“Š Explicit Transformation

🟒 O(n)

🟑 O(n)

πŸ“– Clear logic flow

πŸ”§ Similar to main approach

πŸ”„ Brute Force

πŸ”΄ O(nΒ²)

🟒 O(1)

🎯 Simple to understand

🐌 Quadratic time

πŸ“ˆ Two-Pass Transform

🟒 O(n)

πŸ”΄ O(n)

πŸ” Explicit array transformation

πŸ’Ύ Extra array space

πŸ† Best Choice Recommendation

🎯 Scenario

πŸŽ–οΈ Recommended Approach

πŸ”₯ Performance Rating

πŸ… Optimal performance needed

πŸ₯‡ Prefix Sum Transform

β˜…β˜…β˜…β˜…β˜…

πŸ“– Learning/Understanding

πŸ₯ˆ Explicit Transformation

β˜…β˜…β˜…β˜…β˜…

πŸ’‘ Educational purposes

πŸ₯‰ Two-Pass Transform

β˜…β˜…β˜…β˜…β˜†

🎯 Small input size

πŸ… Brute Force

β˜…β˜…β˜…β˜†β˜†

β˜• Code (Java)

🐍 Code (Python)

🧠 Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: πŸ“¬ Any Questions?arrow-up-right. Let's make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


πŸ“Visitor Count

Visitor counter

Last updated