![]() |
Given an array, array [] of N integers, find the count of reverse pairs. A pair of indices (i, j) is said to be a reverse pair if both the following conditions are met:
Examples: Input: N = 6, Table of Content Using Nested LoopsIn this approach, we iterate through each element in the array and compare it with subsequent elements to find reverse pairs, where the element at a higher index is smaller than the element at a lower index. The counter is incremented whenever such a pair is encountered. Example: The below example uses Nested Loops to count reverse pairs using JavaScript.
Output 3 Time Complexity: O(n^2), where n is the number of elements in the array. Space Complexity: O(1) Using Merge SortIn this approach, we recursively divide the array into smaller parts using the merge sort algorithm. During the merge step, while merging two sorted arrays, we count the reverse pairs by comparing elements from different parts. This allows us to efficiently count reverse pairs in the array. Example: The below example uses Merge Sort to count reverse pairs using JavaScript.
Output 3 Time Complexity: O(nlogn), where n is the number of elements in the array. Space Complexity: O(n) |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 11 |