The Replace Non-Coprime Numbers in Array interview question gives you an integer array and asks you to repeatedly merge adjacent elements that are not coprime (i.e., their GCD is greater than 1) by replacing them with their LCM, until no two adjacent elements share a common factor greater than 1. The array is processed from left to right, but merges can cascade when a new LCM is not coprime with the element before it.
This HARD problem is asked at Uber and Amazon because it combines number theory (GCD/LCM), stack-based processing, and greedy cascade thinking. It tests whether candidates can identify that merging adjacent elements may create new non-coprime pairs with earlier elements, requiring a stack to efficiently handle cascading merges. It mirrors problems in data stream aggregation and recursive merging systems.
The pattern is stack simulation with GCD/LCM arithmetic. Use a stack. For each number in the array: push it onto the stack. Then, while the stack has at least two elements and the top two elements are not coprime (gcd(top, second) > 1), pop both, compute their LCM, and push the LCM back. The LCM of two numbers a and b is a * b // gcd(a, b). Repeat until no adjacent pair on the stack shares a factor. The final stack content is the answer.
Array: [6, 4, 3, 2, 7, 1]
Result: [12, 7, 1].
a // gcd(a,b) * b order to reduce overflow risk.For the Replace Non-Coprime Numbers in Array coding problem, the stack and number theory interview pattern is the key. The stack naturally handles cascading merges. Practice computing GCD and LCM quickly, and understand why a // gcd(a,b) * b is safer than a * b // gcd(a,b) for avoiding overflow. Amazon interviewers appreciate when you immediately identify the cascading nature of merges as the reason a stack is needed.