๐ข Replace Non-Coprime Numbers in Array
Imagine you have an array of integers, and you need to perform a merging process that combines adjacent numbers that share common factors!
Your Task: Given an array of integers nums, repeatedly find any two adjacent numbers that are non-coprime (meaning they share a common factor greater than 1), and replace them with their LCM (Least Common Multiple).
๐ฏ The Process:
- Find any two adjacent numbers in
numsthat are non-coprime - If no such pair exists, stop the process
- Otherwise, delete both numbers and replace them with their LCM
- Repeat until no more adjacent non-coprime pairs exist
Key Concept: Two numbers x and y are non-coprime if GCD(x, y) > 1, meaning they share a common factor other than 1.
Example: [6, 4, 3, 2, 6]
โข 6 and 4 are non-coprime (GCD = 2), replace with LCM = 12
โข Result: [12, 3, 2, 6]
โข Continue until no more merges possible...
๐ Fascinating Property: The order of processing doesn't matter - you'll always get the same final result!
Input & Output
Visualization
Time & Space Complexity
Each element is pushed and popped at most once, GCD operations are O(log min(a,b)) but bounded
Stack can hold up to n elements in worst case when no merges occur
Constraints
- 1 โค nums.length โค 105
- 1 โค nums[i] โค 106
- Values in final array โค 108
- Two numbers are non-coprime if their GCD > 1