
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Minimum number of elements to add to make median equals x using C++.
Problem statement
Given an array “arr” of size n and element x, the task is to find a minimum number of elements to be added in array to make median equals x.
A median in an array with the length of n is an element which occupies position number (n-1)/2 after we sort the elements in the non-decreasing order. For example, in below array median is 20 −
arr1[] = {10, 20, 30, 40}
If arr[] = {1, 2, 3} and x = 4 then we have to add 4 number i.e. {4, 5, 5, 5} in array to make median equal to 4
Algorithm
The algorithm is very simple. We have to add one number x to the array until the median of the array equals to x
Example
#include <iostream> #include <algorithm> using namespace std; int minNumbersToBeAdded(int *arr, int n, int x){ sort(arr, arr + n); int cnt = 0; while (arr[(n - 1)/2] != x) { arr[n] = x; ++n; sort(arr, arr + n); ++cnt; } return cnt; } int main(){ int arr[20] = {1, 2, 3}; int x = 4; int n = 3; cout << "Minimum numbers to be added = " << minNumbersToBeAdded(arr, n, x) << endl; return 0; }
Output
When you compile and execute the above program. It generates the following output −
Minimum numbers to be added = 4
- Related Articles
- Minimum number of moves to make all elements equal using C++.
- Minimum number of elements to be removed to make XOR maximum using C++.
- Minimum number of operations on an array to make all elements 0 using C++.
- Minimum number of elements that should be removed to make the array good using C++.
- Minimum number of given operations required to make two strings equal using C++.
- Minimum number of squares whose sum equals to given number n\n
- Minimum edges required to add to make Euler Circuit in C++
- Minimum number of given moves required to make N divisible by 25 using C++.
- Minimum number of operations required to delete all elements of the array using C++.
- Minimum delete operations to make all elements of array same in C++.
- C++ program to count minimum number of operations needed to make number n to 1
- Program to find minimum number of days to make m bouquets using Python
- Minimum number of deletions to make a string palindrome in C++.
- Minimum Number of Steps to Make Two Strings Anagram in C++
- Minimum Add to Make Parentheses Valid in Python

Advertisements