logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
instagramtwitterfacebookyoutubelinkedinmailgithubrss
Copyright © 2026 All rights reserved.
•
VIKI
Built with Vikramaditya Singh
Built with
VIKI - A posts created with Next.js and Tailwind.css
About
leetcode
Title
Table Of Contents
easy
13. Roman to Integer
14. Longest Common Prefix
20. Valid Parentheses
26. Remove Duplicates from Sorted Array
35. Search Insert Position
69. Sqrt(x)
70. Climbing Stairs
88. Merge Sorted Array (In-Place)
104. Maximum Depth of Binary Tree
118. Pascal's Triangle
121. Best Time to Buy and Sell Stock
205. Isomorphic Strings
242. Valid Anagram
283. Move Zeroes
345. Reverse Vowels of a String
605. Can Place Flowers
704. Binary Search
796. Rotate String
1071. Greatest Common Divisor of Strings
1299. Replace Elements with Greatest Element on Right Side
1431. Kids With the Greatest Number of Candies
1614. Maximum Nesting Depth of the Parentheses
1752. Check if Array Is Sorted and Rotated
1768. Merge Strings Alternately
1903. Largest Odd Number in String
2965. Find Missing and Repeated Values
hard
25. Reverse Nodes in k-Group
26. Remove Duplicates from Sorted Array
27. Remove Element
42. Trapping Rain Water
51. N-Queens
55. Jump Game
80. Remove Duplicates from Sorted Array II
88. Merge Sorted Array
121. Best Time to Buy and Sell Stock
122. Best Time to Buy and Sell Stock II
189. Rotate Array
274. H-Index
medium
2. Add Two Numbers
3. Longest Substring Without Repeating Characters
5. Longest Palindromic Substring
8. String to Integer (atoi)
11. Container With Most Water
15. 3Sum
17. Letter Combinations of a Phone Number
19. Remove Nth Node From End of List
22. Generate Parentheses
33. Search in Rotated Sorted Array
34. Find First and Last Position of Element in Sorted Array
48. Rotate Image
49. Group Anagrams
50. Pow(x, n)
53. Maximum Subarray
54. Spiral Matrix
56. Merge Intervals
61. Rotate List
73. Set Matrix Zeroes
74. Search a 2D Matrix
75. Sort Colors
78. Subsets
137. Single Number II
138. Copy List with Random Pointer
150. Evaluate Reverse Polish Notation
151. Reverse Words in a String
153. Find Minimum in Rotated Sorted Array
155. Min Stack
162. Find Peak Element
169. Majority Element
198. House Robber
207. Course Schedule
215. Kth Largest Element in an Array
227. Basic Calculator II
236. Lowest Common Ancestor of a Binary Tree
237. Delete Node in a Linked List
238. Product of Array Except Self
451. Sort Characters By Frequency
540. Single Element in a Sorted Array
560. Subarray Sum Equals K
636. Exclusive Time of Functions
875. Koko Eating Bananas
1011. Capacity To Ship Packages Within D Days
1101. The Earliest Moment When Everyone Become Friends
1283. Find the Smallest Divisor Given a Threshold
2140. Solving Questions With Brainpower
3169. Count Days Without Meetings
3481. Apply Substitutions
rotate-array-approach-1
189. Rotate Array (Approach 2 )
189. Rotate Array (Approach 1 )
number-of-islands-approach-1
200. Number of Islands (Approach 2)
200. Number of Islands (Approach 1)
meeting-rooms-ii-approach-1
253. Approach Using Priority Queue
253. Meeting Rooms II
misc
Calculate Floor & Ceiling
Find Nth Root Of M
Flatten A Linked List
Implement Lower Bound
Implement Upper Bound
Number of occurrence
take-u-forward
Recently Solved
arrays
The Ultimate Array Pattern Playbook
faqs-hard
Count Inversions in an Array
Find The Repeating And Missing Number
Majority Element II
Maximum Product Subarray
Merge Sorted Array (In-Place)
Reverse Pairs
faqs-medium
3. 3Sum
4. 4Sum
Maximum Subarray
Leaders in an Array
Majority Element
Next Permutation
Get specific element from Pascal's Triangle
Pascal's Triangle II (Row Generation)
Generate Pascal's Triangle (Full)
Spiral Matrix Traversal
Rearrange Array Elements by Sign
Rotate Image
Sort Colors (Dutch National Flag)
Two Sum
fundamentals
Check if Array is Sorted
Largest Element in an Array
Array Rotation (Left and Right)
Left Rotate Array by One
Linear Search
Max Consecutive Ones
Second Largest Element in an Array
Single Number
logic-building
Missing Number
Intersection of Two Sorted Arrays (with Duplicates)
Move Zeros to End
Remove Duplicates from Sorted Array
Union of Two Sorted Arrays
binary-search
About
d-arrays
Find Row With Maximum 1'S
Search In A 2D Matrix
faqs
Aggressive Cows
Allocate Books
Find Peak Element
Kth Element Of 2 Sorted Arrays
Minimise Max Distance to Gas Stations
Split Array - Largest Sum
fundamentals
Lower Bound
Binary Search
Upper Bound
logic-building
Count Occurrences in a Sorted Array
Find Minimum in Rotated Sorted Array
Find out how many times the array is rotated
Find First and Last Position of Element in Sorted Array
Floor and Ceil in Sorted Array
Kth Missing Positive Number
Search in Rotated Sorted Array
Search in Rotated Sorted Array II (With Duplicates)
Search Insert Position
Single Element in a Sorted Array
on-answers
Capacity To Ship Packages Within D Days
Find Nth Root of M
Find Square Root of a Number
Smallest Divisor Given a Threshold
Koko Eating Bananas (Minimum Rate)
Minimum Days to Make M Bouquets
Painter's Partition Problem
Split Array Largest Sum
hashing
Theory
faqs
Subarray Sum Equals K
Count Subarrays with Given XOR K
Largest Subarray with 0 Sum
Longest Consecutive Sequence
Longest Subarray with Sum K
recursion
faqs-medium
Combination Sum II (Unique Combinations)
Combination Sum (Unbounded)
Subset Sums
hard
Letter Combinations of a Phone Number
implementation-problems
Generate Parentheses
Power Function: pow(x, n)
Subsets (The Power Set)
subsequence-pattern-problems
Subsequence Sum Existence
Count All Subsequences With Sum K
sorting
Bubble Sort
Insertion Sort
Merge Sort
Quick Sort
Selection Sort
string
Isomorphic Strings
Largest Odd Number in String
Longest Common Prefix
Reverse Words in a String
Code Scratch›take u forward›arrays›faqs hard

Count Inversions in an Array

# Question

Given an integer array nums, return the number of inversions in the array. Two elements nums[i] and nums[j] form an inversion if nums[i] > nums[j] and i < j.

# Solution

# Pattern

Divide and Conquer (Modified Merge Sort) As you perform a standard Merge Sort, count the number of times an element from the right subarray is placed into the sorted array before elements from the left subarray.

# How to Identify

  • The problem asks for pairs (i, j) that satisfy an inequality condition (e.g., nums[i] > nums[j], nums[i] > 2 * nums[j]).
  • A brute-force approach requires a nested loop taking O(N2)O(N^2)O(N2) time.
  • The condition relies on relative ordering, suggesting that sorting the array might reveal information.

# Description

Step-by-step explanation:

  1. Divide: Split the array into two halves until you reach subarrays of size 1. A subarray of size 1 has 0 inversions.
  2. Conquer: Recursively count the inversions in the left half and the right half.
  3. Merge and Count (The core logic): - Set pointer i at the start of the left sorted half, and j at the start of the right sorted half.
    • Compare nums[i] and nums[j].
    • If nums[i] <= nums[j], there is no inversion. Place nums[i] into a temporary array and advance i.
    • If nums[i] > nums[j], we found an inversion! Because the left half is already sorted, if nums[i] is strictly greater than nums[j], then every element after i in the left half is also greater than nums[j].
    • Therefore, instead of counting 1 inversion, we add (mid - i + 1) to our inversion count. Place nums[j] into the temporary array and advance j.
  4. Finalize: Copy any remaining elements to the temporary array, then copy the temporary array back into the original array. Return the sum of left inversions, right inversions, and merge inversions.

# The Intuition

Think of two lines of students arranged by height (shortest to tallest). Line A (Left) and Line B (Right). Because Line A was originally standing in front of Line B, anyone in Line A should be shorter than anyone in Line B. You are combining them into a single sorted line. You look at the first student in Line A and the first student in Line B. If the student in Line B is actually shorter than the student in Line A, it means the Line B student is "out of order" relative to the Line A student. Furthermore, because Line A is already sorted, the Line B student is also out of order relative to everyone standing behind the first student in Line A. By taking the Line B student and putting them into the final sorted line, you resolve a whole block of "inversions" at once without having to count them individually.

# Complexity

LabelWorstAverage
Time ComplexityO(Nlog⁡N)O(N \log N)O(NlogN)O(Nlog⁡N)O(N \log N)O(NlogN)
Space ComplexityO(N)O(N)O(N)O(N)O(N)O(N)

# Time Complexity

The array is divided in half log⁡2N\log_2 Nlog2​N times. At each level of the recursion tree, merging the subarrays touches every element exactly once, taking O(N)O(N)O(N) time. Thus, the total time is strictly O(Nlog⁡N)O(N \log N)O(NlogN).

# Space Complexity

We allocate a single auxiliary array of size NNN to facilitate the merging process. The recursive call stack goes log⁡N\log NlogN deep. Total space is O(N)+O(log⁡N)=O(N)O(N) + O(\log N) = O(N)O(N)+O(logN)=O(N).

# Code

class Solution {
    public long numberOfInversions(int[] nums) {
        if (nums == null || nums.length < 2) return 0;
        // Allocate temp array ONCE to avoid GC thrashing during recursion
        int[] temp = new int[nums.length];
        return mergeSortAndCount(nums, temp, 0, nums.length - 1);
    }
 
    private long mergeSortAndCount(int[] nums, int[] temp, int start, int end) {
        if (start >= end) return 0;
 
        int mid = start + (end - start) / 2;
 
        long inversions = 0;
        inversions += mergeSortAndCount(nums, temp, start, mid);
        inversions += mergeSortAndCount(nums, temp, mid + 1, end);
        inversions += mergeAndCount(nums, temp, start, mid, end);
        
        return inversions;
    }
 
    private long mergeAndCount(int[] nums, int[] temp, int start, int mid, int end) {
        int i = start, j = mid + 1, t = start;
        long inversions = 0;
 
        while (i <= mid && j <= end) {
            if (nums[i] <= nums[j]) {
                temp[t++] = nums[i++];
            } else {
                // If nums[i] &gt; nums[j], all elements from i to mid are &gt; nums[j]
                inversions += (mid - i + 1);
                temp[t++] = nums[j++]; 
            }
        }
 
        while (i &lt;= mid) temp[t++] = nums[i++];
        while (j &lt;= end) temp[t++] = nums[j++];        
 
        for (i = start; i <= end; i++) nums[i] = temp[i];
        
        return inversions;
    }  
}

# Caveats

  • Integer Overflow: The maximum number of inversions in a strictly descending array of size NNN is N(N−1)2\frac{N(N-1)}{2}2N(N−1)​. For N=105N = 10^5N=105, this is roughly 5×1095 \times 10^95×109, which exceeds the 32-bit Integer.MAX_VALUE (2.14×1092.14 \times 10^92.14×109). The return type and internal counters must be long.
  • Pre-allocating Arrays: Never use new int[] inside the recursive merge function. It works mathematically, but in an enterprise environment, dynamically allocating and destroying thousands of arrays during an O(Nlog⁡N)O(N \log N)O(NlogN) operation causes catastrophic garbage collection pauses.
  • Stability: The comparison nums[i] <= nums[j] is vital. Using < would incorrectly count identical elements as inversions.
  • Large Inputs: Always use long for the count; int will overflow for n &gt; 65,536 in a worst-case scenario (descending order).
  • Data Modification: This algorithm sorts the input array in-place. If the original order must be preserved, a copy must be made first.

# Concepts to Think About

  • Alternative (Fenwick Tree / BIT): You can also solve this by iterating from right to left, querying a Binary Indexed Tree for "how many numbers smaller than nums[i] have I seen so far?", and then updating the tree. This is also O(Nlog⁡N)O(N \log N)O(NlogN) but requires coordinate compression if the numbers are large or negative.
  • Stability: Merge sort is a stable sort. The condition nums[i] &lt;= nums[j] ensures that equal elements maintain their relative order, which is why we don't count an inversion for equal elements.
  • Sorted List / AVL Trees: Inserting into a balanced BST and counting elements to the right can also count inversions.
  • Relationship to Bubble Sort: The inversion count is equal to the number of adjacent swaps Bubble Sort would perform.
  • Standardized Space: Why is O(n)O(n)O(n) space necessary for merging? (Hint: In-place merging exists but is O(n2)O(n^2)O(n2) or extremely complex).

# Logical Follow-up

Question: What if the problem was "Reverse Pairs" (LeetCode 493), where an inversion is strictly defined as nums[i] &gt; 2 * nums[j] and i &lt; j?

Solution: We use the exact same Merge Sort structure. However, we can no longer merge and count in the same step. Why? Because the condition for merging (nums[i] <= nums[j]) is different from the condition for counting (nums[i] &gt; 2 * nums[j]). Before the standard merge step, we write a separate O(N)O(N)O(N) while loop that iterates through the left array and finds how many elements in the right array satisfy the &gt; 2 * nums[j] condition. Then we merge normally. Overall time remains O(Nlog⁡N)O(N \log N)O(NlogN).

Question: Can we solve this in O(nlog⁡n)O(n \log n)O(nlogn) time with O(1)O(1)O(1) auxiliary space?

Solution: Only if we use an in-place merge sort (like the "Gap Method" or Block Merge Sort), which are significantly more complex and often have higher constant factors. In a standard interview, O(n)O(n)O(n) is the expected space complexity.

PreviousThe Ultimate Array Pattern PlaybookNextFind The Repeating And Missing Number
CONTENTS
QuestionSolutionPatternHow to IdentifyDescriptionThe IntuitionComplexityCodeCaveatsConcepts to Think AboutLogical Follow-up