Determine if all values in a vector occur equally often [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 10 days ago.
This post was edited and submitted for review 10 days ago.
Improve this question
What is wrong with this code?
class Solution {
public:
bool uniqueOccurrences(vector<int> &arr) {
map<int, int> mp;
for (auto x : arr) {
mp[x]++;
}
vector<int> v;
for (auto x : mp) {
v.push_back(x.second);
}
sort(v.begin(), v.end());
for (int i = 0; i < v.size() - 1; i++) {
if (v[i] != v[i + 1])
return true;
}
return false;
}
};
Given an array of integers arr, return true if the number of occurrences of each value in the array is unique or false otherwise.
This was the question statement and was working fine with various test cases but fails in the follow test case: [3,5,-2,-3,-6,-6] should return false but returns true

Your problem is here:
for (int i = 0; i < v.size() - 1; i++) {
if (v[i] != v[i + 1])
return true;
}
return false;
You should swap the return true and return false.
for (int i = 0; i < v.size() - 1; i++) {
if (v[i] != v[i + 1])
return false;
}
return true;

Related

Terminate called without an active exception : LeetCode Question 74 [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 months ago.
Improve this question
I'm writing a simple program to search for an element in a 2D matrix. It's not giving me an active/named exception, but it just throws me a Runtime error.
Any help with as to why this is happening?
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
for (int i=0 ;i< matrix.size(); ++i){
int m = matrix[i].size() -1 ;
int n = matrix.size()-1;
if (matrix[n][m] < target){
return false;
}
else if (matrix[i][m] < target){
i++;
} else {
for (int j=0;j <= m; j++ ){
if (matrix[i][j] == target){
return true;
} else if (matrix[i][j] != target) {
continue;
}
}
if (matrix[i][m] != target ){
return false;
}
}
}throw;
}
};
}throw;
A throw without following expression can be used inside an exception handler to re-throw the currently handled exception.
However, at this point your program does not have an active exception. In this case, throw calls std::terminate().
This seems to be an edit artifact.

Trying to figure out why I'm getting a runtime error? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
This is code for the intersecting arrays. It seems to work for most of the cases until
nums1 = [1]
nums2 = [1,1]
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
vector<int> temp;
int i = 0;
int j = 0;
for (i = 0; i < nums1.size(); i++) {
for (j = 0; j < nums2.size(); j++) {
if ( (nums1.size() == nums2.size()) && (nums1[i] < nums1.size() - 1) ) {
if (nums1[i] == nums2[j])
temp.push_back(nums1[i]);
}
else if ( (nums1[i] == nums2[j]) && (i < nums1.size()) ) {
temp.push_back(nums1[i]);
i++;
}
}
}
return temp;
}
};
when i = 1, I get the error, but with the condition that (nums1[i] == nums2[j]) && (i < nums1.size()), why does it still go there and get stuck?
LeetCode 349
The order of your checks are wrong. You need to check if i is a valid index before indexing, like this:
else if ( (i < nums1.size()) && (nums1[i] == nums2[j]) ) {
otherwise you invoke undefined behavior (which could cause a run-time error).
Similarly, in all the cases where you are indexing into a vector, you need to be sure that the index is valid.
The operands of && are evaluated left to right, post-confditions will be checked if pre-conditions are all valid.
BTW, modifying the index in a for-loop is not recommended. In this case, you are likely to do repeated work. if you really want to modify the index to make your algorithm works, a while-loop is better.

How to improve my c++ code's runtime efficency [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I'm doing a leetcode problem 986. Interval List Intersections, I don't know why my O(m+n) solution, even the official solution only beats 5% submissions on runtime. How other people make it runs faster? Is there any ways or suggestions to improve my code? Thanks a lot.
class Solution {
public:
vector<vector<int>> intervalIntersection(vector<vector<int>>& A, vector<vector<int>>& B) {
vector<vector<int>> res;
int i = 0, j = 0;
while(i < A.size() && j < B.size()) {
int lo = max(A[i][0], B[j][0]);
int hi = min(A[i][1], B[j][1]);
if(lo <= hi) {
vector<int> temp{lo, hi};
res.push_back(temp);
}
if(A[i][1] <= B[j][1])
++i;
else
++j;
}
return res;
}
};
Ok, I've done it for you. See my comments in the code.
class Solution {
public:
vector<vector<int>> intervalIntersection(vector<vector<int>>& A, vector<vector<int>>& B) {
vector<vector<int>> res;
// Avoid reallocations, reserve enough memory.
res.reserve(A.size() + B.size());
int i = 0, j = 0;
// Hint to the compiler: A.size() and B.size() are immutable.
const int ii = A.size(), jj = B.size();
while(i < ii && j < jj) {
const int lo = max(A[i][0], B[j][0]);
const int hi = min(A[i][1], B[j][1]);
if(lo <= hi) {
// Construct inner vector in-place.
res.push_back(std::vector<int>({lo, hi}));
}
if(A[i][1] <= B[j][1])
++i;
else
++j;
}
return res;
}
};
The result:
Runtime: 56 ms, faster than 46.23% of C++ online submissions for Interval List Intersections.
Memory Usage: 13 MB, less than 100.00% of C++ online submissions for Interval List Intersections.
Accepted 56 ms 13 MB cpp

codility: EquiLeader Segmentation Fault problem in my code [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have a problem with this simple code. Propably the problem is with using the vector class:
int solution(vector<int> &A) {
// write your code in C++14 (g++ 6.2.0)
vector<int> left, right;
int cnt=0,k,j;
if (A.size()==1) return 0;
if (A.size()==2 && A[0]==A[1]) return 1;
if (A.size()==2 && A[0]!=A[1]) return 0;
if (A.size()==3 && A[0]==A[1] && A[1]==A[2]) return 2;
if (A.size()==3 && A[0]==A[1] && A[1]!=A[2]) return 0;
for (size_t i=0; i<(A.size()-1); ++i)
{
left.assign( A.begin(), A.begin() + i );
right.assign( A.begin() + i + 1, A.end());
sort(left.begin(), right.end());
sort(right.begin(), right.end());
j=left.size()/2;
k=right.size()/2;
if (left[j]==right[k])
{
cnt++;
}
}
return cnt;
}
after execution it return :
stderr:
Segmentation Fault
left[j] is out-of-bounds if i==0 because left.size() is i, so 0.
Similar for right[k].
Also the case A.size() == 0 is not considered and will wrap around A.size()-1.
There is also a typo in sort(left.begin(), right.end()): right.end() should be left.end().

Creating Power set from a given vector<string> with error:"Vector subscript out of range" [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I tried the following algorithm to find the power set from a given vector
std::vector<std::string> *NFAStates
std::vector<std::string> *PowerSet
int state_lines = (*NFAStates).size()
for (int i = 1; i < pow(2, state_lines); i++)
{
for (int j = 0; j < state_lines; j++)
{
if (i &(1 << j) && !(*PowerSet)[i].empty())
{
(*PowerSet)[i].append("_");
(*PowerSet)[i].append((*NFAStates)[j]);
}
else if (i &(1 << j) && (*PowerSet)[i].empty())
(*PowerSet).push_back((*NFAStates)[j]);
}
std::cout << (*PowerSet)[i] << std::endl;
}
return 0;
i get an error "Vector subscript out of range"
Here *NFAStates consist of
S0
S1
S2
and *PowerSet is where my powerset elements are stored
it would be very helpful if i know why i am getting this error
I have tested your code, with minimal mods, namely I changed pointers to references. I found no fault with it.
The problem lies elsewhere, probably in your initialization of the input vectors.
#include <string>
#include <vector>
int func(std::vector<std::string>& NFAStates, std::vector<std::string> &PowerSet)
{
int state_lines = NFAStates.size();
//for (int i = 1; i < pow(2, state_lines); i++)
for (int i = 1; i < (1 << state_lines); i++) // this is more effective for powers of 2
{
for (int j = 0; j < state_lines; j++)
{
if (i &(1 << j) && !PowerSet[i].empty()) // <-- can't access [i] if PowerSet is empty.
{
PowerSet[i].append("_");
PowerSet[i].append(NFAStates[j]);
}
else if (i &(1 << j) && PowerSet[i].empty())
PowerSet.push_back(NFAStates[j]);
}
std::cout << PowerSet[i] << std::endl; // <-- can't access [i] if PowerSet is empty.
}
return 0;
}
int main()
{
std::vector<std::string> NFAStates{ "S0", "S1", "S2" };
std::vector<std::string> PowerSet{"0", "1", "2", "3", "4", "5", "6", "7" };
return func(NFAStates, PowerSet);
}
The program, notably, bugs when PowerSet is initially empty.
Maybe adding PowerSet.resize(1 << NFAStates.size()); before the loop would fix your issue?