Code gives different results for similar inputs - c++

I was working on a problem to find the longest substring without repeating characters. While trying for the solution I wrote this code. I'm not asking for the solution, but just the reason why the code works the way it does.
#include<iostream>
#include<map>
using namespace std;
class Solution {
public:
int lengthOfLongestSubstring(string s) {
map<char,int> mp;
map<char,int>::iterator it;
int i=0,k=0,max=0;
while(i<s.length()){
it = mp.find(s[i]);
if(it==mp.end()){
k++;
}
else{
k=k-distance(mp.begin(),it);
cout<<distance(mp.begin(),it)<<" "; //this distance
mp.erase(mp.begin(),it);
}
if(k>max){
max=k;
}
mp.insert({s[i],1});
i++;
}
return max;
}
};
int main(){
Solution obj;
cout<<obj.lengthOfLongestSubstring("yvyf");
}
When I give the input as "yvyf" it prints the distance as 1, but when I give the input as "avaf" or "pvpf", it prints the distance as 0.

Related

What is the problem with the following code using constructors for sorting strings?

#include <iostream>
#include <string.h>
using namespace std;
class sorting
{
private:
char str[10];
public:
sorting() {
int i;
for(i=0;i<10;i++) {
cin>>str[i];
}
}
void sort() {
int i,j;
char temp;
for(i=0;i<10;i++) {
for(j=i+1;j<10;j++) {
if(strcmp(str[j],str[j+1])>0) {
strcpy(temp,str[j]);
strcpy(str[j],str[j+1]);
strcpy(str[j+1],temp);
}
}
}
for(i=0;i<10;i++) {
cout<<str[i];
cout<<"\n";
}
}
};
int main() {
sorting s1;
cout<<s1.sort();
return 0;
}
This is a code I have written to sort strings using constructors. It gives me error in the if condition of the code where I have used strcmp. Please review this for I could not get the desired output and it gives me errors.
Problem 1
Like someone already pointed out, you cant use strcopy on chars. If you want to create a string array i would suggest using either char** or std::string*.
Problem 2
In your nested loop you will get an index out of bounds error, due to the fact that once i reaches a value of 8, j will be 9, which means that when you try to access str[j+1] which evaluates to str[10], you will get said error.

Why does the program to find the largest number formed using elements of an array not work?

Visit https://www.interviewbit.com/problems/largest-number/ for the question...
Now I wrote the below code to solve the question (although I used an array to store the number, will do the storing in strings part later..)-
So in this algorithm, I basically used quicksort but with a twist, I changed the definition of greater than or lesser than of two numbers say X, Y such that if the number formed by using X first and Y second or XY is >= YX then greater than(X, Y) is true
In the present scenario, the code is giving runtime error, which I can't understand why, also after a bit of debugging as shown in the comments, still the answer is not coming as expected.
#include <iostream>
#include <vector>
#include <cmath>
#include <stdlib.h>
#include <time.h>
using namespace std ;
bool greaterthan(int a,int b)
{
int n1,n2,s1,s2;
n1=((int )log10(a))+1;
n2=((int)log10(b))+1;
s1=a*((int )pow(10,n2))+b;
s2=a + ((int )pow(10,n1))*b;
if(s1>=s2){return true;}
else{return false;}
}
int spartitions(vector<int >&B,int s , int e)
{
int pivot = B[e];
int pin =s;
int i;
for(i=s;i<=e;i++) //if i change this to i<e
{
if(B[pin]>=pivot)
{swap(B[pin],B[i]);
pin++;
}
// and add swap(B[pin],B[e]);
}
return pin-1; // and return pin here then it works but not give correct output
}
int prand(vector<int >&B,int s ,int e)
{
srand(time(NULL));
int n = rand()%(e-s+1)+s;
swap(B[n],B[e]);
int pin = spartitions(B,s,e);
return pin;
}
void qsort(vector<int >&B,int s, int e )
{
if(s<e){
int p= prand(B,s,e);
qsort(B,s,p-1);
qsort(B,p+1,e);
}
}
vector<int> largestnumber(vector<int >&A)
{
int n =A.size();
vector<int >B(n);
B=A;
qsort(B,0,n-1);
return B;
}
int main()
{
int n;
cin>>n;
vector<int>A(n);
int i;
for(i=0;i<n;i++)
{
cin>>A[i];
}
vector<int >B(n);
B=largestnumber(A);
for(i=0;i<n;i++)
{
cout<<B[i];
}
}
Please Help as I am a newbie in programming and can't figure this out from like 3-4 hours ...??
Would really appreciate if someone can correct my code only and not give a different algorithm, as I want this algorithm to be corrected.
Your self-written qsort function recursively calls itself, which adds more things to the stack, which only has so much space. When the list is too big, there will be too many function calls in the stack and it overflows. That's why anything less than 5 for the first input (which is for n) works fine but as soon as you exceed that, you get a runtime error. Consider not using a recursive function call.
Edit: Enabling optimisation also seems to fix this issue.
This may not work depending on the compiler and how it optimises. (Works on MSVC)

Write a short C++ program that outputs all possible strings formed by using each of the characters ’a’, ’b’, ’c’, ’d’, ’e’, and ’f’ exactly once

I came across this question and I am not able to solve it. All I could code was for small strings like ab,ac,ad,ae,af and such. But not for the longer strings like abc,abcd,etc. It would be really nice if someone could direct me towards some kind of solution. I would prefer without recursion but if not then recursion is also fine.
Here is my code:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
vector<string> make_string(vector<char>vec, char ch)
{
int i=0;
vec.erase(remove(vec.begin(), vec.end(), ch), vec.end());
int size = vec.size();
vector<string>all_strings;
string answer="";
for(i=0;i<size;i++) //here is the "meat". I could add a few more for loops for longer strings
// But I think that would just get messy.
{
answer= answer+ch+vec[i];
all_strings.push_back(answer);
answer="";
}
return all_strings;
}
void print_vector(vector<string>vec)
{
int i=0;
int size = vec.size();
for(i=0;i<size;i++)
{
cout<<vec[i]<<endl;
}
cout<<"--------------------------";
cout<<endl;
}
int main()
{
vector<char>vec;
vec.push_back('a');
vec.push_back('b');
vec.push_back('c');
vec.push_back('d');
vec.push_back('e');
vec.push_back('f');
int i=0;
vector<string>my_strings;
int size=vec.size();
for(i=0;i<size;i++)
{
my_strings=make_string(vec,vec[i]);
print_vector(my_strings);
my_strings.clear();
}
return 0;
}
You are looking for a permutation algorithm. Please take a look at this post on wordaligned.org, which describes an iterative solution to the problem:
Next permutation
The author's code is very simple and makes use of the standard library:
#include <algorithm>
#include <cstdio>
int main()
{
char xs[] = "abcdef"; // <-- modified to fit the question.
do
{
std::puts(xs);
}
while (std::next_permutation(xs, xs + sizeof(xs) - 1));
return 0;
}
If you read further, there is a discussion on the implementation of next_permutation and a breakdown of how it works.

Incorrect outputs for simple solution

Codeforces problem 373A-http://codeforces.com/problemset/problem/373/A
Instead of multiple if statements for counting number of elements of each number,I have tried to check for given condition after sorting the array.I am getting incorrect output for 1st test case(given in the link for the problem).What is wrong with my approach?What should I change in my solution.
My solution:
#include<iostream>
#include<cstring>
using namespace std;
int k,i,j,a;
char panel[17],temp,output[4];
int main()
{
cin>>k;
for(i=0;i<16;i++)
cin>>panel[i];
for(i=0;i<16;i++) //Bubble sort.
{
for(j=0;j<(15-i);j++)
{
if(panel[j]>panel[j+1])
{
temp=panel[j+1];
panel[j+1]=panel[j];
panel[j]=temp;
}
}
}
a=1;
strcpy(output,"YES");
for(i=0;i<16;i++)
{
if(panel[i]==panel[i+1])
++a;
else
a=1;
if(a>(2*k));
{
strcpy(output,"NO");
break;
}
}
cout<<output;
}
You have a semi-colon after the if statement:
if(a>(2*k));
That means, it's always going copy "NO" and break the loop. Remove it.

SIGSEGV on Submission

i was solving the problem
https://www.spoj.pl/problems/ACPC11A/
and here is my code :
#include<iostream>
#include<cstdio>
#include<string>
#include<vector>
using namespace std;
int main()
{
int tc,i,n;
scanf("%d",&tc);
while(tc--)
{
vector<string> v1,v2;
string str,w;
scanf("%d",&n);
int flag=0;
for(i=0;i<n;i++)
{
cin>>str;
if(str[0]!='#')
{
flag=1;
w=str;
}
else if(flag==0)
{
v1.push_back(str);
}
else
v2.push_back(str);
}
//print v2-->w-->v1
for(i=0;i<v2.size();i++)
{
cout<<v2[i]<<" ";
}
if(w!="")
cout<<w<<" ";
for(i=0;i<v1.size()-1;i++)
cout<<v1[i]<<" ";
cout<<v1[v1.size()-1]<<endl;
v1.clear();v2.clear();str.clear();w.clear();
}
return 0;
}
i am getting the correct output for the sample test case...but on submission my code gives segmentation fault.
my logic is simple..
i took 2 vectors 1 for storing words before a English word arrives(v1) and other for storing worlds after a English word arrives(v2)
after that i print the contents of v2 followed by word and then content of v1.
please help me in understanding why is this code giving segmentation fault.
don't bother guys...i got my mistake
Error is in line for(i=0;i<v1.size()-1;i++)
when v1.size() is 0 ,then as size() returns unsigned value...hence 0-1 will be very large value and hence the SIGSEGV