Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 1283 · Binary Search on Answer

Find the Smallest Divisor Given a Threshold

LeetCode 1283 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

Monotonic total ⇒ binary search on d.

ಮಧ್ಯಮArrayBinary Search
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು Find the Smallest Divisor Given a Threshold (LeetCode 1283) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Binary Search on Answer ಪ್ಯಾಟರ್ನ್‌ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.

ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್‌ನಲ್ಲಿದೆ.

Intuition

A bigger divisor makes every ceil(num / d) smaller, so the total only goes down as d grows. Binary search the smallest divisor whose total is within the threshold.

Approach

  1. 1

    Search d in [1, max(nums)].

  2. 2

    total(d) = Σ ceil(num / d).

  3. 3

    Within threshold → try smaller d; else larger.

ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ

Binary search on divisorPythonO(n log M) time
class Solution:
    def smallestDivisor(self, nums: List[int], threshold: int) -> int:
        def isTotalSumWithinThreshold(mid):
            totalSum=0
            for num in nums:
                totalSum+=math.ceil(num/mid)
            if totalSum<=threshold:
                return True
            else:
                False
        low =1
        high = max(nums)
        while low<=high:
            mid = (low+high)//2
            withinThreshold = isTotalSumWithinThreshold(mid)
            if withinThreshold:
                high = mid-1
            else:
                low=mid+1
        return low
ಸ್ಟೆಪ್-ಥ್ರೂ ಲೋಡ್ ಆಗುತ್ತಿದೆ…

Find the Smallest Divisor Given a Threshold — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು

Find the Smallest Divisor Given a Threshold ಹಿಂದಿನ intuition ಏನು?

A bigger divisor makes every ceil(num / d) smaller, so the total only goes down as d grows. Binary search the smallest divisor whose total is within the threshold.

Find the Smallest Divisor Given a Threshold (LeetCode 1283) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?

1. Search d in [1, max(nums)]. 2. total(d) = Σ ceil(num / d). 3. Within threshold → try smaller d; else larger.

Find the Smallest Divisor Given a Threshold ನ time ಮತ್ತು space complexity ಎಷ್ಟು?

Time: O(n log M). Space: O(1). (Accepted approach: Binary search on divisor.)

Find the Smallest Divisor Given a Threshold ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?

The helper falls through to None when the total is too big — None is falsy, so it still works, but return False explicitly.