Minimize replacements to sort an array with elements 1, 2, and 3
Last Updated :
14 Feb, 2024
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:
C++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
// Function to Minimum replacements to
// make array sorted containing only numbers 1, 2 and 3
int minOperations(int arr[], int N)
{
// DP array initalized with 0
vector<vector<int> > dp(N + 1, vector<int>(4, 0));
// calculating answer till i'th element
for (int i = 1; i <= N; i++) {
// i'th element is made 1 then (i - 1)th element
// should be 1
dp[i][1] = dp[i - 1][1] + (arr[i - 1] != 1);
// i'th element is made 2 then (i- 1)th element
// should be either 1 or 2
dp[i][2] = min(dp[i - 1][1], dp[i - 1][2])
+ (arr[i - 1] != 2);
// if the i'th element is made 3 then (i - 1)th
// element should be either 1, 2 or 3
dp[i][3] = min({ dp[i - 1][1], dp[i - 1][2],
dp[i - 1][3] })
+ (arr[i - 1] != 3);
}
// returning final answer minimum number of operations
// required to make array sorted by by replacing i'th
// element by 1, 2 or 3
return min({ dp[N][1], dp[N][2], dp[N][3] });
}
// Driver Code
int main()
{
// Input
int N = 5;
int arr[] = { 2, 1, 3, 2, 1 };
// Function Call
cout << minOperations(arr, N) << endl;
return 0;
}
Java
public class MinOperations {
public static int minOperations(int[] arr, int N) {
// DP array initialized with 0
int[][] dp = new int[N + 1][4];
// Calculating answer till i'th element
for (int i = 1; i <= N; i++) {
// i'th element is made 1 then (i - 1)th element
// should be 1
dp[i][1] = dp[i - 1][1] + (arr[i - 1] != 1 ? 1 : 0);
// i'th element is made 2 then (i- 1)th element
// should be either 1 or 2
dp[i][2] = Math.min(dp[i - 1][1], dp[i - 1][2]) + (arr[i - 1] != 2 ? 1 : 0);
// If the i'th element is made 3 then (i - 1)th
// element should be either 1, 2, or 3
dp[i][3] = Math.min(Math.min(dp[i - 1][1], dp[i - 1][2]), dp[i - 1][3]) + (arr[i - 1] != 3 ? 1 : 0);
}
// Returning the final answer, the minimum number of operations
// required to make the array sorted by replacing i'th
// element by 1, 2, or 3
return Math.min(Math.min(dp[N][1], dp[N][2]), dp[N][3]);
}
// Driver Code
public static void main(String[] args) {
// Input
int N = 5;
int[] arr = {2, 1, 3, 2, 1};
// Function Call
System.out.println(minOperations(arr, N));
}
}
Python3
# Function to Minimum replacements to
# make array sorted containing only numbers 1, 2 and 3
def min_operations(arr, N):
# DP array initialized with 0
dp = [[0] * 4 for _ in range(N + 1)]
# calculating answer till i'th element
for i in range(1, N + 1):
# i'th element is made 1 then (i - 1)th element
# should be 1
dp[i][1] = dp[i - 1][1] + (arr[i - 1] != 1)
# i'th element is made 2 then (i- 1)th element
# should be either 1 or 2
dp[i][2] = min(dp[i - 1][1], dp[i - 1][2]) + (arr[i - 1] != 2)
# if the i'th element is made 3 then (i - 1)th
# element should be either 1, 2, or 3
dp[i][3] = min(dp[i - 1][1], dp[i - 1][2],
dp[i - 1][3]) + (arr[i - 1] != 3)
# returning the final answer, the minimum number of operations
# required to make the array sorted by replacing i'th
# element by 1, 2, or 3
return min(dp[N][1], dp[N][2], dp[N][3])
# Driver Code
if __name__ == "__main__":
# Input
N = 5
arr = [2, 1, 3, 2, 1]
# Function Call
print(min_operations(arr, N))
C#
using System;
class GFG
{
// Function to Minimum replacements to
// make array sorted containing only numbers 1, 2 and 3
static int MinOperations(int[] arr, int N)
{
// DP array initialized with 0
int[][] dp = new int[N + 1][];
for (int i = 0; i <= N; i++)
{
dp[i] = new int[4];
}
// calculating answer till i'th element
for (int i = 1; i <= N; i++)
{
// i'th element is made 1 then (i - 1)th element
// should be 1
dp[i][1] = dp[i - 1][1] + (arr[i - 1] != 1 ? 1 : 0);
// i'th element is made 2 then (i- 1)th element
// should be either 1 or 2
dp[i][2] = Math.Min(dp[i - 1][1], dp[i - 1][2]) + (arr[i - 1] != 2 ? 1 : 0);
// if the i'th element is made 3 then (i - 1)th
// element should be either 1, 2 or 3
dp[i][3] = Math.Min(Math.Min(dp[i - 1][1], dp[i - 1][2]), dp[i - 1][3]) + (arr[i - 1] != 3 ? 1 : 0);
}
// returning final answer minimum number of operations
// required to make array sorted by replacing i'th
// element by 1, 2 or 3
return Math.Min(Math.Min(dp[N][1], dp[N][2]), dp[N][3]);
}
// Driver Code
static void Main()
{
// Input
int N = 5;
int[] arr = { 2, 1, 3, 2, 1 };
// Function Call
Console.WriteLine(MinOperations(arr, N));
}
}
JavaScript
// Function to find the minimum replacements required to make the array sorted containing only numbers 1, 2, and 3
function minOperations(arr) {
const N = arr.length;
// Initializing DP array with 0
const dp = new Array(N + 1).fill(0).map(() => new Array(4).fill(0));
// Calculating answer till ith element
for (let i = 1; i <= N; i++) {
// If ith element is made 1, then (i - 1)th element should be 1
dp[i][1] = dp[i - 1][1] + (arr[i - 1] !== 1 ? 1 : 0);
// If ith element is made 2, then (i - 1)th element should be either 1 or 2
dp[i][2] = Math.min(dp[i - 1][1], dp[i - 1][2]) + (arr[i - 1] !== 2 ? 1 : 0);
// If ith element is made 3, then (i - 1)th element should be either 1, 2, or 3
dp[i][3] = Math.min(dp[i - 1][1], dp[i - 1][2], dp[i - 1][3]) + (arr[i - 1] !== 3 ? 1 : 0);
}
// Returning the final answer: minimum number of operations required to make the array sorted
return Math.min(dp[N][1], dp[N][2], dp[N][3]);
}
// Driver code
const arr = [2, 1, 3, 2, 1]; // Input array
console.log(minOperations(arr)); // Output: 1
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read