Uber: Driver Names as Shown in the Rider App — SQL Problem
For privacy the rider app never shows a driver's full name: it shows the first name, a space, the first letter of the last name and a full stop — Rahul…
- Difficulty: Easy
- Topics: Strings
- Dialect: MySQL
- Problem: #977
Problem statement
For privacy the rider app never shows a driver's full name: it shows the first name, a space, the first letter of the last name and a full stop — Rahul Kumar Sharma appears as Rahul S.. A driver registered with a single name is shown exactly as registered.
Return driver_id and display_name for every driver, ordered by driver_id. Names are words separated by single spaces, with no leading or trailing spaces.
A practice scenario set at Uber: the tables and data are invented, and this is not a question from, or endorsed by, Uber.
Tables
Table: Driver
| Column | Type |
|---|---|
| driver_id | int |
| full_name | varchar |
| city | varchar |
Primary key: driver_id.
One row per driver partner; full_name is as written on the driving licence.
Examples
Example 1
Driver
| driver_id | full_name | city |
|---|---|---|
| 1 | Rahul Kumar Sharma | Bengaluru |
| 2 | Priya Nair | Kochi |
| 3 | Zara | Mumbai |
| 4 | Mohammed Farhan Khan | Hyderabad |
| 5 | Anjali Rao | Delhi |
Output
| driver_id | display_name |
|---|---|
| 1 | Rahul S. |
| 2 | Priya N. |
| 3 | Zara |
| 4 | Mohammed K. |
| 5 | Anjali R. |
How to solve Uber: Driver Names as Shown in the Rider App
The display name is assembled from two pieces of the full name: the first word, and the first letter of the last word. SUBSTRING_INDEX(full_name, ' ', 1) returns everything before the first space, and SUBSTRING_INDEX(full_name, ' ', -1) everything after the last space; LEFT(…, 1) takes that word's initial. CONCAT glues them together with a space and a full stop. Middle names fall away naturally, because only the first and the last words are read.
A single-word name needs its own branch. Without it, both SUBSTRING_INDEX calls would return the whole name and Zara would become Zara Z.. LOCATE(' ', full_name) = 0 detects the missing space, and the CASE returns the name unchanged.
The alternative does the same with positions: INSTR finds the first space for the first name, and the last space is found by searching the reversed string, then converting that position back. Both are a constant amount of string work per row.
Reference solution (MySQL)
SELECT driver_id,
CASE WHEN LOCATE(' ', full_name) = 0 THEN full_name
ELSE CONCAT(SUBSTRING_INDEX(full_name, ' ', 1), ' ', LEFT(SUBSTRING_INDEX(full_name, ' ', -1), 1), '.')
END AS display_name
FROM Driver
ORDER BY driver_idAnother way
SELECT driver_id,
IF(INSTR(full_name, ' ') = 0, full_name,
CONCAT(LEFT(full_name, INSTR(full_name, ' ') - 1), ' ',
SUBSTRING(full_name, CHAR_LENGTH(full_name) - LOCATE(' ', REVERSE(full_name)) + 2, 1), '.')) AS display_name
FROM Driver
ORDER BY driver_id← Uber: Promo Codes Nobody Has Redeemed · Uber: Airport Queue Dispatches per Terminal →