#1618
Medium Algorithms Maximum font to fit a sentence in a screen
Array String Binary Search Interactive
62.0% acceptance
Mar 31, 2026
114
22
You are given a string text. We want to display text on a screen of width w and height h. You can choose any font size from array fonts, which contains the available font sizes in ascending order.
You can use the FontInfo interface to get the width and height of any character at any available font size.
The FontInfo interface is defined as such:
interface FontInfo {
// Returns the width of character ch on the screen using font size fontSize.
// O(1) per call
public int getWidth(int fontSize, char ch);
// Returns the height of any character on the screen using font size fontSize.
// O(1) per call
public int getHeight(int fontSize);
}
The calculated width of text for some fontSize is the sum of every getWidth(fontSize, text[i]) call for each 0 <= i < text.length (0-indexed). The calculated height of text for some fontSize is getHeight(fontSize). Note that text is displayed on a single line.
It is guaranteed that FontInfo will return the same value if you call getHeight or getWidth with the same parameters.
It is also guaranteed that for any font size fontSize and any character ch:
getHeight(fontSize) <= getHeight(fontSize+1)
getWidth(fontSize, ch) <= getWidth(fontSize+1, ch)
Return the maximum font size you can use to display text on the screen. If text cannot fit on the display with any font size, return -1.
Solution
C++
Time O(n)
Space O(1)
/**
* // This is the FontInfo's API interface.
* // You should not implement it, or speculate about its implementation
* class FontInfo {
* public:
* // Return the width of char ch when fontSize is used.
* int getWidth(int fontSize, char ch);
*
* // Return Height of any char when fontSize is used.
* int getHeight(int fontSize)
* };
*/
class Solution {
public:
int maxFont(string text, int w, int h, vector<int>& fonts, FontInfo fontInfo) {
int lo = 0, hi = fonts.size() - 1, ans = -1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (fits(text, w, h, fonts[mid], fontInfo)) {
ans = fonts[mid];
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
private:
bool fits(const string& text, int w, int h, int fontSize, FontInfo& fontInfo) {
if (fontInfo.getHeight(fontSize) > h) return false;
long long totalWidth = 0;
for (char c : text) {
totalWidth += fontInfo.getWidth(fontSize, c);
if (totalWidth > w) return false;
}
return true;
}
};