Skip to main content

GATE CSE 2024Algorithms › Sorting AlgorithmsVerified

GATE CSE 2024 PYQ: Let A \text{A} A be an array containing integer values. The distance of A \text{A} A is defined as the…

Let A\text{A} be an array containing integer values. The distance of A\text{A} is defined as the minimum number of elements in A\text{A} that must be replaced with another integer so that the resulting array is sorted in non-decreasing order. The distance of the array [2,5,3,1,4,2,6][2,5,3,1,4,2,6] is ___________.

    Answer

    3

    Approach

    Keeping an element unchanged is useful only if the kept elements already form a non-decreasing subsequence in their original positions. To minimize replacements, keep a longest non-decreasing subsequence (LNDS); every other element must be replaced. Thus the distance is $n - \text{LNDS length}$.

    The elements that stay unchanged must form a non-decreasing subsequence, and all remaining positions can be filled with suitable integers. Since the longest non-decreasing subsequence has length 4 in a 7-element array, the minimum number of elements to replace is $7-4=3$.

    Reviewed by GateIQ Editorial Team: IIT & IISc Alumni.