Solve order-statistics and XOR-triplet problems
Company: Google
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Onsite
Quick Answer: This multi-part question evaluates skills in order-statistics and efficient counting for array inversion-like problems, alongside bitwise manipulation and prefix-XOR reasoning for combinatorial triplet counting.
Part 1: Count Smaller Elements to the Right
Constraints
- 0 <= len(nums) <= 10^5
- -10^9 <= nums[i] <= 10^9
Examples
Input: ([5, 2, 6, 1],)
Expected Output: [2, 1, 1, 0]
Explanation: For 5, the smaller elements to its right are 2 and 1. For 2, only 1 is smaller. For 6, only 1 is smaller.
Input: ([-1, -1],)
Expected Output: [0, 0]
Explanation: Equal values are not strictly smaller.
Input: ([],)
Expected Output: []
Explanation: Edge case: empty input returns an empty list.
Input: ([42],)
Expected Output: [0]
Explanation: A single element has nothing to its right.
Input: ([3, 2, 2, 6, 1],)
Expected Output: [3, 1, 1, 1, 0]
Explanation: For 3, the smaller values to the right are 2, 2, and 1. Each 2 has only 1 smaller element to its right.
Hints
- If you scan from right to left, every element you have already seen is to the right of the current index.
- Because values can be negative and large, map them to sorted ranks before using a Fenwick tree or segment tree.
Part 2: Count Triplets with XOR Inequality
Constraints
- 0 <= len(nums) <= 10^5
- 0 <= nums[i] <= 10^9
- The answer fits in a signed 64-bit integer
Examples
Input: ([],)
Expected Output: 0
Explanation: Edge case: there are no triplets in an empty array.
Input: ([0],)
Expected Output: 0
Explanation: For the only triplet (1,1,1), both sides are equal to 0, so the inequality is false.
Input: ([1, 1],)
Expected Output: 2
Explanation: The valid triplets are (1,1,2) and (1,2,2).
Input: ([2, 3, 1],)
Expected Output: 6
Explanation: There are 6 valid triplets after evaluating all x <= y <= z combinations.
Input: ([1, 2, 3],)
Expected Output: 5
Explanation: Five triplets satisfy the inequality.
Hints
- Write every subarray XOR using prefix XORs P[k] = nums[0] XOR nums[1] XOR ... XOR nums[k-1].
- For a fixed y, let b be the highest set bit of nums[y]. Comparing T and T XOR nums[y] depends first on bit b.