For Each Price, Count Later Days with a Strictly Lower Price
Last updated: November 29, 2026
Quick Overview
Given a list of daily prices, return for each day the number of later days whose price is strictly lower than that day's price, in O(n log n) time.
0
0
0 solved
Given a list of daily prices, return for each day the number of later days whose price is strictly lower than that day's price, in O(n log n) time.
A Google onsite question framed around Shopping price history, testing inversion counting with a clever data structure. The interviewer expects a Fenwick tree over compressed values or a merge sort with index tracking, and often asks for both.
What the Interviewer Expects
- Rules out O(n^2) and explains the inversion-counting connection
- Coordinate compresses values to ranks
- Scans right to left querying a Fenwick tree for counts of smaller ranks
- Handles duplicates as not strictly smaller
- Mentions the merge-sort alternative and its trade-offs
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Count later days with a price strictly higher instead, or within a band [p - d, p + d].
- Prices arrive online and queries ask about the last W days.
- Return the total number of inversions in O(n log n) without per-element output.
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Input: list of integers (any range, duplicates allowed).
- Output: list where
out[i] = #{j > i : a[j] < a[i]}....
High-Level Design
Compress values to ranks 1..m in sorted order so the Fenwick tree has size m regardless of value range. Walk from the right end to the left. For position i, the Fenwick tree holds counts of ranks for ...