Count Largest Equal Pairs

Count Largest Equal Pairs

Count Largest Equal Pairs

Category: algorithms

Description

Given a 0-indexed integer array nums of length n, return the number of pairs (i, j) where 0 <= i <= j < n, such that nums[i] == nums[j] and nums[k] <= nums[i] for i <= k <= j

Solutions

The O(N^2) solution is simple as we traverse every pair and keep track of the maximum value between them, thus, we count pairs where the maximum between the pairs is less than or equal to the equal pair.

But the constraints of the problems won't allow O(N^2), to optimize we make use of the fact that we are only interested in indexes such that the maximum up to that index is at most nums[i] for each i, ie. if j is the first index to the right of i such that nums[j] > nums[i] then we only need to count equal pairs from index i to index j - 1.

So, we need the next greater element for each index, which is a well-known monotonic stack problem possible in O(N) https://leetcode.com/problems/next-greater-element-ii/

Now we need to count the frequency of arr[i] from index i to next_greater[i] - 1 for each i, this is also a well-known technique, range frequency queries, https://leetcode.com/problems/range-frequency-queries/

Using both these techniques, the overall solution is O(N log N) which is suitable with given constraints.

The question can be changed to only count pairs with i < j instead of i <= j as (i, i) is always counted anyways, thus we just subtract N from the below solution for that.

Here's the optimal code with a brute force checker function and random test case generator to verify solutions.

https://leetcode.com/playground/4BT2WGhq

Test Cases

Input: nums = [4, 2, 4, 5, 4]

Output: 6

Input: nums = [3, 4, 4, 3, 4]

Output: 8

Tags

Monotonic Stack, Binary Search

Comments

Popular posts from this blog

Range Update Maximum Query

Exploring a Number Conversion Algorithm

Toeplitz Matrix