Skip to main content

Largest Integer With Given Digit Sum - Solution & Explanation

EasyMathGreedy6 min read
Practice this problem

Problem Statement

You are given two non-negative integers n and s.

Return the largest integer that has at most n digits and whose sum of digits is s. If no such integer exists, return -1.

 

Example 1:

Input: n = 2, s = 9

Output: 90

Explanation:

The largest integer with at most 2 digits that has a sum of digits of 9 is 90.

Example 2:

Input: n = 2, s = 19

Output: -1

Explanation:

There is no integer with at most 2 digits that has a sum of digits of 19, so the answer is -1.

Example 3:

Input: n = 5, s = 0

Output: 0

Explanation:

The only non-negative integer whose digits sum to 0 is 0.

 

Constraints:

  • 1 <= n <= 5
  • 0 <= s <= 100

Approach Overview

Problem Overview: You need to construct the numerically largest integer whose digits add up to a given target sum. The key observation is that larger leading digits always produce a larger overall number, so the solution depends on how you distribute the digit sum efficiently.

Approach 1: Brute Force Enumeration (Exponential Time)

This approach generates every possible number whose digit sum matches the target and keeps track of the maximum value found. You can use recursion or backtracking to try all digit combinations from 0 to 9. While this proves correctness for small inputs, the search space grows exponentially because each position branches into multiple digit choices. Time complexity is O(10^n) in the worst case, and space complexity is O(n) for recursion depth.

Approach 2: Greedy Construction (O(n))

The optimal solution uses a greedy strategy. To maximize the integer, you place the largest possible digit at every position. Repeatedly append 9 while the remaining sum is at least 9, then append the leftover value if it is greater than 0. This works because any smaller leading digit would reduce the final number regardless of later digits. Time complexity is O(n), where n is the number of digits in the result, and space complexity is O(n) for storing the output string.

The greedy solution is a classic optimization pattern from Greedy problems. Instead of exploring all combinations, you make the locally optimal choice at each step and still guarantee the globally largest number. Since each iteration reduces the remaining sum, the implementation stays simple and efficient.

Approach 3: String Builder Optimization (O(n))

For languages where repeated string concatenation is expensive, use a mutable structure such as StringBuilder in Java or a character list in Python. The logic stays identical to the greedy method, but append operations become more efficient for large digit sums. This version is preferred in production-quality implementations because it avoids unnecessary string copies. Time complexity remains O(n) and space complexity remains O(n).

Problems like this often appear alongside Math and Implementation patterns because the challenge is mostly about numeric reasoning and constructing the output correctly.

Recommended for interviews: Interviewers expect the greedy solution because it demonstrates that you can recognize optimal digit placement without brute force search. Mentioning the exhaustive recursive approach first shows problem-solving depth, but implementing the greedy construction shows stronger optimization skills.

Solution

If n times 9 < s, even filling every digit with 9 cannot reach digit sum s, so return -1.

Otherwise, to maximize the integer, assign as large a digit as possible to higher places. Construct n digits from high to low: each digit takes min(s, 9), then subtract that value from s. The resulting integer is the answer (if s = 0, the result is 0).

The time complexity is O(n), and the space complexity is O(1).

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force EnumerationO(10^n)O(n)Useful for validating small cases or understanding the search space
Greedy ConstructionO(n)O(n)Best general solution for interviews and competitive programming
Greedy with String BuilderO(n)O(n)Preferred when output length is large and string concatenation is costly

Video Solution

Largest Integer With Given Digit Sum | Leetcode 4000 | Weekly Contest 512 • Prince Gupta Study • 134 views views

Watch 3 more video solutions →

Frequently Asked Questions

Is Largest Integer With Given Digit Sum easy or hard?
Largest Integer With Given Digit Sum is generally considered an Easy problem because the core idea is a straightforward greedy observation. The challenge is recognizing that larger leading digits always produce a larger number overall.
Largest Integer With Given Digit Sum Python/Java solution
Python solutions typically use a list of characters followed by ''.join() for efficiency. Java solutions usually rely on StringBuilder to avoid repeated string copies. Both implementations follow the same greedy logic and run in O(n) time.
How to solve Largest Integer With Given Digit Sum in O(n)?
Use a greedy construction strategy. While the remaining digit sum is at least 9, append the digit 9 to the answer and subtract 9 from the sum. After the loop, append the remaining value if it is greater than 0. The algorithm processes each digit once, giving O(n) complexity.
What is the best approach for Largest Integer With Given Digit Sum?
The greedy approach is the best solution because placing the largest possible digit first always maximizes the final integer. Repeatedly append 9 while reducing the remaining digit sum, then append the leftover digit if needed. This runs in O(n) time with O(n) space.
Is Largest Integer With Given Digit Sum asked at Google/Amazon/Meta?
Greedy digit construction problems commonly appear in coding interviews at large tech companies because they test optimization and numeric reasoning. Variants of this problem have shown up in interview prep sets for Amazon, Google, and Meta-style rounds.
What data structure is used in Largest Integer With Given Digit Sum?
Most solutions use a string builder, character array, or list to efficiently append digits while constructing the answer. No advanced data structure is required because the algorithm depends mainly on greedy selection.
What is the time complexity of Largest Integer With Given Digit Sum?
The optimal greedy solution runs in O(n) time, where n is the number of digits in the constructed integer. Each iteration appends one digit and decreases the remaining sum. Space complexity is also O(n) because the output string must be stored.

Ready to solve this problem?

Practice Largest Integer With Given Digit Sum with our built-in code editor and test cases.

Practice on FleetCode