Reverse Pairs

Arrays FAQs(Hard) Hard
  • Fun Fact: While the problem of finding reverse pairs in an integer array might seem abstract, it actually finds use in data analysis and comparison-based sorting algorithms like Merge sort or Quick sort
  • In these cases, an efficient sorting of elements matters a lot, especially when dealing with large datasets
  • The concept of identifying and handling reverse pairs can be used to optimize these sorting algorithms, thereby improving the performance of software applications that rely on data processing, analysis, or management

Given an integer array nums. Return the number of reverse pairs in the array.


An index pair (i, j) is called a reverse pair if:

  • 0 <= i < j < nums.length
  • nums[i] > 2 * nums[j].

Examples:

Input: nums = [6, 4, 1, 2, 7]

Output: 3

Explanation: The reverse pairs are:

(0, 2) : nums[0] = 6, nums[2] = 1, 6 > 2 * 1

(0, 3) : nums[0] = 6, nums[3] = 2, 6 > 2 * 2

(1, 2) : nums[1] = 4, nums[2] = 1, 4 > 2 * 1

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

Output: 0

Explanation: No pairs satisfy both the conditons.

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

Constraints

  • 1 <= nums.length <= 105
  • -104 <= nums[i] <= 104

Hints

  • Similar to counting inversions, we divide the array into two halves and count reverse pairs while merging. During merging, count the number of nums[j] where nums[i] > 2 * nums[j] for all i < j.
  • If values in nums are bounded, a Fenwick Tree or Segment Tree can efficiently count elements <= 2 * nums[j] in O(log n).

Company Tags

Zynga Splunk American Express Unity Technologies Walmart Stripe Robinhood HCL Technologies Alibaba Databricks Epic Systems Activision Blizzard OYO Rooms Pinterest Electronic Arts PwC Rockstar Games Flipkart Chewy Boston Consulting Group Riot Games Broadcom Swiggy Visa Uber Google Microsoft Amazon Meta Apple Netflix Adobe