{x}
blog image

Maximum Font to Fit a Sentence in a Screen

Solution Explanation

This problem asks to find the maximum font size that allows a given text to fit within a screen of specified width and height. We are provided with an array of available font sizes and a FontInfo interface to query the width and height of characters at a given font size.

The key insight is to use binary search. Because the font sizes are sorted in ascending order, and both the width and height of characters increase monotonically with the font size, we can efficiently search for the largest font size that satisfies the constraints.

Algorithm:

  1. check(size) function: This helper function determines if a given size (font size) allows the text to fit on the screen. It first checks if the height at this size exceeds the screen height h. If it does, the function immediately returns false. Otherwise, it calculates the total width of the text at the given size by summing the widths of individual characters using fontInfo.getWidth(). If the total width is less than or equal to the screen width w, it means the text fits, and the function returns true; otherwise, it returns false.

  2. Binary Search: The main part of the algorithm performs a binary search on the fonts array. It initializes left to 0 and right to len(fonts) - 1. The search iteratively narrows down the search space by checking the middle element mid. If check(fonts[mid]) is true (meaning the text fits at fonts[mid]), then the maximum font size must be at least fonts[mid], so we update left = mid. Otherwise, we update right = mid - 1. The loop continues until left < right is no longer true.

  3. Result: After the binary search, left points to the index of the largest font size that satisfies the conditions. We then check one last time if check(fonts[left]) is true, and return fonts[left] if it is, and -1 otherwise, indicating that no font size allows the text to fit.

Time Complexity: O(N log M), where N is the length of the text and M is the number of font sizes. The check function takes O(N) time to calculate the total width. The binary search takes O(log M) iterations.

Space Complexity: O(1). The algorithm uses a constant amount of extra space.

Code Explanation (Python):

The Python code directly implements the algorithm described above. The check function is defined as an inner function for better readability and encapsulation. The binary search efficiently finds the maximum font size. The final check ensures a correct result even if the text doesn't fit with any font sizes.

Code Explanation (Other Languages):

The Java, C++, and JavaScript codes follow the same logic and algorithm. They implement the check function and the binary search similarly, adapting the syntax to their respective languages. The core idea of using binary search to efficiently find the maximum font size remains the same.