FastPrepLargest K-Digit Subsequence

Largest K-Digit Subsequence

Google logoGoogle● MediumINTERNONSITE INTERVIEW
Learn

Problem statement

You are given a decimal digit string digits and an integer k. Select exactly k digits while preserving their relative order.

Return the lexicographically largest length-k digit string that can be formed. Leading zeroes are retained.

Function

largestKDigitSubsequence(digits: String, k: int) → String

Examples

Example 1

digits = "1924"k = 2return = "94"

Choosing 9 and 4 gives the largest two-digit subsequence.

Example 2

digits = "4177252841"k = 4return = "7841"

The selected digits 7, 8, 4, and 1 occur at increasing indices and form the maximum possible four-digit string.

Example 3

digits = "0012"k = 3return = "012"

The first zero can be skipped, but the leading zero in the selected subsequence is retained.

Constraints

  • 1 <= digits.length <= 200000.
  • 1 <= k <= digits.length.
  • digits contains only characters from '0' through '9'.

More Google problems

See Google hiring insights
public String largestKDigitSubsequence(String digits, int k) {
    // Write your code here.
}
digits"1924"
k2
expected"94"
Checking account…