Hackerrank challenge timout [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
hey i am just trying to solve a challenge on hackerrank but in some test cases the code timeouts and i don't know why. This is the challenge.
And here is my code:
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int main(){
int n, k, q;
scanf("%d %d %d",&n,&k,&q);
int qs[q];
int a[n];
for(int i = 0; i < n; i++){
scanf("%d", &a[i]);
}
for(int i = 0; i < q; i++){
scanf("%d",&qs[i]);
}
int lastNbr = a[n-1];
for(int i = 0; i < k; i++){
lastNbr = a[n-1];
for(int j = n - 1; j > -1; j--){
a[j] = (j-1 >= 0) ? a[j-1] : lastNbr;
}
}
for(int i = 0; i < q; i++){
printf("%d\n", a[qs[i]]);
}
return 0;
}

All right, lets start with analysing your algorithm's time complexity:
You have the 2 nested for loops which always go for n * k operations, as you rotate your array k times and you need n operations to make the rotation.
This goes as O(n * k), so it's about 10^10 operations on the worst case input, which is quite too much for this task.
Please read this article first about how to calculate an algorithm's complexity, as it provides very useful information and it's explained with practical examples.
Now, you have to rethink your algorithm and get a better time complexity. I won't spoil the solution to you, but I can give you a hint: Think that you don't really need to rotate your array k times by 1 unit, you can instead do it only once by k units.
Hope this helps, good luck in solving the challenge! :)

If you look at your code it is o (n*k) solution. You can solve it in o (n) time. And input size is 10 pow 5 that's why you are getting time out error. % will help you out here.

Related

C simple question of getting average value from array each components addition [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
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.
Closed 2 years ago.
Improve this question
This is a c code for getting the average value of the addition of array components.
But once I run this which is not outputting anything.
Can anyone help me out where I got the code wrong?
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
double solution(int arr[], size_t arr_len);
int main()
{
int array[10] = { 1,2,3,4,5,6,7,8,9,10 };
int length = sizeof(array[10]);
double out = solution(array, length);
printf("solution is %f\n", out);
return 0;
}
double solution(int arr[], size_t arr_len) {
double answer = 0;
int total = 0;
for (int i = 0; i < arr_len;){
total += arr[i];
}
answer = total / arr_len;
return answer;
}
You are not incrementing the loop counter in solution so its stuck in an infinite loop.
for (int i = 0; i < arr_len;){
needs to be
for (int i = 0; i < arr_len; i++) {
Edit:
sizeof is also wrong. It returns the total memory used by the array. So you need to do
int length = sizeof(array) / sizeof(array[0])
which divides the total memory by the size of one element to give you the total number of elements.

A bug in merge sort [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Can you guys please help me with this code. I know this is basic but I am now really obsessed with it. I am trying to implement a very simple version of mergesort, but the output is all wrong. Please try to fix this code instead of writing a completely new one.
#include <stdio.h>
void merge_them(int a[], int l, int m, int r)
{
int i=l, j=m+1;
int final[r-l+1];
int p=0;
for(int k=0; k<=r-l+1; k++)
{
if(a[i]<a[j])
{
final[p]=a[i];
i++;
p++;
}
else if(a[i]>=a[j])
{
final[p]=a[j];
j++;
p++;
}
}
j=0;
for( i=l; i<r+1; i++)
{
a[i]=final[j];
j++;
}
}
void merge(int a[], int l, int r)
{
if(l<r)
{
int m = (l+r)/2;
merge(a,l,m);
merge(a,m+1,r);
merge_them(a,l,m,r);
}
}
int main()
{
int a[10] = {10,9,8,7,6,5,4,3,2,1};
merge(a,0,9);
for(int i=0; i<10; i++)
printf("%d ",a[i]);
}
UPDATE: This was not a homework. I was just revisiting some sorting algos based on recursion and tried to implement Merge sort. Anyway, I switched to while loop and used a more precise condition check, which led to correct sorted outputs.
There are actually three bugs:
The condition k<=r-l+1 in the for statement is wrong and it will have it do one more loop. It should be k<r-l+1 (< should be used instead of <=) like the condition i<r+1 used later.
The condition a[i]<a[j] is wrong because it isn't checking if the parts are used up. It should be j > r || (i <= m && a[i]<a[j]).
if(a[i]>=a[j]) should be removed because if you don't take an element from one part, you will obviously take from another part.

How to solve a competitve programming task with dynamic programming? (CodeForces) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
The condition is:
Ayoub and Kilani felt board while they are going to ArabellaCPC in
(Amman-Irbid) road, so Kilani invented a new game to play with Ayoub.
The game is described by the following rules :
Ayoub picks a random integer n (1≤n≤109) , and Kilani picks a random
integer k (1≤k≤n), then they will start playing. In each turn a player
can choose any number x (1≤x≤max(1,m−k)) (which m is the current value
of n) and subtract it from n. if n equals zero then the player can't
make a move. The player who can't make a move is considered to lose
the game.
If Kilani starts, and each player played optimally, who would be the
winner?
Actually, I am a fresh-water in competivie programming and totally cannot come up with right idea. I have written something, but I cannot get is this right way, because it gives me wrong results.
#include <iostream>
#include <string>
#include <iterator>
#include <sstream>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <list>
#include <numeric>
#include <iomanip>
#include <numeric>
#include <deque>
#include <cmath>
int bestWin(int m, int k)
{
if (m - k <= 0)
return 0;
std::vector<int> availableNumbers(m - k);
std::iota(availableNumbers.begin(), availableNumbers.end(), 1);
std::vector<int> possibleWins;
for (auto i = 0; i < availableNumbers.size(); i++)
{
possibleWins.push_back(bestWin(m - availableNumbers[i], k));
}
return *std::max_element(possibleWins.begin(), possibleWins.end()) + 1;
}
int main()
{
int testCases;
std::cin >> testCases;
while (testCases--)
{
int n, k;
std::string numbers;
std::cin.get();
std::getline(std::cin, numbers);
std::istringstream iNumbers(numbers);
iNumbers >> n; iNumbers >> k;
std::cout << bestWin(n, k);
}
return 0;
}
Could you explain me please what an approach should I use? I guess it is dynamic programming... I do not know where can I ask a help anywhere else...
You don't need dynamic programming to solve this problem. Consider the following:
When n <= k+1 then the only value that can be chosen for x is 1 (x<=max(1, n-k)
When n > k+1 you can choose any value for x so Kilani will always win by choosing n-k or n-k-1 and reaching k or k+1 (explained below)
For the first point you just need to check wether k is odd or even, because Kilani can reach k in one move and after that players will alternate removing 1 each round. In that case, if k is odd Ayoub wins and Kilani wins otherwise.
For the second point, depending on the parity of k Kilani can pick n-k or n-k-1, For example:
n = 10, k = 3
Kilani chooses max(1, m-k) = max(1, 10-3-1) = 6
n = 4
Ayoub chooses max(1, m-k) = max(1, (any number)-3) = 1
n = 3
then they keep alternating picking ones and Kilani will win
So you could modify your code to do:
while (testCases--)
{
int n, k;
std::string numbers;
std::cin.get();
std::getline(std::cin, numbers);
std::istringstream iNumbers(numbers);
iNumbers >> n; iNumbers >> k;
if (n-k == 1 && (k&1)) {
std::cout << "Ayoub";
} else {
std::cout << "Kilani";
}
}

Create an array with increasing decimal values in C [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
Super noob question here, but I haven't worked much in C and I'm trying to create an array but it doesn't seem to be working. I have played around a bit in an online compilator but I just can't get it right.
What I want is an array containing 100 elements. I want the first element to be 8, the last element to be 12, and every element should increase by 0.04. So [8, 8.04, 8.08, ..... , 11.96, 12].
Can anyone help a newbie out? :)
#define NUMS 101
int main()
{
double arr[NUMS];
double start = 8.0, end = 12.0;
double gap = (end - start) / (NUMS - 1);
int i;
for (i = 0; i < NUMS; ++i)
arr[i] = start + i * gap;
}
Here is code example based on Blaze snipped. This code first fills array and then prints it out. Also as jwismar mentioned you need 101 elements.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[]) {
float a[101];
for (int i = 0; i < sizeof(a)/sizeof(a[0]); i++)
a[i] = 8.0 + (i*0.04);
for (int i = 0; i < sizeof(a)/sizeof(a[0]); i++) {
printf("%f\n",a[i]);
}
return 0;
}
BTW if you want to start from 8 and end with 12 then you need 101 elements.
#include <stdio.h>
#include <stdlib.h>
int main()
{
double arr[101];
int i;
arr[0] = 8;
for (i = 1; i < 101; i++)
arr[i] = arr[i - 1] + 0.04;
for (i = 0; i < 101; i++)
printf("%f\n",arr[i]);
}

Sorting array of integers C [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 years ago.
Improve this question
i'm a beginner c programmer studying computer science and i'm trying to create a sorting program to sort an array of integers although i keep getting wrong results, this is what i got so far:
#include <stdio.h>
#include <string.h>
#define TAM 9
int sort_array(int num1[],int num2[]);
int main(){
int i=0;
int num1[TAM] = {5,6,2,4,7,1,3,0};
int num2[TAM] = {0};
int * ptr_num2 = num2;
sort_array(num1,num2);
while(*ptr_num2 != '\0'){
printf("%c",*ptr_num2+48);
ptr_num2++;
}
putchar('\n');
return 0;
}
int sort_array(int num1[],int num2[]){
int min=256,max=0,i,j;
int * ptr_num1 = num1;
int * ptr_max = num1;
int * ptr_num2 = num2;
/* check for max */
while(*ptr_max != '\0'){
if(*ptr_max > max) max = *ptr_max;
ptr_max++;
}
for(i=0;i<TAM-1;i++){
/* check for min */
for(j=0;j<TAM-1;j++){
if(*ptr_num1 < min) min = *ptr_num1;
ptr_num1++;
num1[i] = max;
}
*ptr_num2 = min;
ptr_num2++;
}
return 0;
}
I've been banging my head for several hours on this already.
EDIT: Forgot to mention that some of these things might not make sense since i'm just experimenting with a few things.
I understand you do not know about the typical array sorts... Well, let me to introduce you to one of the more simple ones. Allthough it's usually not the most efficient one, it's the easiest one to understand, and considering the fact you are messing with little arrays and not databases, it will be just fine.
I am talking about good old Chum, our Bubble sort.
Bubble sort is a well known simple array sorting algorithm -
The logic is simple. You go over the whole array on pairs of two - I.e, Array[0] with Array[1], Array[1] with Array[2], etc...
Whenever you find that things are not the way they are supposed to be - in your case, The larger index number is bigger than the lower index number - you swap between them, until you reach an iteration where you passed through the whole array and didnt swap at all.
In case you didn't understand well, here's Pseudo code from wikipedia (OMG who the heck uses wikipedia i'm such a n00b):
procedure bubbleSort( A : list of sortable items )
n = length(A)
repeat
swapped = false
for i = 1 to n-1 inclusive do
/* if this pair is out of order */
if A[i-1] > A[i] then
/* swap them and remember something changed */
swap( A[i-1], A[i] )
swapped = true
end if
end for
until not swapped
end procedure
And here's some C code:
#include <stdio.h>
int main()
{
int array[100], n, c, d, swap;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
for (c = 0 ; c < ( n - 1 ); c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (array[d] > array[d+1]) /* For decreasing order use < */
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
printf("Sorted list in ascending order:\n");
for ( c = 0 ; c < n ; c++ )
printf("%d\n", array[c]);
return 0;
}
Here again, btw, the credit is not for me:
http://www.programmingsimplified.com/c/source-code/c-program-bubble-sort
Hope this helped you, and good luck :)

Resources