oneby7

2-D Dynamic Programming Two strings

571. Minimum ASCII Delete Sum for Two Strings

Medium

You are given two strings, s1 and s2. You may delete characters from either string until the two strings are equal. Deleting a character costs its ASCII code: a costs 97, b costs 98, and so on up to 122 for z.

Return the smallest total cost that makes the two strings equal. Deleting every character leaves two empty strings, which are equal, so there is always an answer.

Example 1

Input: s1 = "silent", s2 = "listen"

Output: 658

Explanation: Delete i, l and t from both strings, and both become "sen". The cost is 2 · (105 + 108 + 116) = 658. Keeping "len" also leaves three letters, but it deletes s instead of l and costs 672.

Example 2

Input: s1 = "cab", s2 = "fig"

Output: 604

Explanation: The strings share no letter, so every letter goes: 99 + 97 + 98 + 102 + 105 + 103 = 604.

Example 3

Input: s1 = "art", s2 = "party"

Output: 233

Explanation: Delete p (112) and y (121) from "party". Nothing needs to be deleted from "art".

Check your understanding

Work out the answer for this input before you write any code.

s1 = "zzzzaaaaa", s2 = "aaaaazzzz"

Constraints

  • 1 ≤ s1.length, s2.length ≤ 3000
  • s1 and s2 hold only lowercase English letters.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.