FastPrepImplement Printf
Problem · String

Implement Printf

Learn this problem
MediumNvidia logoNvidiaFULLTIMEONSITE INTERVIEW

Problem statement

Implement a small formatted-text function. For this exercise, assume the format pattern supports exactly %s, %d, and %%.

  • Copy each ordinary character in pattern unchanged.
  • %s consumes the next string in values and inserts it verbatim.
  • %d consumes the next string, which represents a signed 32-bit decimal integer. Insert its canonical decimal representation: omit a leading plus sign and redundant leading zeroes, and write zero as 0.
  • %% inserts one literal percent sign and consumes no value.
  • Process only the original pattern. Percent signs inside an inserted value are ordinary output characters and are never interpreted again.

Return the resulting string. Every pattern is valid, every percent sign begins one of the three supported two-character directives, and the number of consuming directives equals values.length. Width, precision, and other directives are outside this exercise.

Function

formatPrintf(pattern: String, values: String[]) → String

Examples

Example 1

pattern = "%s scored %d%%"values = ["Ada","+007"]return = "Ada scored 7%"

The two consuming directives insert Ada and normalized integer 7. The final escape inserts a percent sign.

Example 2

pattern = "[%s] %d"values = ["%d%%","-0000"]return = "[%d%%] 0"

The inserted percent signs remain literal, while negative zero becomes 0.

Example 3

pattern = "%%%%"values = []return = "%%"

Two percent escapes produce two literal percent signs without consuming any values.

Constraints

  • 0 <= pattern.length <= 10^5.
  • 0 <= values.length <= 10^5.
  • All strings contain only printable ASCII characters; an argument used by %s may be empty.
  • An argument used by %d contains an optional + or - followed by between 1 and 10 decimal digits, and its value lies from -2147483648 through 2147483647.
  • The total number of characters across all values is at most 10^5, and the returned string has at most 2 * 10^5 characters.

More Nvidia problems

drafts saved locally
public String formatPrintf(String pattern, String[] values) {
    // Write your code here.
}
pattern"%s scored %d%%"
values["Ada","+007"]
expected"Ada scored 7%"
checking account