Prime Subtraction Operation - 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].

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.

Input & Output

Example 1 — Possible Case
$ Input: nums = [4,9,6,10]
Output: true
💡 Note: We can subtract prime 2 from 4 to get [2,9,6,10], then subtract prime 7 from 9 to get [2,2,6,10], but 2=2 violates strictly increasing. Actually, we need different approach: subtract 2 from 4→2, subtract 5 from 6→1, but then 9>1 so subtract more from 9. The greedy approach working right-to-left would determine feasibility.
Example 2 — Already Increasing
$ Input: nums = [6,8,11,12]
Output: true
💡 Note: Array is already strictly increasing: 6 < 8 < 11 < 12, so no operations needed.
Example 3 — Impossible Case
$ Input: nums = [5,8,3]
Output: false
💡 Note: We need 5 < something < 3, but after subtracting any prime from 8, we cannot make 8 less than 3 while keeping 5 less than the result.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i] ≤ 1000

Visualization

Tap to expand
Prime Subtraction Operation INPUT nums array (length 4) 4 i=0 9 i=1 6 i=2 10 i=3 Available Primes: 2, 3, 5, 7, ... Goal: Make array strictly increasing Constraint: p must be strictly less than nums[i] ALGORITHM STEPS 1 Start from right (i=3) nums[3]=10, keep as is 2 Check i=2: nums[2]=6 Need 6 < 10 (OK, keep) 3 Check i=1: nums[1]=9 9 > 6! Subtract prime 5 9 - 5 = 4 (now 4 < 6) 4 Check i=0: nums[0]=4 4 = 4! Subtract prime 3 4 - 3 = 1 (now 1 < 4) Transformation: [4, 9, 6, 10] 4-3=1, 9-5=4 [1, 4, 6, 10] 1 < 4 < 6 < 10 OK FINAL RESULT Transformed Array: 1 4 6 10 < < < Output: true Verification: * 1 < 4 ... OK * 4 < 6 ... OK * 6 < 10 ... OK Strictly Increasing! Key Insight: Greedy Right-to-Left: Process from the end to ensure each element is less than its successor. For each position, find the largest prime p < nums[i] such that (nums[i] - p) < nums[i+1]. This greedy choice maximizes flexibility for earlier elements, ensuring global optimality. TutorialsPoint - Prime Subtraction Operation | Greedy Right-to-Left Approach
Asked in
Google 15 Amazon 12 Microsoft 8
12.4K Views
Medium Frequency
~25 min Avg. Time
287 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen