Binary Search Over Date-Filtered Content Flags
Heaps, Sorting & SearchAuto-graded · 18 test casesLast updated
Tests whether a candidate can isolate records by category and then apply binary search to efficiently locate all entries within an inclusive date window.
Content Flag Log Search
A moderation system stores a running log of flagged content items. Each entry records an item identifier, the flag category, and the date the flag was raised.
Each log entry is a dictionary with these keys:
pin_id— integer identifier of the flagged itemtype— string describing the kind of flag (e.g."spam","privacy","child")violation_date— date string inYYYY-MM-DDformat
Given the full log, a target flag type, and an inclusive date range, return the pin_id of every entry whose type matches the target and whose violation_date falls within [window_start, window_end] (both endpoints included).
Requirements
- Use binary search to locate the date boundaries rather than scanning the filtered list linearly.
- Results must be ordered by
violation_dateascending. Among entries sharing the same date, preserve their original order in the input list (stable sort). - Do not deduplicate: if the same
pin_idappears in multiple matching entries, include it once per matching entry. - Return an empty list when nothing matches, when the log is empty, or when
window_start > window_end.
Constraints
0 <= len(log) <= 10^5pin_idis a non-negative integer.- All
violation_datevalues are zero-padded ISO 8601 strings (YYYY-MM-DD). Lexicographic string comparison is equivalent to chronological comparison for this format. window_startandwindow_endare also zero-padded ISO 8601 strings.- The input log is not guaranteed to be pre-sorted.
Examples
Example 1
Input: search_flag_log([{'pin_id': 0, 'type': 'spam', 'violation_date': '2022-01-03'}, {'pin_id': 1, 'type': 'spam', 'violation_date': '2022-01-03'}, {'pin_id': 0, 'type': 'privacy', 'violation_date': '2022-01-03'}, {'pin_id': 2, 'type': 'child', 'violation_date': '2022-02-06'}, {'pin_id': 3, 'type': 'spam', 'violation_date': '2022-02-10'}], 'spam', '2022-01-03', '2022-02-10')
Output: [0, 1, 3]
Example 2
Input: search_flag_log([{'pin_id': 0, 'type': 'spam', 'violation_date': '2022-01-03'}, {'pin_id': 1, 'type': 'spam', 'violation_date': '2022-01-03'}, {'pin_id': 0, 'type': 'privacy', 'violation_date': '2022-01-03'}, {'pin_id': 2, 'type': 'child', 'violation_date': '2022-02-06'}, {'pin_id': 3, 'type': 'spam', 'violation_date': '2022-02-10'}], 'privacy', '2022-01-01', '2022-01-31')
Output: [0]
Example 3
Input: search_flag_log([{'pin_id': 4, 'type': 'spam', 'violation_date': '2022-03-01'}, {'pin_id': 4, 'type': 'spam', 'violation_date': '2022-03-02'}, {'pin_id': 5, 'type': 'spam', 'violation_date': '2022-03-02'}, {'pin_id': 6, 'type': 'privacy', 'violation_date': '2022-03-03'}], 'spam', '2022-03-02', '2022-03-02')
Output: [4, 5]
Hints
Hint 1
Filter the log down to only the entries matching the target type before doing anything else — binary search requires the array to be sorted on the key you are searching, and mixing multiple types would break that ordering.
Hint 2
Build a parallel list of just the date strings from the filtered, sorted entries. Then use bisect_left on window_start to find the first included index and bisect_right on window_end to find the exclusive upper bound — this is the standard pattern for an inclusive [a, b] window.
Hint 3
Think carefully about why bisect_left and bisect_right are paired the way they are. Using bisect_right on the lower bound or bisect_left on the upper bound would silently exclude entries that fall exactly on a boundary date.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight
Binary search only works on a sorted sequence. The log mixes every flag type together, so a direct binary search on dates across the whole log would miss records or include wrong ones. The fix is to filter first, then sort, then search.
Once the list contains only entries of the target type and is sorted by date, the entries satisfying date >= window_start form a contiguous suffix and the entries satisfying date <= window_end form a contiguous prefix. The intersection of those two is a single contiguous slice — exactly what binary search can locate in O(log m).
Step-by-step
-
Filter by type. Walk the full log once and keep only entries where
typematches. This is O(n). -
Sort by date. Sort the filtered list on
violation_date. Python's Timsort is stable, so entries with identical dates remain in their original input order. If the input happened to be sorted already, Timsort detects that and runs in O(m). In the general case it is O(m log m). -
Build a parallel date list. Extract just the
violation_datestrings into a separate list sobisecthas a clean array to work on. -
Binary search for both boundaries.
bisect.bisect_left(dates, window_start)returns the leftmost index where a date ≥window_startappears — this is the first included entry.bisect.bisect_right(dates, window_end)returns the index one past the last date ≤window_end— this is the exclusive upper bound.- The matching slice is
[left, right).
The
bisect_left/bisect_rightpairing is deliberate. Using the same variant for both boundaries would silently exclude any entry whose date falls exactly on a boundary. -
Collect results. Slice the filtered list and return the
pin_idvalues. Ifwindow_start > window_end,left >= rightand the result is naturally[]with no special-casing needed.
Why string comparison works
All dates are zero-padded ISO 8601 strings (YYYY-MM-DD). Lexicographic order on such strings is identical to chronological order, so Python's default string comparison is safe here.
Complexity
Let n = total log entries, m = entries matching the flag type, k = entries in the result.
| Step | Time | Space |
|---|---|---|
| Filter | O(n) | O(m) |
| Sort | O(m log m) | O(1) auxiliary |
| Build date list | O(m) | O(m) |
| Two bisects | O(log m) | O(1) |
| Build output | O(k) | O(k) |
Overall: O(n + m log m) time, O(m) space.
Note that a single call still scans all n records during the filter step. The binary search only becomes a clear win when the filtered, sorted structure is built once and reused across many queries — for example, as a precomputed dictionary mapping each type to its sorted list of (date, pin_id) pairs. Each subsequent query then costs just O(log m + k).
Reference solution
from typing import List, Dict
import bisect
def search_flag_log(log: List[Dict], flag_type: str, window_start: str, window_end: str) -> List[int]:
# 1. Keep only entries for the requested flag type, then sort by date.
# Python's sort is stable, so equal dates keep their original input order.
filtered = [entry for entry in log if entry['type'] == flag_type]
filtered.sort(key=lambda x: x['violation_date'])
# 2. Build a parallel list of date strings — the key bisect will search on.
dates = [entry['violation_date'] for entry in filtered]
# 3. Locate the inclusive window [window_start, window_end]:
# bisect_left -> first index where date >= window_start
# bisect_right -> first index where date > window_end
left = bisect.bisect_left(dates, window_start)
right = bisect.bisect_right(dates, window_end)
# 4. Every index in [left, right) is inside the window.
return [filtered[i]['pin_id'] for i in range(left, right)]
Edge cases to keep in mind
- Empty log or no matching type:
filteredis empty, both bisects return 0, result is[]. - Boundary dates included: an entry dated exactly
window_startorwindow_endis always included because ofbisect_left/bisect_right. - Inverted range (
window_start > window_end):left >= right, slice is empty, no special handling needed. - Window entirely outside the data: both bisects land at the same index, result is
[]. - Duplicate pin_ids: the same
pin_idappears once per matching log entry; no deduplication is performed.