VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimize-replacements-to-sort-an-array-with-elements-1-2-and-3/

⇱ Minimize replacements to sort an array with elements 1, 2, and 3 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimize replacements to sort an array with elements 1, 2, and 3

Last Updated : 23 Jul, 2025

Given an array arr[] of length N containing elements 1, 2 and 3. The task is to find the minimum number of operations required to make array sorted by replacing any elements of given array with either 1, 2 or 3.

Examples:

Input: arr[] = {2, 1, 3, 2, 1}
Output: 3
Explanation:

  • 1st Operation: Choose index i = 0, Update arr[0] = 2 into 1. Then updated arr[] = {1, 1, 3, 2, 1}
  • 2nd Operation: Choose index i = 2, Update arr[2] = 3 into 2. Then updated arr[] = {1, 1, 2, 2, 1}
  • 3rd Operation: Choose index i = 4, Update arr[4] = 1 into 2. Then updated arr[] = {1, 1, 2, 2, 2}

Now, it is clearly visible that arr[] is sorted and required operations were 3. Which is minimum possible.

Input: arr[] = {1, 3, 2, 1, 3, 3}
Output: 2
Explanation: It can be verified that arr[] can be sorted under 2 operations.

Approach: Implement the idea below to solve the problem

As we have choice to update any arr[i] into either 1, 2 or 3. Then, Dynamic Programming can be used to solve this problem. The main concept of DP in the problem will be:

DP[i][j] will store the minimum number of operations to make first i elements of array sorted by making current element j(1, 2 or 3)

Transition:

  • DP[i][1] = DP[i - 1][1] + (arr[i - 1] != 1) (If ith element is made 1, then (i - 1)th element should be 1 as well).
  • DP[i][2] = min(DP[i - 1][1], [i - 1][2]) + (arr[i - 1] != 2) (If the ith element is made 2 then (i - 1)th element should be either 1 or 2).
  • DP[i][3] = min({DP[i - 1][1], DP[i - 1][2], DP[i - 1][3]}) + (arr[i - 1] != 3) (If the ith element is made 3 then (i - 1)th element should be either 1, 2 or 3).

Step-by-step approach:

  • Declare a 2D array let say DP of size [N + 1][4] with all initialized to zero.
  • Calculate answer for ith state by iterating from i = 1 to N and follow below-mentioned steps:
    • In each iteration update DP table as
      • DP[i][1] = DP[i - 1][1] + (arr[i - 1] != 1)
      • DP[i][2] = min(DP[i - 1][1], DP[i - 1][2]) + (arr[i - 1] != 2)
      • DP[i][3] = min({DP[i - 1][1], DP[i - 1][2], DP[i - 1][3]}) + (arr[i - 1] != 3)
  • Return min(DP[N][1], DP[N][2], DP[N][3])

Below is the implementation of the above approach:


Output
3

Time Complexity: O(N)
Auxiliary Space: O(N)

Comment