Pages

Monday, May 4, 2026

3917. Count Indices With Opposite Parity (Brute Force) O(n2) + Optimized Solution O(n) + tips LEETCODE WEEKLY 500

 class Solution {

    public int[] countOppositeParity(int[] nums) {

        // approach 1 - checks every pair
        int n = nums.length;

        // i dont get the logic of how the conditions satisfy each other, and score part.

        int[] ans = new int[n];

        for(int i=0; i<n;i++) {
            int score = 0;

            for(int j=i+1; j<n; j++) {
                // check if value parity is opp
                boolean oppositeValue = (nums[i]%2!=nums[j]%2);
                if(oppositeValue) {
                    score++;
                }
            }

            ans[i] = score;
        }

        return ans;
    }
}


// approach 2 - checks every element once

oddCount =0;
evenCount=0; for(int =n-1; i>=0; i--) { if(n%2==0) { // curr->even, it pairs with all odds to its right
ans[i] = evenCount;
oddCount++;
} else {

//curr-> odd, it pairs with all even to its right ans[i] = oddCount;
evenCount++;
} }

3917. Count Indices With Opposite Parity (Brute Force) O(n2) + Optimized Solution O(n) + tips LEETCODE WEEKLY 500

  class Solution {     public int [] countOppositeParity ( int [] nums ) {          // approach 1 - checks every pair         int n = n...