← Problems80. First and last touch attributionMediumPySpark
00:00 / 25:00

First and last touch attribution

MediumNot attempted yetAsked at Adobe, Amazon, Google

Marketing wants to know which channel introduced a customer and which one was in front of them when they bought.

Input

touches touch_id bigint -- unique conversion_id bigint channel string -- 'SEARCH', 'EMAIL', 'SOCIAL', 'DIRECT', 'AFFILIATE' touched_at string -- ISO-8601 UTC, 'YYYY-MM-DDTHH:MM:SSZ'

Output

One row per conversion_id, with the columns:

  • conversion_id
  • first_channel — the channel of the earliest touch
  • last_channel — the channel of the latest touch
  • touch_count

Order touches by touched_at; where two share one, the smaller touch_id is the earlier.

Example

touch_idconversion_idchanneltouched_at
1100SEARCH2024-01-01T10:00:00Z
2100EMAIL2024-01-02T10:00:00Z
3100DIRECT2024-01-03T10:00:00Z
conversion_idfirst_channellast_channeltouch_count
100SEARCHDIRECT3

Constraints

  • A conversion with one touch has that channel as both first and last.
  • last_value over an ordered window without an explicit frame returns the current row, not the last one. It is right on the final row of each partition and wrong on every other, which is why it usually looks correct.
  • Row order is not graded. Column names and their order are.

Example 1three touches, first and last differ

Input · touches
channeltouch_idtouched_atconversion_id
SEARCH12024-01-01T10:00:00Z100
EMAIL22024-01-02T10:00:00Z100
DIRECT32024-01-03T10:00:00Z100
Output
conversion_idfirst_channellast_channeltouch_count
100SEARCHDIRECT3

Example 2a single touch is both the first and the last

Input · touches
channeltouch_idtouched_atconversion_id
SOCIAL12024-02-01T00:00:00Z200
SEARCH22024-02-02T00:00:00Z201
SEARCH32024-02-03T00:00:00Z201
Output
conversion_idfirst_channellast_channeltouch_count
200SOCIALSOCIAL1
201SEARCHSEARCH2

Topics

window functionsaggregation

Similar problems

Community-reported interview topic. Not an official company question and no affiliation is implied.

solution.py
Loading editor…
Draft not saved yet · Spaces 4 · UTF-8⌘↵ run ⌘⇧↵ submit
Nothing run yet

Run against the public tests, or submit to score against all of them.