Duplicates in Array - c++

Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same.
Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.
Return k after placing the final result in the first k slots of nums.
What is wrong with my code ??
map<int,int> m;
for(int i = 0 ; i < nums.size() ; i++){
m[nums[i]]++;
if(m[nums[i]] > 2)nums.erase(nums.begin() + i);
}
return nums.size();

From the given text, we can derive the following requirements
Given an integer array nums
sorted in non-decreasing order,
remove some duplicates in-place such that each unique element appears at most twice.
The relative order of the elements should be kept the same.
Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums.
More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result.
It does not matter what you leave beyond the first k elements
Return k after placing the final result in the first k slots of nums.
So, after elicitating the requirements, we know that we have a fixed size array, presumably (because of the simplicity of the task) a C-Style array or a C++ std::array. Because of the shown source code, we assume a std::array.
It will be sorted in increasing order. Their shall be an in-place removal of elements. So, no additional variables. The rest of the requirements already shows the solution.
--> If we find duplicates (more than 2) we will shift the rest of the values one to the left and overwrite one of the duplicates. Then the logical number of elements in the array will be one less. So, the loop must run one step less.
This ends up in a rather simple program:
#include <iostream>
#include <array>
// Array with some test values
constexpr int ArraySize = 25;
std::array<int, ArraySize> nums{ 1,2,2,2,3,3,3,4,4,4,4,4,6,5,5,5,5,5,6,6,6,6,6,6,9,9 };
int main() {
// Currentlogical end of the data in the array. In the beginning, last value in the array
size_t endIndex = nums.size();
// Check allelments from left to tright
for (size_t index = 0; index < endIndex;) {
// Check, if 3 elements are same
if ((index < (endIndex -2)) and nums[index] == nums[index + 1] and nums[index + 1] == nums[index + 2]) {
// Yes, found 3 same elements. We willdelete one, so the endIndex needs to be decremented
--endIndex;
// Now hsift all array elements one to the left
for (size_t shiftIndex = index + 2; shiftIndex < endIndex; ++shiftIndex)
nums[shiftIndex] = nums[shiftIndex + 1];
}
else ++index;
}
// SHow result
std::cout << endIndex << '\n';
}

I can offer the solution of your problem.
#include <iostream>
#include <vector>
#include <set>
using namespace std;
void showContentSet(set<int>& input)
{
for(auto iterator=input.begin(); iterator!=input.end(); ++iterator)
{
cout<<*iterator<<", ";
}
return;
}
void showContentVector(vector<int>& input)
{
for(int i=0; i<input.size(); ++i)
{
cout<<input[i]<<", ";
}
return;
}
void solve()
{
vector<int> numbers={1, 2, 1, 3, 4, 5, 7, 5, 8, 5, 9, 5};
set<int> indicesToDelete;
for(int i=0; i<numbers.size(); ++i)
{
int count=0;
for(int j=0; j<numbers.size(); ++j)
{
if(numbers[i]==numbers[j])
{
++count;
if(count>2)
{
indicesToDelete.insert(j);
}
}
}
}
cout<<"indicesToDelete <- ";
showContentSet(indicesToDelete);
int newOrder=0;
cout<<endl<<"Before, numbers <- ";
showContentVector(numbers);
for(auto iterator=indicesToDelete.begin(); iterator!=indicesToDelete.end(); ++iterator)
{
numbers.erase(numbers.begin()+(*iterator-newOrder));
++newOrder;
}
cout<<endl<<"After, numbers <- ";
showContentVector(numbers);
cout<<endl;
return;
}
int main()
{
solve();
return 0;
}
Here is the result:
indicesToDelete <- 9, 11,
Before, numbers <- 1, 2, 1, 3, 4, 5, 7, 5, 8, 5, 9, 5,
After, numbers <- 1, 2, 1, 3, 4, 5, 7, 5, 8, 9,

I suggest using a frequency array.
frequency array works, That you count how many duplicates of each number while inputting, It's stored usually in an array called freq, Also can be stored in a map<int, int> or unordered_map<int, int>.
And because of input is in non-decreasing order, outputting this solution will be easy.
Note: this solution won't work if input numbers is bigger than 10^5
Solution:
#include <iostream>
const int N = 1e5 + 1; // Maximum size of input array
int n;
int nums[N], freq[N];
int main()
{
// Input
std::cin >> n;
for (int i = 0; i < n; i++)
{
std::cin >> nums[i];
freq[nums[i]]++;
}
// Outputting numbers, Using frequency array of it
for (int i = 0; i < N; i++)
{
if (freq[i] >= 1)
std::cout << i << ' ';
if (freq[i] >= 2)
std::cout << i << ' ';
}
return 0;
}

This is basically a conditional copy operation. Copy the entire range, but skip elements that have been copied twice already.
The following code makes exactly one pass over the entire range. More importantly it avoids erase operations, which will repeatedly shift all elements to the left.
vector<int> nums; // must be sorted already
if (nums.size()<=1)
return; // already done
// basically you copy all elements inside the vector
// but copy them only if the requirement has been met.
// `in` is the source iterator. It increments every time.
// `out` is the destination iterator. It increments only
// after a copy.
auto in=nums.begin();
auto out=nums.begin();
// current is the current 'int' value
int current=*in;
// `count` counts the repeat count of the current value
int count=0;
while (in!=nums.end()) {
if (*in==current) {
// The current value repeats itself, so increment
// the count value
++count;
} else {
// No, this is a new value.
// initialise current and count
current=*in;
count=1;
}
if (count<=2) {
// only if at most two elements of the same value
// copy the current value to `out`
*out=current;
++out;
}
// try next element
++in;
}
// out points to the last valid element + 1

Related

Remove duplicates from array C++

Input: int arr[] = {10, 20, 20, 30, 40, 40, 40, 50, 50}
Output: 10, 30
My code:
int removeDup(int arr[], int n)
{
int temp;
bool dupFound = false;
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(arr[i] == arr[j]){
if(!dupFound){
temp = arr[i];
dupFound = true;
}
else{
arr[i] = temp;
}
}
}
}
//shift here
}
First of all, I don't know if this is the most efficient way of doing this.
I'm trying to find the first duplicate element, assign it to every duplicate element and shift them to the end of the array, which doesn't work because the last duplicate element cannot be compared.
I need some help with finding the last duplicate element, so I can assign temp to it.
I do not understand the logic of your code. When you find the second element arr[j] that equals arr[i] you will assign temp to arr[i]. However, temp has been assigned arr[i] when you found the first duplicate. Essentially you do arr[i] = arr[i]. Its not clear how this is supposed to find unique elements.
You can use a map to count frequency of elements, then print those with frequency 1:
#include <unordered_map>
#include <iostream>
int main()
{
std::unordered_map<int,size_t> freq;
int arr[] = {10, 20, 20, 30, 40, 40, 40, 50, 50};
// count frequencies
for (auto e : arr) { ++freq[e]; }
// print the elements e where freq[e] == 1
for (const auto& f : freq) {
if (f.second == 1) {
std::cout << f.first << "\n";
}
}
}
Only small modifications needed to add the unique elements to a vector.
Instead of trying to do everything at once, let us focus on correctness first:
int removeDup(int* arr, int n) {
// Note: No i++! This depends on whether we find a duplicate.
for (int i = 0; i < n;) {
int v = arr[i];
bool dupFound = false;
for (int j = i+1; j < n; j++) {
if (v == arr[j]) {
dupFound = true;
break;
}
}
if (!dupFound) {
i++;
continue;
}
// Copy values to the sub-array starting at position i,
// skipping all values equal to v.
int write = i, skipped = 0;
for (int j = i; j < n; j++) {
if (arr[j] != v) {
arr[write] = arr[j];
write++;
} else {
skipped++;
}
}
// The previous loop duplicated some non-v elements.
// We decrease n to make sure these duplicates are not
// considered in the output
n -= skipped;
}
return n;
}
Let's start with logistics (so to speak). An array always contains a fixed number of items. There's simply no way to start with an array of 5 items, and turn it into an array of 2 items. Simply can't be done.
So, as a starting point, you need to either return something like an std::vector that keeps track of its size along with the data it contains, or else you're going to need to track the size, and return something to indicate how many elements in the array are valid after the processing.
Probably the simplest way to do things would be to use something like an std::unoredered_map to count the items, then walk through the map, and insert an item in the output if (and only if) its count is 1.
std::unordered_map<int, std::size_t> counts;
for (int i=0;i<n; i++)
++counts[arr[i]];
std::vector<int> output;
for (auto item : counts)
if (item.second == 1)
output.push_back(item.first);
return output;
If you want to modify the data in place, I'd start by sorting the input data. Then you'll start with two indices: one for your "input" position, and one for your "output" position. output starts as zero, and input as 1.
The general idea from there is pretty simple: we look at data[input] and see if it's different from both the preceding and succeeding elements. If so, we copy it to data[output], and increment the output position.
Since this tries to look at both the preceding and succeeding elements, we have to include special cases for the beginning and end of the array. The first element is unique if it's different from the following, and the end is unique if it's different from the preceding. Code can look like this:
#include <algorithm>
#include <iostream>
unsigned remove_dupe(int *data, unsigned n) {
if (n < 2) {
return n;
}
std::sort(data, data+n);
unsigned output = data[0] != data[1];
for (unsigned input = output+1; input<n-1; input++)
if (data[input] != data[input-1] && data[input] != data[input+1])
data[output++] = data[input];
if (data[n-1] != data[n-2]) {
data[output++] = data[n-1];
}
return output;
}
template <class T, std::size_t N>
void test(T (&arr)[N]) {
unsigned end = remove_dupe(arr, N);
for (int i=0; i<end; i++)
std::cout << arr[i] << "\t";
std::cout << "\n";
}
int main() {
int arr0[] = {10, 20, 20, 30, 40, 40, 40, 50, 50};
int arr1[] = { 1, 2};
int arr2[] = { 1, 1};
test(arr0);
test(arr1);
test(arr2);
}
Result:
10 30
1 2
Another option that might be available is to sort() the array. When this is done, all duplicate values throughout the array are now adjacent. You simply compare element [n] with element [n+1] to see if they are the same. You can now find and count all duplicates in a single linear pass through the sorted array.
Sorting is one of the most heavily-studied class of algorithms in computer science, and very efficient processes can be developed which rely upon things being sorted a certain way.

iterating over vector elements backwards

I am trying to implement a small program that iterates over a 2d vector backwards and adds the value of the element.
If that element have already been added then I want to overwrite the value of the vector with 99.
So for example if number of climbs is four then add the of the program points should have the value 5 and the vector should look like this at the end
{1, 1 ,1},
{99, 1, 1},
{99(should start here), 99, 99}
But I keep getting a segmentation fault and I don't know whether I am iterating over the vector backwards incorrectly.
This is my full code
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<vector<int>> vect
{ {3}, //finish here
{1, 1 ,1},
{2, 1, 1},
{1, 1, 1} //start here
};
int points = 0;
for (int i = 0; i < vect.size(); i++)
{
for (int j = 0; j < vect[i].size(); j++)
{
cout << vect[i][j] << " ";
}
cout << endl;
}
int visited = 99;
int number_of_climbs = 4;
for(int i = 4; i >= 0; i--)
for (int j = 0; j < number_of_climbs; j++)
{
if(vect[i][j] != 99)
{
points += vect[i][j];
vect[i][j] = 99;;
continue;
}
}
return 0;
}
Looping over things backwards always trips me up too, especially when I accidentally declare my loop using an unsigned int. Your backwards loop is close to correct, but can be simplified into:
for (int i = vect.size() - 1; i >= 0; --i)
{
for (int j = vect[i].size() - 1; j >= 0; --j)
{
}
}
You need to start at size() - 1 because the only indices available are [0, size) (that is EXCLUSIVE of size), so in a vector of 4 elements, that's 0, 1, 2 and 3 (and you need to start at 3), which is likely the cause of your segmentation fault since you start your initial loop at 4 so it's immediately out-of-bounds.
Here in the inner loop you can see we account for the vectors being different sizes by just using the size of each vector.
It's also possible to use reverse iterators, but iterators can be confusing to people:
for (auto outer = vect.rbegin(); outer != vect.rend(); ++outer)
{
for (auto inner = outer->rbegin(); inner != (*outer).rend(); ++inner)
{
}
}
Note I've shown both ways to access the iterator, using it-> or (*it). Within the inner loop, you will simply use *inner to get the actual value held by the vector, so if you simply had std::cout << *inner << " "; that would print the 2d vector on one line in reverse order.
Even though we're looping in reverse, we still use ++

Count Number of Digits in an array (c++)

let's say I have an array
arr[5]={5,2,3,2,5} and i wrote following program for it
#include <iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter Length of Elements= ";
cin>>n;
int arr[50];
for(int i=0;i<n;i++)
{
cout<<"Enter Number=";
cin>>arr[i];
}
for(int i=0;i<n;i++)
{
int countNum=1;
for(int j=i+1;j<n;j++)
{
if(arr[i]==arr[j])
{
if(i>0)
{
int countNum2=0;
for(int k=0;k>i;k++)
{
//bool repeat=false;
if(arr[i]==arr[k])
{
//repeat=false;
}
else
{
countNum2++;
}
}
if(countNum2==i)
{
countNum++;
}
}
else
{
countNum++;
}
}
else
{
for(int k=0;k<i;k++)
{
if(arr[k]==arr[i])
{
}
else
{
countNum=1;
}
}
}
}
cout<<arr[i]<<" has appeared "<<countNum<< "Times"<<endl;
}
return 0;
}
but why I am getting
5 has appeared 2 Times
2 has appeared 1 Time
3 has appeared 1 Time
2 has appeared 1 Time
5 has appeared 1 Time
instead of
5 has appeared 2 Times
2 has appeared 2 Times
3 has appeared 1 Times
so how to fix my program
help!
That's what you exactly need (amount of each number in array):
// we'll store amounts of numbers like key-value pairs.
// std::map does exactly what we need. As a key we will
// store a number and as a key - corresponding counter
std::map<int, size_t> digit_count;
// it is simpler for explanation to have our
// array on stack, because it helps us not to
// think about some language-specific things
// like memory management and focus on the algorithm
const int arr[] = { 5, 2, 3, 2, 5 };
// iterate over each element in array
for(const auto elem : arr)
{
// operator[] of std::map creates default-initialized
// element at the first access. For size_t it is 0.
// So we can just add 1 at each appearance of the number
// in array to its counter.
digit_count[elem] += 1;
}
// Now just iterate over all elements in our container and
// print result. std::map's iterator is a pair, which first element
// is a key (our number in array) and second element is a value
// (corresponding counter)
for(const auto& elem : digit_count) {
std::cout << elem.first << " appeared " << elem.second << " times\n";
}
https://godbolt.org/z/_WTvAm
Well, let's write some basic code, but firstly let's consider an algorithm (it is not the most efficient one, but more understandable):
The most understandable way is to iterate over each number in array and increment some corresponding counter by one. Let it be a pair with the first element to be our number and the second to be a counter:
struct pair {
int number;
int counter;
};
Other part of algorithm will be explained in code below
// Say that we know an array length and its elements
size_t length = // user-defined, typed by user, etc.
int* arr = new int[length];
// input elements
// There will be no more, than length different numbers
pair* counts = new pair[length];
// Initialize counters
// Each counte will be initialized to zero explicitly (but it is not obligatory,
// because in struct each field is initialized by it's default
// value implicitly)
for(size_t i = 0; i < length; i++) {
counts[i].counter = 0;
}
// Iterate over each element in array: arr[i]
for(size_t i = 0; i < length; i++)
{
// Now we need to find corresponding counter in our counters.
size_t index_of_counter = 0;
// Corresponding counter is the first counter with 0 value (in case when
// we meet current number for the first time) or the counter that have
// the corresponding value equal to arr[i]
for(; counts[index_of_counter].counter != 0 && counts[index_of_counter].number != arr[i]; index_of_counter++)
; // Do nothing here - index_of_counter is incrementing in loop-statement
// We found an index of our counter
// Let's assign the value (it will assign a value
// to newly initialized pair and won't change anything
// in case of already existing value).
counts[index_of_counter].number = arr[i];
// Increment our counter. It'll became 1 in case of new
// counter, because of zero assigned to it a bit above.
counts[index_of_counter].counter += 1;
}
// Now let's iterate over all counters until we reach the first
// containing zero (it means that this counter and all after it are not used)
for(size_t i = 0; i < length && counts[i].counter > 0; i++) {
std::cout << counts[i].number << " appeared " << counts[i].counter << " times\n";
}
// correctly delete dynamically allocated memory
delete[] counts;
delete[] arr;
https://godbolt.org/z/hN33Pn
Moreover it is exactly the same solution like with std::map (the same idea), so I hope it can help you to understand, how the first solution works inside
The problem with your code is that you don't remove the duplicates or assign an array which effectively stores the count of each unique element in your array.
Also the use of so many loops is completely unnecessary.
You just need to implement two loops, outer one going through all the elements and the inner one checking for dupes first (using an array to check frequency/occurence status) and counting appearance of each element seperately with a variable used as a counter.
Set a counter array (with the corresponding size of your taken array) with a specific value (say zero) and change that value when same element occurs while traversing the array, to trigger not to count for that value again.
Then transfer the count value from the counter variable to the counter array (the one which we set and which distinguishes between duplicates) each time the inner loop finishes iterating over the whole array. (i.e. place it after the values are counted)
With a little bit of modification, your code will work as you would want it to:
#include <iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter Length of Elements = ";
cin>>n;
int arr[50];
for(int i=0;i<n;i++)
{
cout<<"Enter Number = ";
cin>>arr[i];
}
int counter[50];
for(int i=0; i<n; i++)
counter[i]=0;
// Our counter variable, but counts will be transferred to count[] later on:
int tempcount;
for(int i=0; i<n; i++)
{ // Each distinct element occurs once atleast so initialize to one:
tempcount = 1;
for(int j=i+1; j<n; j++)
{
// If dupe is found:
if(arr[i]==arr[j])
{
tempcount++;
// Ensuring not to count frequency of same element again:
counter[j] = 1;
}
}
// If occurence of current element is not counted before:
if(counter[i] != 1)
counter[i] = tempcount;
}
for(int i=0; i<n; i++)
{
if(counter[i] != 0)
printf("%d has appeared %d times.\n", arr[i], counter[i]);
}
return 0;
}
I used a variable tempcount to count occurence of each element and a zero-initialized array count to get the dupes checked (by setting it to 1 for a duplicate entry, and not counting it if it qualifies as 1) first. Then I transferred the counted occurence values to counter[] from tempcount at each outer loop iteration. (for all the unique elements)

randomly reorder elements in an array without duplication

I have a fixed array of sized nine and I am trying to reorder it randomly without duplication.
this is the following code:
class numbers{
int randomIndexCount;
public:
void randomArray( int numArray[],int size){
randomIndexCount = 0;
for (int i = 0; i < size; i++)
{
int RandomIndex = rand() % size;
randomIndexCount++;
numArray[i] = numArray[RandomIndex];
cout << numArray[i] <<endl;
}
}
int main(){
srand(time(0));
int numArray[9]= {1,2,3,4,5,6,0,0,0};
numbers n;
n.randomArray(numArray,9);
return 0;
}
So far I was able to reorder the array randomly with the given elements however I am unsure how to get rid of duplication. the output should be {1,2,3,4,5,6,0,0,0} but in a random order.
I am unable to use the shuffle function and can only use rand.
I am not sure how to remove duplicate entries
this is what I had in mind
1) with the given index check if that value already exist and if it does then skip this line " numArray[i] = numArray[RandomIndex];". however this approach would not be efficient as im sure this would be too time consuming.
is there a way to remove duplicate values so my output is something like:
{0,1,0,6,2,0,5,3,4}
You should swap elements in this line numArray[i] = numArray[RandomIndex];, not assigning. This will duplicate data! Here's the swap:
int v = numArray[i];
numArray[i] = numArray[RandomIndex];
numArray[RandomIndex] = v;
You are duplicating the elements with the assignement inside the for loop
numArray[i] = numArray[RandomIndex]
Instead asign the element to the position of the array, you need to swap those elements as follow:
class numbers
{
int randomIndexCount;
public:
void randomArray (int numArray[], int size)
{
randomIndexCount = 0;
// Use srand with a time seed value in order to
// have different results in each run of the programm
srand (time (NULL));
for (int i = 0; i < size - 1; i++)
{
int swap = numArray[i];
//take a random index from 0 to i
int j = rand () % (size);
numArray[i] = numArray[j];
numArray[j] = swap;
cout << numArray[i] << endl;
}
}
};
int main ()
{
int numArray[9] = { 1, 2, 3, 4, 5, 6, 0, 0, 0 };
numbers n;
n.randomArray (numArray, 9);
return 0;
}
This will be the output that includes all then numbers in the array:
5
2
0
6
3
0
1
0
This loop scans positions from the end of the array towards its beginning and randomly selects a new item to be put at the current position. Items are chosen from positions not scanned yet.
This way every place is exactly once chosen to be filled with some item, and each item is exactly once placed in its final position (although, before this happens, it may be several times swapped out of places chosen for other elements).
It also guarantees no item disappears (gets overwritten) and no duplicates appear (no item is copied inadvertently) - if you have duplicates in input data, the same duplicates remain in the output (although permuted); if there are no duplicates, there will be no duplicates.
Additionally, if the rand() function has no bias, every item has the same chance to end at any chosen position, hence each possible permutation is equally probable as an output.
for (int i = size; i > 1; -- i)
{
int swapIndex = rand() % i;
int swap = numArray[swapIndex];
numArray[swapIndex] = numArray[i-1];
numArray[i-1] = swap;
}

algorithms to find the minimum move-element-to-end steps required to get a sorted list

We are given an array of int which are not sorted (Do not assume that the array contain only positive integer and no duplicate elements.). Each time, we are only allowed to pick a random element and put it at the end of the array. What is the minimum steps required to make this array a sorted list (in ascending order)?
A illustrating example for you to understand
Suppose the given list is {2, 1, 4, 3}, then the minimum step required is 3.
step 1: pick 2, put it at the end of the array, now the array is {1, 4, 3, 2}
step 2: pick 3, put it at the end of the array, now the array is {1, 4, 2, 3}
step 3: pick 4, put it at the end of the array, now the array is {1, 2, 3, 4}
I have tried to solve this problem on my own. But I am not sure if my solution has minimum time complexity and space complexity.
My solutions
suppose the given array is nums, which is a vector of int. My solution is (now with complete code to run it on your own)
#include <vector>
#include <iostream>
using namespace std;
int main(){
int N; // N is the number of elements in this array
cin >> N;
vector<int> nums(N);
vector<int> nums_copy(N);
for (int i = 0; i != N; ++i){
cin >> nums[i];
nums_copy[i] = nums[i];
}
sort(nums_copy.begin(), nums_copy.end());
size_t j = 0;
for (size_t i = 0, end = nums.size(); i != end; ++i){
if (nums[i] == nums_copy[j])
++j;
}
cout << nums.size() - j << endl;
return 0;
}
The idea is to sort the original array, and then count the number of element in the original array which are in correct order in the sorted array(j in the above code). So the minimum steps required is just nums.size()-j.
The space complexity is O(n) and time complexity is O(nlog(n)) which is just
the time complexity of sorting the array.
If you think that my solution is wrong or you have a better solution in term of either time or space complexity or both, share your solution.
I have code that only needs O(1) space and O(n) time:
#include <iostream>
#include <vector>
#include <climits>
static std::size_t xsteps(const std::vector<int> &nums) {
int min = nums.end()[-1], bad_min = INT_MAX;
for (std::size_t i = nums.size(); i--; ) {
if (nums[i] < min) {
min = nums[i];
} else if (min < nums[i] && nums[i] < bad_min) {
bad_min = nums[i];
}
}
std::size_t count = 0;
std::size_t i;
for (i = 0; i < nums.size(); i++) {
if (nums[i] >= bad_min) {
count++;
}
}
while (i-- && nums[i] >= bad_min) {
if (nums[i] == bad_min) {
count--;
}
}
return count;
}
int main() {
std::cout << xsteps({2, 1, 4, 3}) << '\n';
}
The idea is to first find the smallest element that's out of place (i.e. has a smaller element to the right of it). This is done by the first loop, which iterates from the end, keeping track of the smallest element seen so far (min) and the smallest element that's out of place (bad_min).
By the end of this loop, we know that all elements smaller than bad_min are already in their right place and we don't need to touch them.
Then we iterate over the vector again. We count all elements that are greater than or equal to bad_min as out of place. However, this overestimates the true count: All copies of bad_min that are not themselves out of place (i.e. are not followed by a smaller element) do not need to be moved.
This is fixed in the third loop. It iterates from the right and decrements the counter for each bad_min found, stopping as soon as it sees a smaller element.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int calcsort(vector<int>& nums)
{
int start=1;
for(int i=0;i<nums.size();i++)
{
if (nums[i]==start)
start++;
}
return (nums.size()-(start-1));
}
int main()
{
vector<int> nums={2,1,4,3};
cout<<calcsort(nums)<<endl;
}
The idea is to find max ascending subsequenсe. Apparently, min amount of steps = nums.size() - subsequenсe's length. That's all.