Перейти к содержанию

First Bad Version

🇷🇺 Название: Первая плохая версия
LeetCode: first-bad-version
Временная сложность: O(log n)
Пространственная сложность: O(1)

Решение

# The isBadVersion API is already defined for you.  
# def isBadVersion(version: int) -> bool:  


class Solution:  
    def firstBadVersion(self, n: int) -> int:  
        first, last = 1, n  

        while first < last:  
            center = first + (last - first) // 2  

            if not isBadVersion(center):  
                first = center + 1  
            else:  
                last = center  

        return first

🇺🇸 Условие

You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.

Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad.

You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.

🇷🇺 Условие

Примеры

Example 1:

Input: n = 5, bad = 4
Output: 4
Explanation:
call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true
Then 4 is the first bad version.

Example 2:

Input: n = 1, bad = 1
Output: 1

{
  "examples": [
    {
      "input": {
        "n": 5,
        "bad": 4
      },
      "output": 4
    },
    {
      "input": {
        "n": 1,
        "bad": 1
      },
      "output": 1
    }
  ]
}

Ограничения

  • \(1 \leq bad \leq n \leq 2^{31} - 1\)

Потребление ресурсов

⏱ Time complexity: O(log n)

  • Алгоритм использует бинарный поиск по диапазону от 1 до n.
  • На каждом шаге сокращает интервал вдвое.
  • Максимум log₂(n) вызовов isBadVersion.

Итог: O(log n)

🧠 Space complexity: O(1)

  • Используются только несколько переменных (first, last, center).
  • Нет дополнительной памяти, зависящей от n.

Итог: O(1)

easy binary-search interactive


Metadata

  • title_rus: Первая плохая версия
  • difficulty: Easy
  • leetcode_url: https://leetcode.com/problems/first-bad-version/
  • topics: ['Binary Search', 'Interactive']
  • time: O(log n)
  • space: O(1)
  • grind75: True
  • tags: ['Binary Search', 'Easy', 'Interactive', 'problem']
  • git_revision_date_localized: 5 июля 2025 г.
  • git_revision_date_localized_hash: f6ac458ea7f3485fe36c4b8c8f7c610ae2d995e7
  • git_revision_date_localized_tag:
  • git_revision_date_localized_raw_date: 5 июля 2025 г.
  • git_revision_date_localized_raw_datetime: 5 июля 2025 г. 19:32:08
  • git_revision_date_localized_raw_datetime-timezone: 5 июля 2025 г. 19:32:08 UTC
  • git_revision_date_localized_raw_iso_date: 2025-07-05
  • git_revision_date_localized_raw_iso_datetime: 2025-07-05 19:32:08
  • git_revision_date_localized_raw_timeago:
  • git_revision_date_localized_raw_custom: 05. июля 2025
  • git_site_revision_date_localized_hash: f6ac458ea7f3485fe36c4b8c8f7c610ae2d995e7
  • git_site_revision_date_localized_tag:
  • git_site_revision_date_localized: 5 июля 2025 г.
  • git_site_revision_date_localized_raw_date: 5 июля 2025 г.
  • git_site_revision_date_localized_raw_datetime: 5 июля 2025 г. 19:32:08
  • git_site_revision_date_localized_raw_datetime-timezone: 5 июля 2025 г. 19:32:08 UTC
  • git_site_revision_date_localized_raw_iso_date: 2025-07-05
  • git_site_revision_date_localized_raw_iso_datetime: 2025-07-05 19:32:08
  • git_site_revision_date_localized_raw_timeago:
  • git_site_revision_date_localized_raw_custom: 05. июля 2025