Prime Subtraction Operation — LeetCode 2601 Python Solution

MediumGreedyArrayMathBinary SearchNumber Theory
Problem
#2601
Reading time
4 min

The problem

You are given a 0-indexed integer array nums of length n. You can perform the following operation as many times as you want: Pick an index i that you haven’t picked before, and pick a prime p strictly less than nums[i], then subtract p from nums[i].

Example

Input
nums = [4,9,6,10]
Output
true
Explanation
In the first operation: Pick i = 0 and p = 3, and then subtract 3 from nums[0], so that nums becomes [1,9,6,10].

Python solution

Python
class Solution:
    def primeSubOperation(self, nums: List[int]) -> bool:
        p = []
        for i in range(2, max(nums)):
            for j in p:
                if i % j == 0:
                    break
            else:
                p.append(i)

        n = len(nums)
        for i in range(n - 2, -1, -1):
            if nums[i] < nums[i + 1]:
                continue
            j = bisect_right(p, nums[i] - nums[i + 1])
            if j == len(p) or p[j] >= nums[i]:
                return False
            nums[i] -= p[j]
        return True

Complexity

MeasureComplexity
TimeO(n \log n)
SpaceO(n) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 2601. Prime Subtraction Operation is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2601. Prime Subtraction Operation?
LeetCode 2601. Prime Subtraction Operation is rated Medium on LeetCode.
What is the time complexity of LeetCode 2601. Prime Subtraction Operation?
The Python solution on this page runs in O(n \log n).
What is the space complexity of LeetCode 2601. Prime Subtraction Operation?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2601. Prime Subtraction Operation cover?
LeetCode 2601. Prime Subtraction Operation is tagged Greedy, Array, Math, Binary Search and Number Theory on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview