Skip to main content

Prime Subtraction Operation - Solution & Explanation

MediumArrayMathBinary SearchGreedy22 min readAsked at: Amazon, Microsoft, Meta +1
Practice this problem

Problem Statement

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].

Return true if you can make nums a strictly increasing array using the above operation and false otherwise.

A strictly increasing array is an array whose each element is strictly greater than its preceding element.

 

Example 1:

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].
In the second operation: i = 1, p = 7, subtract 7 from nums[1], so nums becomes equal to [1,2,6,10].
After the second operation, nums is sorted in strictly increasing order, so the answer is true.

Example 2:

Input: nums = [6,8,11,12]
Output: true
Explanation: Initially nums is sorted in strictly increasing order, so we don't need to make any operations.

Example 3:

Input: nums = [5,8,3]
Output: false
Explanation: It can be proven that there is no way to perform operations to make nums sorted in strictly increasing order, so the answer is false.

 

Constraints:

  • 1 <= nums.length <= 1000
  • 1 <= nums[i] <= 1000
  • nums.length == n

Approach Overview

Problem Overview: You receive an integer array nums. For each element, you may subtract a prime number smaller than the element at most once. The goal is to determine whether these operations can transform the array into a strictly increasing sequence.

Approach 1: Prime Subtraction Greedy Approach (O(n log p) time, O(p) space)

The core observation is that earlier elements should be minimized as much as possible so later elements have more room to remain larger. Iterate from left to right and maintain the previous valid value. For each nums[i], find the largest prime p such that nums[i] - p > prev. This keeps the new value just above the previous element while reducing the current number as much as possible. Store all primes up to the maximum array value and use binary search to quickly locate the largest valid prime. If no such prime exists and nums[i] <= prev, forming a strictly increasing sequence becomes impossible. This greedy strategy works because minimizing earlier numbers maximizes flexibility for the remaining elements.

Approach 2: Optimized Prime Sieve with Early Exit (O(m log log m + n log p) time, O(m) space)

Prime lookup becomes faster by generating all primes up to max(nums) using the Sieve of Eratosthenes from number theory. The sieve runs once in O(m log log m) where m is the largest number in the array. During the main pass, compute the difference diff = nums[i] - prev. Only primes smaller than diff are valid candidates. Use binary search over the prime list to pick the largest valid prime and subtract it. If nums[i] is already greater than prev, you may skip subtraction for efficiency. Add an early exit check whenever the current value cannot exceed prev. This approach combines greedy decision making with precomputed primes to keep each step efficient.

Recommended for interviews: Interviewers typically expect the greedy strategy with precomputed primes. A naive trial of primes per element shows understanding, but the optimized sieve + binary search demonstrates stronger algorithmic thinking. It combines array traversal, prime generation, and greedy decision making while maintaining near-linear performance.

Approach 1: Prime Subtraction Greedy Approach

The idea is to ensure every element is greater than its previous one by subtracting a suitable prime. We iterate through each element and subtract the smallest possible prime until the condition is met.

For each element in the array, find if there's a prime that can be subtracted to make the current element greater than the previous one. Repeat this for all elements until the array becomes strictly increasing.

This C solution iterates over the array elements and whenever a non-increasing pair is detected, it attempts to subtract the smallest prime number from the current element to make it bigger than the previous one. After adjusting each element, the code checks again if the array is strictly increasing.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n * log(n)), primarily dominated by the prime-checking function.
Space Complexity: O(1), since we are modifying the array in place and not using any additional data structures.

Try this approach in the editor →

Approach 2: Optimized Prime Sieve with Early Exit

This approach involves using the Sieve of Eratosthenes to precompute primes up to the maximum value in the array. For each element, we maintain a list of unpicked primes smaller than the current number and dynamically reduce the current element with the largest viable prime, proceeding until a strictly increasing order is established.

We use this optimized list to attempt to produce a valid increasing order to minimize operation count and improve efficiency.

This C solution uses a sieve to precompute all primes less than a given maximum value. This approach allows us to quickly identify potential subtraction values to transform the array into one that is strictly increasing.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n * sqrt(m)), but preprocessing the prime sieve to reduce runtime cost per loop.
Space Complexity: O(m), for storing the boolean list to evaluate primes.

Try this approach in the editor →

Approach 3: Preprocessing prime numbers + binary search

We first preprocess all the primes within 1000 and record them in the array p.

For each element nums[i] in the array nums, we need to find a prime p[j] such that p[j] \gt nums[i] - nums[i + 1] and p[j] is as small as possible. If there is no such prime, it means that it cannot be strictly increased by subtraction operations, return false. If there is such a prime, we will subtract p[j] from nums[i] and continue to process the next element.

If all the elements in nums are processed, it means that it can be strictly increased by subtraction operations, return true.

The time complexity is O(n log n) and the space complexity is O(n). where n is the length of the array nums.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Approach 4: Preprocessing prime numbers

Code

TypeScript

JavaScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Prime Subtraction Greedy Approach

Time Complexity: O(n * log(n)), primarily dominated by the prime-checking function.
Space Complexity: O(1), since we are modifying the array in place and not using any additional data structures.

Optimized Prime Sieve with Early Exit

Time Complexity: O(n * sqrt(m)), but preprocessing the prime sieve to reduce runtime cost per loop.
Space Complexity: O(m), for storing the boolean list to evaluate primes.

Preprocessing prime numbers + binary search—
Preprocessing prime numbers—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Prime Subtraction Greedy with Binary SearchO(n log p)O(p)General case when primes are precomputed and you need efficient lookups
Optimized Prime Sieve with Early ExitO(m log log m + n log p)O(m)Best for repeated prime queries or large arrays where fast prime generation helps

Video Solution

Prime Subtraction Operation - Leetcode 2601 - Python • NeetCodeIO • 10,369 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Prime Subtraction Operation easy or hard?
Prime Subtraction Operation is rated Medium because it combines multiple concepts: greedy decisions, prime generation, and maintaining a strictly increasing sequence. The logic is simple once the greedy insight is clear, but recognizing the correct subtraction strategy requires careful reasoning.
Prime Subtraction Operation Python/Java solution
Most implementations generate primes using the Sieve of Eratosthenes, then iterate through the array applying the greedy subtraction rule. The logic is straightforward to implement in Python, Java, C++, or JavaScript because it mainly involves array iteration, prime lookup, and binary search.
How to solve Prime Subtraction Operation in O(n)?
Near linear performance is achieved by combining a greedy pass with precomputed primes. After building the prime list using a sieve, iterate through the array once and choose the largest valid prime less than the allowed difference. Each step performs constant or logarithmic work, making the overall runtime close to O(n).
What is the best approach for Prime Subtraction Operation?
The most effective solution uses a greedy strategy combined with precomputed primes. Iterate through the array and subtract the largest prime that keeps the current value greater than the previous element. Precomputing primes with the Sieve of Eratosthenes and using binary search gives an efficient O(n log p) approach.
Is Prime Subtraction Operation asked at Google/Amazon/Meta?
Problems combining greedy logic and number theory frequently appear in interviews at companies like Google, Amazon, and Meta. Variants that involve prime preprocessing, array constraints, or monotonic sequences are common in technical screens.
What data structure is used in Prime Subtraction Operation?
The solution primarily uses arrays and a list of prime numbers. The prime list is generated using a sieve and queried with binary search. The algorithm itself relies on greedy traversal of the input array.
What is the time complexity of Prime Subtraction Operation?
The optimized solution runs in O(m log log m + n log p) time. The sieve step generates primes up to the maximum value m, and each array element performs a binary search among p primes. Space complexity is O(m) for storing the sieve or prime list.

Ready to solve this problem?

Practice Prime Subtraction Operation with our built-in code editor and test cases.

Practice on FleetCode