KatInterview

Find Lexicographically Smallest Expression to Match Target

Dynamic ProgrammingAuto-graded · 28 test cases
MediumAuto-gradedDynamic Programmingdynamic-programmingrecursionstrings

Last updated

Tests interval dynamic programming to build fully parenthesized expressions using all numbers in order with +, -, * operators to reach a target value.

You are given a list of non-negative integers numbers and an integer target_value. Your task is to construct a mathematical expression that uses every integer from numbers exactly once, in their original order, and evaluates to target_value.

Between each pair of consecutive numbers, you must place exactly one operator from the set {+, -, *}. Every operation must be fully parenthesized, meaning each operator application is wrapped in parentheses. For example, with three numbers, valid expressions include ((a+b)*c) and (a+(b*c)).

Return the lexicographically smallest valid expression that evaluates to target_value. If no such expression exists, return an empty string.

Note: Lexicographic comparison follows standard ASCII ordering where ( < ) < * < + < - < digits.

Constraints

  • 2 <= len(numbers) <= 8
  • 0 <= numbers[i] <= 100
  • target_value is an integer (may be negative)
  • Each expression must use all numbers in their original order
  • Intermediate results may be negative or exceed the input range

Examples

Example 1

Input: find_smallest_expression([1, 2, 3], 9)

Output: '((1+2)*3)'

Example 2

Input: find_smallest_expression([2, 2], 4)

Output: '(2*2)'

Example 3

Input: find_smallest_expression([1, 2, 3], 100)

Output: ''

Example 4

Input: find_smallest_expression([7], 7)

Output: '7'

Hints

Hint 1

Think about how to break down the problem: any parenthesized expression has a root operator that splits the numbers into left and right subexpressions

Hint 2

For each subrange of numbers, track all possible values you can create and the smallest expression string for each value

Hint 3

Use interval dynamic programming: process shorter ranges first, then combine them to build longer ranges