Problem · String

Highlight and Rank Overlapping Citations

Learn this problem
HardHarvey logoHarveyFULLTIMEONSITE INTERVIEW

Problem statement

Given an output string text and a list of source phrases sources, find every exact word-level occurrence of every source phrase in text. Words contain only letters and digits, and adjacent words are separated by exactly one space. Matching is case-sensitive and must use complete words, so network does not match a word inside networking.

Each occurrence covers a half-open span of words. Merge all occurrences whose spans overlap, directly or transitively, into a maximal highlighted region. Merely adjacent spans do not overlap. Wrap each merged region in <yellow> and </yellow>.

After each highlighted region, append one citation [i] for every distinct source index i that has an occurrence participating in that region. Order those indices by the total number of exact occurrences of that source across the entire text, from greatest to least. Break equal-frequency ties by smaller source index.

Keep exactly one space between the original words and inserted highlighted regions. If no source phrase occurs, return text unchanged.

Function

highlightAndRankCitations(text: String, sources: String[]) → String

Examples

Example 1

text = "the quick brown fox"sources = ["the quick","quick brown"]return = "<yellow>the quick brown</yellow>[0][1] fox"

The phrases cover word spans [0, 2) and [1, 3). They overlap and merge into the quick brown. Each source occurs once, so the index tie is resolved as [0][1].

Example 2

text = "red blue green red blue red"sources = ["red blue","blue green","red"]return = "<yellow>red blue green</yellow>[2][0][1] <yellow>red blue</yellow>[2][0] <yellow>red</yellow>[2]"

Across the whole text, source 2 occurs three times, source 0 twice, and source 1 once. Those totals determine citation order inside every merged region. The last one-word occurrence is adjacent to, but does not overlap, the preceding phrase.

Example 3

text = "aa aaab x"sources = ["aa","aaab","aa aaab"]return = "<yellow>aa aaab</yellow>[0][1][2] x"

Word-level matching keeps aa separate from aaab. The two single-word matches overlap the two-word source span, so all three belong to one region. Their global counts tie.

Constraints

  • 1 <= text.length <= 100000
  • 1 <= sources.length <= 2000
  • 1 <= sources[i].length
  • text and every sources[i] contain only letters, digits, and single spaces between words.
  • The total number of exact source occurrences in text is at most 200000.

More Harvey problems

drafts saved locally
public String highlightAndRankCitations(String text, String[] sources) {
    // Write your code here.
}
text"the quick brown fox"
sources["the quick","quick brown"]
expected"<yellow>the quick brown</yellow>[0][1] fox"
checking account