Prime Subtraction Operation — LeetCode 2601 Python Solution
- Problem
- #2601
- Pattern
- Monotonic Stack
- Reading time
- 4 min
- Source
- leetcode.com
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
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 TrueComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \log n) |
| Space | O(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.