The question is :
Given an array arr[] of size n, find the first repeating element. The element should occurs more than once and the index of its first occurrence should be the smallest
and the time complexity and space complexity is O(n)
// { Driver Code Starts
// Initial template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function template in C++
class Solution {
public:
// Function to return the position of the first repeating element.
int firstRepeated(int arr[], int n) {
//this is my solution
int b[n]={0};
for(int i=0; i<n; i++)
{
b[arr[i]]++;
}
for(int i=0; i<n; i++)
{
if(b[i]>=1 )
return i-1;
}
return -1;
}
};
// { Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; ++i) cin >> arr[i];
Solution ob;
cout << ob.firstRepeated(arr, n) << "\n";
}
return 0;
}
// } Driver Code Ends
So any one can help me why my above code is not working instead of the below code
unordered_map<int, int> m;
for(int i=0; i<n; i++)
{
m[arr[i]]++;
}
for(int i=0; i<n; i++)
{
if(m[arr[i]] >=2 )
return i+1;
}
return -1;
Related
I am trying to sort three files (I/O) using bubble sort. For this purpose, I write this code
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
void bubble_Sort_ascending_order(ll n, ll v[]){
ll i,j;
for(i=1; i<=n-1; i++)
{
for(j=1; j<=n-i; j++)
{
if(v[j]>v[j+1])
swap(v[j],v[j+1]);
}
}
}
int bubble_Sort_ascending_input1() {
freopen("input1.txt","r",stdin);
freopen("output_File1.txt","w",stdout);
ll n;
cin >> n;
ll t[n];
for(ll i=1; i<=n; i++)
{
cin >> t[i];
}
bubble_Sort_ascending_order(n,t);
for(ll k=1; k<=n; k++)
{
cout << t[k] << endl;
}
}
int bubble_Sort_ascending_input2() {
freopen("input2.txt","r",stdin);
freopen("output_File2.txt","w",stdout);
ll n;
cin >> n;
ll r[n];
for(ll i=1; i<=n; i++)
{
cin >> r[i];
}
bubble_Sort_ascending_order(n,r);
for(ll k=1; k<=n; k++)
{
cout << r[k] << endl;
}
}
int bubble_Sort_ascending_input3() {
freopen("input3.txt","r",stdin);
freopen("output_File3.txt","w",stdout);
ll n;
cin >> n;
ll v[n];
for(ll i=1; i<=n; i++)
{
cin >> v[i];
}
bubble_Sort_ascending_order(n,v);
for(ll k=1; k<=n; k++)
{
cout <<v[k]<<endl;
}
}
int main(){
bulble_Sort_ascending_input1();
bubble_Sort_ascending_input2();
bubble_Sort_ascending_input3();
}
First input file function output is working properly. Second and third input function gives garbage value in output file two and three.
But I can't seem to locate any solutions to a similar problem. I'm really having trouble with understanding file I/O for some reason. Thanks in advance for the help.
This might not answer your question, but I see some flaws in your bubble sort algorithm. First of all, your indexing has to start at 0, otherwise you'll never read the first element in array, and then you can speed it up a little bit by right conditions in the for loop.
And then you could write bubble_Sort_ascending_input() method as just one with parameters such as std::string input_file_name and std::string output_file_name. Then you would more easily debug the program and see, where the problems are.
And for the love of gods, don't use #include <bits/stdc++.h>.
#include <fstream>
using namespace std;
typedef long long ll;
void bubble_Sort_ascending_order(ll n, ll v[]) {
ll i,j;
for(i = 0; i < n-1; i++) {
for(j = 0; j < n - i -1; j++) {
if(v[j] > v[j+1])
swap(v[j], v[j+1]);
}
}
}
void bubble_Sort_ascending(const std::string& input_file, const std::string& output_file) {
fstream input("../"+input_file, fstream::in);
fstream output("../"+output_file, fstream::out);
// "../" is just for IDE, if you run it from cmd, delete the path
ll n;
if (input.is_open()) {
input >> n;
ll arr[n];
int i = 0;
while (input >> arr[i]) {
++i;
}
bubble_Sort_ascending_order(n, arr);
if (output.is_open()) {
for (ll& number : arr) {
output << number << " ";
}
}
} else {
cout << "input not open";
}
}
int main() {
bubble_Sort_ascending("input1.txt", "output1.txt");
return 0;
}
I dont know why the program is failed to give output, This is the code to find number of zero's
in a given array
#include<iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0; i<n; i++)
{
cin>>arr[i];
}
int b=0 , a;
for(int j=0; j<n; j++)
{
a=arr[j];
while(a==0)
{
b=b++;
}
}
cout<<b;
}
Try changing it to
if (a==0) //you had a while here
{
b=b++;
}
Since you are not changing the value of 'a' inside the loop, it gets stuck inside the while and this leads to an infinite loop!
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
int b = 0, a = 0;
for (int j = 0; j < n; j++)
{
a = arr[j];
if (a == 0) //here you used while use if as you are checking the condition every iteration of loop.
{
b++; //here instead of using b=b++ use this.
}
}
cout << b;
return 0; //return is optional.
}
just do this in the j for loop. you don't need any a variable or anything
and also runtime variable arrays are not allowed in C++ use dynamic arrays or vectors
for(int j=0; j<n; j++)
{
if(arr[j]==0){
b++;
}
}
I have ruby version of this program & trying to do the same in C++
The input must be:
2 # Number of pairs
562 -881 # First pair
310 -385 # Second pair
And output:
-319
-75
It's working fine with one array of 2 numbers and breaks if pairs > 2. What's wrong in my for loops?
#include <iostream>
using namespace std;
int main() {
int sum = 0;
int iter;
cin >> iter;
int arr[2];
for (int i=0; i<iter; i++) {
for (int n=0; n<2; n++) {
// Enter numbers
cin >> arr[n];
}
}
for (int num=0; num<2; num++) {
sum+=arr[num];
}
for (int i=0; i<iter; i++) {
// Get the sum of numbers
cout << sum << endl;
}
return 0;
}
Thanks for any help!
for (int i=0; i<iter; i++) {
for (int n=0; n<2; n++) {
// Enter numbers
cin >> arr[n];
}
}
In first iteration values are entered in arr and again in second iteration previous values are overwritten (similar in next iterations if any ). This is the problem .
Solution -
#include <iostream>
using namespace std;
int main() {
int iter;
cin >> iter;
int arr[2];
int sum[iter]; // declare sum as array with iter number of elements
for(int i=0;i<iter;i++){
sum[i]=0; // initialize elements of sum to 0
}
for (int i=0; i<iter; i++) {
for (int n=0; n<2; n++) {
// Enter numbers
cin >> arr[n]; // take iput
sum[i]+=arr[n]; // add numbers and store in sum
}
}
for (int i=0; i<iter; i++) {
// Get the sum of numbers
cout << sum[i] << endl; // print values in sum after taing all inputs
}
return 0;
}
You're overwriting the contents of arr on each iteration of the loop. Try something like this (live demo here):
#include <iostream>
using namespace std;
int main() {
int sum = 0;
int iter;
cin >> iter;
int arr[2];
for (int i=0; i<iter; i++) {
for (int n=0; n<2; n++) {
// Enter numbers
cin >> arr[n];
}
for (int num=0; num<2; num++) {
sum+=arr[num];
}
cout << sum << endl;
}
return 0;
}
I want to create a program that prompts the user for the size of the vector, then applies that size to the vector (filled with random numbers). This is what I have so far, but I am at a loss. There was a similar question on this site but it was closed due to being too ambiguous. How can I create x number of data.push_back instances based on a number entered by the user?
int main()
{
srand(time(NULL));
data.push_back(rand()%10+1);
for (int i=0; i<data.size(); i++)
{
cout<<"Vector: "<<i<<" "<<data[i]<<endl;
}
return 0;
}
You could do the following if you have to use push_back
main()
{
int n;
cin >> n;
vector<int> data;
srand(time(NULL));
for (int i = 0 ; i < n; i++)
{
data.push_back(rand()%10+1);
}
for (int i=0; i<data.size(); i++)
{
cout<<"Vector: "<<i<<" "<<data[i]<<endl;
}
return 0;
}
You may also pre-allocate the whole vector, which is more efficient.
main()
{
int n;
cin >> n;
vector<int> data(n);
srand(time(NULL));
for (int i = 0 ; i < n; i++)
{
data[i] = rand()%10 + 1;
}
for (int i=0; i<data.size(); i++)
{
cout<<"Vector: "<<i<<" "<<data[i]<<endl;
}
return 0;
}
Here is one way:
Get a number from the user using std::cin and store it in an int or preferably std::vector<int>::size_type. Let's call this number n.
Loop n times, each time calling rand(), and push_back the result into your std::vector<int>
Note that std::vector<int> is a dynamic container and it's size can change at runtime. In your case, you do not have to specify it's size at compile time.
You could go for:`
srand(time(NULL));
std::vector<int> data;
int x;
std::cin>>x;
data.resize(x);
std::generate(data.begin(), data.end(), [](){return rand()%10+1;});
for(auto& num : data)
std::cout<<num<<std::endl;`
or, if you want to display the index as well:
for (int i=0; i<data.size(); i++)
cout<<"Vector: "<<i<<" "<<data[i]<<endl;
making sure you include the appropriate headers (<cstdlib>, <vector> and <algorithm>)
I have a simple sorting program being compiled by Dev-C++ 4.9.8.0. I ran the program (yes this compiles) and it simply stops after displaying the line where the vector is displayed for the first time. Note - it does not freeze, it seems to just be taking a pause. In the code, the selection sort comes next so I assume that the error happens there, but there is no error message for me to even figure out what to do!
#include <iostream>
#include <stdlib.h>
#include <vector>
#include <cmath>
#include <ctime>
using namespace std;
void bubbleSort (vector<int>& data)
{
if(data.size() <= 1)
return;
int flag=1;
int temp;
for(int i=1; (i<=data.size()) && flag; i++)
{
flag=0;
for(int j=0; (j<data.size()-1); j++)
{
if(data[j+1] > data[j])
{
temp = data[j];
data[j] = data[j+1];
data[j+1] = temp;
flag=1;
}
}
}
}
void selectionSort(vector<int>& data)
{
int min, temp, n=data.size();
for (int i=0; i<n; i++)
{
min = i;
for (int j=i+1; j<n; j++)
{
if (j<min)
{
temp=i;
i=min;
min=temp;
}
}
}
}
int main()
{
int n;
vector<int> data;
cout<<"Vector length?: "<<endl;
cin>>n;
srand(time(0));
for (int i=0; i<n; i++)
{
data.push_back(rand()%20+1);
}
cout<<"Vector: ";
for (int i=0; i<data.size(); i++)
{
cout<<data[i]<<", ";
}
selectionSort(data);
cout<<"Sorted Vector: ";
for (int i=0; i<data.size(); i++)
{
cout<<data[i]<<", ";
}
system("Pause");
return 0;
}
selectionSort() method has variable 'n' that is completely a random value that happens to be on the stack at that location. You haven't initialized it!
You have a nested loop, which is O(n^2). Say n is 1982734 or some such arbitrarily large number. You are simply looping over 1982734 * 1982734 times. EVENTUALLY it will complete. Why don't you print the value of 'n' inside selectionSort(). Just initialize it with the size of the vector.
As others commented this whole work is in progress.