I am trying to solve this problem in hackerrank.
https://www.hackerrank.com/challenges/circular-array-rotation/problem
Every other test is fine but one test is creating Segmentation Fault. This is the test case:
https://hr-testcases-us-east-1.s3.amazonaws.com/1884/input04.txt?AWSAccessKeyId=AKIAR6O7GJNX5DNFO3PV&Expires=1648127766&Signature=a0c1UvQ4t9DBn%2Fkr02ZnLUurhjk%3D&response-content-type=text%2Fplain
I wish to what part of my code is creating Segmentation Fault and I want to know the way to solve it with code and some explanation well as I believe my code should not have created any. Here is my code:
vector<int> circularArrayRotation(vector<int> a, int k, vector<int> queries) {
rotate(a.begin(),a.begin()+a.size()-k,a.end());
vector<int> result;
cout<<result.size()<<endl;
for(auto x:queries) result.push_back(a[x]);
return result;
}
This is the code I am submitting in the hackerrank solution. Please help me to pass the test.
The problem is:
rotate(a.begin(),a.begin()+a.size()-k,a.end());
According to the problem statement, the constraints are:
1 <= n <= 10^5
1 <= k <= 10^5
There is no constraint that k <= n, and the test case you got there is exactly the hit, n = 515, k = 100000.
So the problem is:
a.begin()+a.size()-k // a.size()-k, when k > n, is negative
So the hackerrank compiler has a problem while it's doing a.begin() - negative num.
For fixing that you should make sure it won't go in negative bounds, and since it's a circular rotation one full rotation or 1000 full rotations won't change anything, only the remainder matters:
rotate(a.begin(), a.begin() + a.size() - (k % a.size()), a.end());
It passes all the test cases.
Related
Link to The Problem: https://codeforces.com/problemset/problem/166/E
Problem Statement:
*You are given a tetrahedron. Let's mark its vertices with letters A, B, C, and D correspondingly.
An ant is standing in the vertex D of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time, he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place.
You do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex D to itself in exactly n steps. In other words, you are asked to find out the number of different cyclic paths with the length of n from vertex D to itself. As the number can be quite large, you should print it modulo 1000000007 (10^9 + 7).*
Input:
The first line contains the only integer n (1 ≤ n ≤ 107) — the required length of the cyclic path.
Output:
Print the only integer — the required number of ways modulo 1000000007 (10e9 + 7).
Example: Input n=2 , Output: 3
Input n=4, Output: 21
My Approach to Problem:
I have written a recursive code that takes two input n and present index, then I am traveling and exploring all possible combinations.
#include<iostream>
using namespace std;
#define mod 10000000
#define ll long long
ll count_moves=0;
ll count(ll n, int present)
{
if(n==0 and present==0) count_moves+=1, count_moves%=mod; //base_condition
else if(n>1){ //Generating All possible Combinations
count(n-1,(present+1)%4);
count(n-1,(present+2)%4);
count(n-1,(present+3)%4);
}
else if(n==1 and present) count(n-1,0);
}
int main()
{
ll n; cin>>n;
if(n==1) {
cout<<"0"; return;
}
count(n,0);
cout<<count_moves%mod;
}
But the problem is that I am getting Time Limit Error since Time Complexity of my Code is very high. Please Can anyone suggest me how can I optimize/Memoize my code to reduce its complexity?
#**Edit 1: ** Some People are commenting about macros and division well it's not an issue. The Range of n is 10^7 and complexity of my code is exponential so my actual doubt is how to decrease it to linear time. i,e O(n).
Anytime you built into a recursion and you exceeded time complexity, you have to understand the recursion is likely the problem.
The best solution is to not use a recursion.
Look at the result you have:
3
6
21
60
183
546
1641
4920
⋮ ⋮
While it might be hard to find a pattern for the first couple terms, but it gets easier later on.
Each term is roughly 3 times larger than the last term, or more precisely,
Now you could just write a for loop for it:
for(int i = 0; i < n-1; i++)
{
count_moves = count_moves * 3 + std::pow(-1, i) * 3;
}
or to get rid of pow():
for(int i = 0; i < n-1; i++)
{
count_moves = count_moves * 3 + (i % 2 * 2 - 1) * -3;
}
Further more, you could even build that into a general term formula to get rid of the for loop:
or in code:
count_moves = (pow(3, n) + (n % 2 * 2 - 1) * -3) / 4;
However, you can't get rid of the pow() this time, or you will have to write a loop for that then.
I believe one of your issues is that you are recalculating things.
Take for example n=4. count(3,x) is called 3 times for x in [0,3].
However if you made a std::map<int,int> you could save the value for (n,present) pairs and only calculate each value once.
This will take more space. The map will be 4*(n-1) big when you are done. That is still probably too large for 10^9?
Another thing you can do is multithread. Each call to count can instigate its own thread. You need to be careful then to be thread safe when changing the global count and the state of the std::map if you decide to use it.
Edit:
Calculate count(n,x) one time for n in [1,n-1] x in [0,3] then count[n,0] = a*count(n-1,1) +b*count(n-1,2) +c*count(n-1,3).
If you can figure out the pattern for what a,b,c are given n or maybe even the a,b,c for the n-1 case then you may be able to solve this problem easily.
First off all, feel free to improve the formatting of the question
This question is already solved by Goswin von Brederlow!
Hello, i'm praticing programming and this problem came across and i don't know how is the best way to solve this:
The question have T test cases that consists in:
Given a range L and R, find how many numbers meet the constraints:
i) Number is a perfect square;
ii) The sqrt(Number) is a prime number.
Limits:
1 <= T <= 1e4
1 <= L, R <= 1e12
Time limit: 1 second
So, i tried it with a simple idea of pre-processing with an unodered_map(lld, bool) all the answers with the sieve of eratosthenes for each sqrt(Number) given that Number is a perfect square
After, I pass in range pow(sqrt(l), 2) and increments it the next odd number... like: 4 9 16 25, the difference are odd numbers: 5 7 9...
My code:
long long int l, r; scanf("%lld %lld", &l, &r);
long long int odd = ceil(sqrt(l)), n = odd*odd;
odd = (2*odd) + 1;
long long int ans = 0;
while((n >= l && n <= r)){
it = h.find(n);
ans = ans + it->second;
n = n + odd;
odd = odd + 2;
}
But a i still got TLE, i need some help guys, thank you!
The only question I see I infer from "i don't know how is the best way to solve this".
Your way seems to be pretty smart already. You have some bugs even in just the bit of code you pasted. You seem to compute the sum of the numbers instead of counting them.
One thing I could think of improving is the counting itself. Looks like you have a hash table of all the squares of primes and you simply test all auqares if they are in the table.
Why not make a balanced tree out of the primes? In each node you store the minimum and maximum number and the count for the subtree. The leaves would be (n, n, 1) where n is one of the squares of primes. Given L and R you can then go through the tree and sum up all subtrees that are in the interval and recurse into subtrees that are only partially inside. Ignore everything outside. That should add a logarithmic factor to your complexity.
I am solving the following question:
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
by constructing the following code snippet:
class Solution {
public:
int climbStairs(int n) {
if(n==0)
return 0;
vector<int> dp(n+1);
dp[0]=0;
dp[1]=1;
for(int i=2; i<=n; i++)
dp[i] = dp[i-1] + dp[i-2];
return dp[n];
}
};
When I looked at the solutions, I found out that they make this initialization:
dp[0]=0;
dp[1]=1;
dp[2]=2; //--> Why? And when to do this?
Because of the way I initialized it, I get lower values (like the answer for n is at dp[n-1] and so on). All this, just because I didn't initialize dp[2]=2. Could someone please point out the intuition behind this particular initialization?
Thanks!
Note: Question is taken from LeetCode.com.
The code that’s posted here is incorrect, which is why you don’t see dp[2] = 2.
I believe that the DP table here is such that dp[k] represents the number of ways to climb from step n - k to step n using the rules described here. As a result, dp[0] should be 1, not 0. There’s one way to get from step n to step n by following these rules: namely, don’t take any steps!
Once you’ve initialized that value properly, then you’d have dp[2] = dp[0] + dp[1] = 1 + 1 = 2. There’s no need to explicitly initialize dp[2] since the value follows from the general case.
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 8 years ago.
Improve this question
Hi I'm getting SIGSEGV error for this problem, dont know where is th problem: http://www.spoj.com/problems/PRIME1/
I tried to solve it by sieve-of-Eratosthenes algo given on Wikipedia.
here is my code, please help thanks in advance.
int main()
{
int t; // test cases
cin>>t;
while(t--)
{
long int m,n;
cin>>m>>n;
if( 1 <= m <= n <= 1000000000 && n-m<=100000)
{
bool a[n];
for(long int i=2;i<=n;i++)
{
a[i]=true; // set all to true
}
a[0]=false;
a[1]=false;
for( long int i=2;i*i<=n;i++)
{
if(a[i])
{
for( long int k=i*i;k<=n;k+=i)
{
a[k]=false;
}
}
}
for(long int i=m;i<=n;i++)
{
if(a[i])
cout<<i<<endl; //Now all i such that a[i] is true are prime.
}
cout<<endl;
}
else
return -1;
}
return 0;
}
You have to use gdb to find out exactly what happened. There are many things wrong with this code.
As pointed out in the comments, for n large enough your a[n] will overflow the stack.
You have an off-by-one error in your first and third for loops; you check a[n] but only allocated up to a[n-1]. All of the i <= n should be i < n
if( 1 <= m <= n <= 1000000000 && n-m<=100000) is probably not what you intended; for any positive integer 'n', (1 <= m <=n) will be true
There are 3401 primes below the square root of 109. That's all you need to sieve any segment of numbers below the 109 upper limit.
So, first, sieve a segment from 2 to 31622. Store the resulting 3401 prime integers in an array.
Then for each pair of numbers m <= n, m >= n - 100000 create a temporary array covering the segment from m to n inclusive, and sieve it with those primes you've calculated in the first step. You can stop each sieving when a prime's square is above a given n:
for( i=0; primes[i]*primes[i] <= n; ++i)
{
....
See also my posts about the "offset sieve" of Eratosthenes.
This problem has been treated before on SO. For example, see Sieve of Eratosthenes on Stack Overflow. You may also want to read this blog that describes a typical C implementation: C implementation of Sieve of Eratosthenes. As pointed out above there are multiple issues with your code, so many in fact that you need to think about reorganizing it completely. Please read the linked posts to get ideas for how to do that successfully.
I am given a array A[] having N elements which are positive integers
.I have to find the number of sequences of lengths 1,2,3,..,N that satisfy a particular property?
I have built an interval tree with O(nlogn) complexity.Now I want to count the number of sequences that satisfy a certain property ?
All the properties required for the problem are related to sum of the sequences
Note an array will have N*(N+1)/2 sequences. How can I iterate over all of them in O(nlogn) or O(n) ?
If we let k be the moving index from 0 to N(elements), we will run an algorithm that is essentially looking for the MIN R that satisfies the condition (lets say I), then every other subset for L = k also is satisfied for R >= I (this is your short circuit). After you find I, simply return an output for (L=k, R>=I). This of course assumes that all numerics in your set are >= 0.
To find I, for every k, begin at element k + (N-k)/2. Figure out if this defined subset from (L=k, R=k+(N-k)/2) satisfies your condition. If it does, then decrement R until your condition is NOT met, then R=1 is your MIN (your could choose to print these results as you go, but they results in these cases would be essentially printed backwards). If (L=k, R=k+(N-k)/2) does not satisfy your condition, then INCREMENT R until it does, and this becomes your MIN for that L=k. This degrades your search space for each L=k by a factor of 2. As k increases and approaches N, your search space continuously decreases.
// This declaration wont work unless N is either a constant or MACRO defined above
unsigned int myVals[N];
unsigned int Ndiv2 = N / 2;
unsigned int R;
for(unsigned int k; k < N; k++){
if(TRUE == TESTVALS(myVals, k, Ndiv2)){ // It Passes
for(I = NDiv2; I>=k; I--){
if(FALSE == TESTVALS(myVals, k, I)){
I++;
break;
}
}
}else{ // It Didnt Pass
for(I = NDiv2; I>=k; I++){
if(TRUE == TESTVALS(myVals, k, I)){
break;
}
}
}
// PRINT ALL PAIRS from L=k, from R=I to R=N-1
if((k & 0x00000001) == 0) Ndiv2++;
} // END --> for(unsigned int k; k < N; k++)
The complexity of the algorithm above is O(N^2). This is because for each k in N(i.e. N iterations / tests) there is no greater than N/2 values for each that need testing. Big O notation isnt concerned about the N/2 nor the fact that truly N gets smaller as k grows, it is concerned with really only the gross magnitude. Thus it would say N tests for every N values thus O(N^2)
There is an Alternative approach which would be FASTER. That approach would be to whenever you wish to move within the secondary (inner) for loops, you could perform a move have the distance algorithm. This would get you to your O(nlogn) set of steps. For each k in N (which would all have to be tested), you run this half distance approach to find your MIN R value in logN time. As an example, lets say you have a 1000 element array. when k = 0, we essentially begin the search for MIN R at index 500. If the test passes, instead of linearly moving downward from 500 to 0, we test 250. Lets say the actual MIN R for k = 0 is 300. Then the tests to find MIN R would look as follows:
R=500
R=250
R=375
R=312
R=280
R=296
R=304
R=300
While this is oversimplified, your are most likely going to have to optimize, and test 301 as well 299 to make sure youre in the sweet spot. Another not is to be careful when dividing by 2 when you have to move in the same direction more than once in a row.
#user1907531: First of all , if you are participating in an online contest of such importance at national level , you should refrain from doing this cheap tricks and methodologies to get ahead of other deserving guys. Second, a cheater like you is always a cheater but all this hampers the hard work of those who have put in making the questions and the competitors who are unlike you. Thirdly, if #trumetlicks asks you why haven't you tagged the ques as homework , you tell another lie there.And finally, I don't know how could so many people answer this question this cheater asked without knowing the origin/website/source of this question. This surely can't be given by a teacher for homework in any Indian school. To tell everyone this cheater has asked you the complete solution of a running collegiate contest in India 6 hours before the contest ended and he has surely got a lot of direct helps and top of that invited 100's others to cheat from the answers given here. So, good luck to all these cheaters .