Skip to content
Official PYQ · 2024

GATE CS 2024 Set 2 Q25 — Searching, Sorting, Hashing

Explain with AI
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 ___________.
View worked solution

Answer: 3

To find the minimum number of elements that must be replaced to make the array sorted in non-decreasing order, we should keep as many elements in their original relative order as possible. These kept elements must form a Longest Non-Decreasing Subsequence (LNDS) of the array.

If nn is the length of the array and LL is the length of its LNDS, then the minimum number of replacements (distance) is given by:

Distance=n−L\text{Distance} = n - L

For the given array A=[2,5,3,1,4,2,6]A = [2, 5, 3, 1, 4, 2, 6] of size n=7n = 7:

  • Let's find the LNDS of AA.
  • One such longest non-decreasing subsequence is [2,3,4,6][2, 3, 4, 6] (corresponding to indices 0,2,4,60, 2, 4, 6).
  • The length of this subsequence is L=4L = 4.

Thus, the minimum number of elements to replace is:

7−4=37 - 4 = 3

For example, by replacing the elements at indices 1,3,1, 3, and 55 (which are 5,1,5, 1, and 22), we can obtain the sorted array [2,2,3,3,4,5,6][2, 2, 3, 3, 4, 5, 6] with exactly 33 replacements.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Searching, Sorting, Hashing questions