Longest Word in Dictionary through Deleting

MediumTwo Pointerstwo pointers

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given a string s and a list of strings dictionary, find the longest dictionary word that can be formed by deleting some characters of s (possibly none), without reordering the ones that remain. In other words, the word must be a **subsequence** of s. If several words have that maximum length, return the lexicographically smallest one. If no dictionary word is a subsequence of s, return the empty string "".

Examples

Input: s = "abpcplea", dictionary = ["ale","apple","monkey","plea"]
Output: "apple"
"apple" is a subsequence of s and is the longest valid word.
Input: s = "abpcplea", dictionary = ["a","b","c"]
Output: "a"
All three words are valid and length 1; "a" is lexicographically smallest.

Constraints

  • 1 <= s.length <= 1000
  • 1 <= dictionary.length <= 1000
  • 1 <= dictionary[i].length <= 1000
  • `s` and every `dictionary[i]` consist of lowercase English letters.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More two pointers problems