IAE Academy

GATE 2024 CS2 Q.35: solution and answer

GATE 2024 · CS2Q.35 · 1 mark · NAT

Let be an array containing integer values. The distance of is defined as the minimum number of elements in that must be replaced with another integer so that the resulting array is sorted in non-decreasing order. The distance of the array is ____________.

See the question in the paper

Answer and solution

ANSWER

The distance of the array is 3.

Official answer: 3Source: Official answer key, GATE 2024 CS2 (IISc Bengaluru)

  1. Reformulate the problem: the elements that are NOT replaced must already appear in non-decreasing order among themselves (as a subsequence), because every replaced position can be filled with any value needed to bridge the gaps and keep the whole array non-decreasing.

  2. Therefore the minimum number of replacements equals minus the length of the Longest Non-Decreasing Subsequence (LNDS) of the array.

  3. Let (1-indexed), so .

  4. Define = length of the LNDS ending at index : , or if no such exists.

  5. for . for (using ). for (using ). for (no earlier element ).

  6. for : eligible predecessors () are , , ; taking the maximum gives (subsequence ).

  7. for : eligible predecessors () are , ; so .

  8. for : all earlier elements are , so the eligible set is everything; the maximum among is (at ), giving (subsequence at indices ).

  9. The length of the LNDS is .

  10. Distance . Check: keeping positions (values ) and replacing positions with, say, gives a valid non-decreasing array using exactly replacements, and no non-decreasing subsequence of has length greater than , so is indeed the minimum.

KEY IDEA

Minimum replacements to make an array non-decreasing = − (length of the Longest Non-Decreasing Subsequence), because the untouched elements must themselves already form a non-decreasing subsequence, and any gaps left by replaced elements can always be filled with values that bridge them.

WATCH OUT FOR

Comparing the array with its sorted version, [1, 2, 2, 3, 4, 5, 6], and counting the positions that differ gives 5, because only positions 5 and 7 already match. The elements kept unchanged need only be in non-decreasing order among themselves, not in their final sorted positions, so the distance is minus the length of the longest non-decreasing subsequence: .

From the GATE 2024 CS2 paper. Every question of this paper · Download the full paper · All 8 Design techniques questions, with notes

More Design techniques questions