Quantcast
Channel: CodeChef Discuss - latest questions
Viewing all 40121 articles
Browse latest View live

StopStalk: Tool to maintain your algorithmic progress

$
0
0

Hello Coders,

Hope you are having a great time coding hard. Here I present to you a Utility tool - StopStalk which will encourage you to keep your algorithmic progress going by coding with your friends and improve.

It retrieves your friends’ recent submissions from various competitive websites(CodeChef, Codeforces, Spoj, HackerEarth and HackerRank for now) and shows you in one place. It includes lots of other features like - User streak notification, Global Leaderboard, Filter submissions, search problems by tags, and a lot more… You can send friend requests to your friends on StopStalk or you can also add a Custom User. Register here - StopStalk

The goal is to involve more and more people to Algorithmic Programming and maintain their streak. Also the project is completely Open Source - Github

Feel free to contribute. :)

We would be happy to hear from you - bugs, enhancements, feature-requests, appreciation, etc. In the end - Stop Stalking and start StopStalking! Happy coding!

PS: We update our database every 24 hrs but just for today we will update it every 3 hrs. So don’t miss this opportunity to register.


Doubt in Time complexity

$
0
0

There is a question Chef and Numbers. According to Editorial it is purely based on FFT having overall time complexity $O(n * log(n))$. But after crawling other solution i found one of the solution which is Based on Dynamic programming. So the doubt is about it's time complexity which seems to be $O(n^2)$.

Can anyone tell me the full explanation about it's real complexity of that ACsolution?

SPOJ - Problem AGGRCOW - Aggressive cows

$
0
0

I cannot understand how binary search will solve the problem.

Problem statement is here

Need Help! Thanks :)

Chef and Array-Editorial

$
0
0

PROBLEM LINK-https://www.codechef.com/problems/EXPCODE1

Author:https://www.codechef.com/users/vivek96

DIFFICULTY:EASY

PREREQUISITES:Array,Sorting

PROBLEM:Being a programmer, Chef like arrays lot. On Chef' birthday,Chef friends given him an array "a" consists of n distinct integers. Unfortunately, the size of array "a" is too small. Chef want a bigger array!,Chef friends agree to give him an bigger array. but only if Chef is able to answer the following questions correctly: 1-Largest element in array a 2-Kth largest element Help him for getting bigger Array!

EXPLANATION:First We need Largest Element in the Array,so we have to Sort the Array,you can use any sorting technique(bubble sort,quick sort,etc) because there is no issue of Constraints and then print the largest element in array a[ n-1 ],Then answer for 2nd Question is print a[n-k],because we know the kth largest element is at position n-k

Algorithm:

begin BubbleSort(list)

for all elements of list

  if list[i] greater list[i+1]
     swap(list[i], list[i+1])
  end if
  end for

return list
end BubbleSort

Implementation: https://goo.gl/oKM4kb

AUTHOR'S AND TESTER'S SOLUTIONS:http://campus.codechef.com/EXCO17TS/viewsolution/13037182/

Edit1-Link+Corrections

LEDIV - Editorial

$
0
0

PROBLEM LINK

Practice
Contest

DIFFICULTY

SIMPLE

PREREQUISITES

Simple Math

PROBLEM

You are given a list of numbers. You have to find the smalelst number which divides all these numbers.

QUICK EXPLANATION

To the initiated, this question should be a breeze.

  • Find the GCD of the list of numbers.
  • Find the smallest prime factor of the GCD.

EXPLANATION

The GCD of two numbers can be found using the Euclid's Algorithm.

gcd(a,b)
    return (b == 0) ?
        a : gcd(b, (a mod b))

The GCD of a list of numbers A[1 ... N] can be found as

let G = 0

for i = 1 to N G = gcd( A[i], G )

The above is intuitive and easy to prove by induction.

Now, the next step is to find the smallest prime factor of the GCD. Calculating this can be done in O(sqrt(N)) time easily.

for i = 2 to floor(sqrt(G))
    if G is divisible by i
        return i
return G  // Since G is prime!

This calculation is probably the most time consuming step in the solution. Although, iterating till sqrt(G) will fit within the time limit, you can make one optimization to make it faster. That optimization is pre-calculation! You can pre-calculate the smallest primes in the factorization of any number by sieving.

Consider the snippet below

smallestPrime[ 2 ... N ] // We will store our answers here
for i = 2 to N
    smallestPrime[i] = i
for i = 2 to N
    if smallestPrime[i] = i
        for j = 2*i to N, step-size i
            smallestPrime[j] = min( smallestPrime[j], i )

Notice how we modify the step in which in the usual Sieve of Eratosthenes, we set the multiples of i as non-prime. In this step now, we are simply updating the smallestPrime array at index j. This is a very clever trick to master while solving problems. When you deal with a problem where you need to perform an operation based on all prime factors of a number (like in this case, we wanted to find the smallest of them), a small code snippet like above is usually needed.

SETTERS SOLUTION

Can be found here.

TESTERS SOLUTION

Can be found here.

DataBread : Tool to Track your Algorithmic Ratings.

$
0
0

Hello Coders,

Hope you are having a great time. I take the pleasure in introducing you to DataBread where you can see all your friends ratings from different competitive programming websites (Codechef, SPOJ, HackerEarth, HackerRank and Codeforces for now) at one place (called databread ratings).

It includes a leaderboard which you can filter by your Institution or Country and compare your ratings with your friends easily. Find your friends easily and view their profile, all at a single place.

It also includes a feature to link your linkedIn profile on your profile page. Feel free to contribute.

I would love to hear if you have some great suggestions or found any bugs

EDIT: So guys Finally the site is completely up, Hackerrank Ratings also working now, Leaderboard will be updated in a few minutes. You may wish to check your standings now.

And here's our new facebook page. If you like databread then share.

EDIT:

Added option to sharedatabread with your friends.

EDIT

Small but an important update. Find out here.

So for now

All The Best

Code Hard

Can someone please provide me with Editorial of Problem BASE (December Long Challenge 2016)

Chef and Ola Cab-Editorial

$
0
0

PROBLEM LINK:https://www.codechef.com/problems/EXPCODE2

Author:https://www.codechef.com/users/vivek96

DIFFICULTY:EASY

PREREQUISITES:Basic Maths,Math Functions

PROBLEM: Chef want to book Ola Cab,he have to take ride from point one (xi,yi) to second point (xj,yj),Ola cost N rupees per unit, Chef have R rupees in his pocket, You have to help Chef to find Whether he have suffiecient amount of money in his pocket for paying to ola.

if yes print “yes”(without quotes) else print “no”(without quotes)

EXPLANATION: From the Question,its clear we have to find distance between two points.

Distance Formula: Given the two points (x1, y1) and (x2, y2), the distance d between these points is given by the:alt text

find the distance d between 2 points then we know ola cost N rupees per unit so,

total cost=d(distance) * N(Cost of Per Unit).

so if total cost<=R(Amount chef have in his pocket) then Print yes else print no

AUTHOR'S AND TESTER'S SOLUTIONS:

class chefandolacab {

public static void main(String[] args)

{

    Scanner sc=new Scanner(System.in);

    int x1=sc.nextInt();

    int y1=sc.nextInt();

    int x2=sc.nextInt();

    int y2=sc.nextInt();

    int r=sc.nextInt();

    int n=sc.nextInt();

    double dist=Math.ceil(Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)));

    if(dist*r<=n)
    System.out.println("yes");

    else
        System.out.println("no");

}

}

Edit-Correction :)


Easy One-Electricity Bill Editorial

$
0
0

Problem Link:https://www.codechef.com/problems/EXOCODE7/

Author:https://www.codechef.com/users/vivek96

DIFFICULTY:Cakewalk

PREREQUISITES:basic programming,basic maths

PROBLEM:Chef wants to calculate his Electricity bill,Help him to do so

Acc to Conditions:-

For First 50 units Rs 0.50/unit

For next 100 units Rs 0.75/unit

For next 100 units Rs 1.20/unit

For unit above 250 Rs 1.50/unit

An additional surcharge of 20% is added to the bill

EXPLANATION: Below is the step by step descriptive logic to compute electricity bill.

1-Read units consumed by the customer in some variable say unit.

2-If user consumed less or equal to 50 units. Then amt = unit * 0.50.

3-If user consumed more than 50 units but less than 100 units. Then add the first 50 units amount i.e. 25 to the final amount and compute the rest 50 units amount. Which is given by amt = 25 + (unit-50) * 0.75. I have used units-50, since I already calculated first 50 units which is 25.

4-Likewise check rest of the conditions and calculate total amount.

5-After calculating total amount. Calculate the surcharge amount i.e. sur_charge = total_amt * 0.20. Add the surcharge amount to net amount. Which is given by net_amt = total_amt + sur_charge.

AUTHOR'S AND TESTER'S SOLUTIONS:

include <stdio>

int main()

{

int unit;

float amt, total_amt, sur_charge;

/*
 * Read unit consumed from user
 */
printf("Enter total units consumed: ");
scanf("%d", &unit);


/*
 * Calculate electricity bill according to given conditions
 */

if(unit less then equal to 50)
{
    amt = unit * 0.50;
}
else if(unit less then equal to 150)
{
    amt = 25 + ((unit-50)*0.75);
}
else if(unit less then equal to 250)
{
    amt = 100 + ((unit-150)*1.20);
}
else
{
    amt = 220 + ((unit-250)*1.50);
}

/*
 * Calculate total electricity bill
 * after adding surcharge
 */
sur_charge = amt * 0.20;
total_amt  = amt + sur_charge;

printf("%.2f", total_amt);

return 0;

}

Note-->printf("%.2f) is use for controlling precission

ALEXNUMB - Editorial

$
0
0

Problem: You are given an array of N numbers. You are to find the number of pairs of numbers in the array s.t a[i] < a[j].

Solution: First you find the set of all distinct elements in the array {x(1), ..., x(M)} with x(i) < x(i+1) and their corresponding counts {c(1),...,c(M). Now it is easy to see that the required number of such pairs is Sum_{i} (c(i) * (c(1)+..c(i-1)) This is simply Sum_{i} (c(i) * c_cumulative(i-1)) where c_cumulative(k) is the cumulative sum of c() that can be computed in O(M) time. Thus, the total counts of such pairs can be computed in O(N).

Chef and Palindrome Editorial

$
0
0

Problem Link:https://www.codechef.com/problems/EXOCODE3

Author:https://www.codechef.com/users/vivek96

DIFFICULTY:Medium

PREREQUISITES:Algorithms,Hashing,Array,String

PROBLEM:Chef like palindrome strings more than normal trings ,so chef Just want to check if characters of a given string can be rearranged to form a palindrome string or not.

Help him to check, print YES if its possible,else print NO

EXPLANATION:

Palindrome String:A string is said to be palindrome if reverse of the string is same as string. For example, “abba” is palindrome, but “abbc” is not palindrome

A set of characters can form a palindrome if at most one character occurs odd number of times and all characters occur even number of times.

A simple solution is to run two loops, the outer loop picks all characters one by one, the inner loop counts number of occurrences of the picked character. We keep track of odd counts. Time complexity of this solution is O(n^2),This will lead to tle(Time Limit Exceeded)

We can do it in O(n) time using a hash array. Following are detailed steps.

1) Create a hash array,which is typically of size 26 because string "s" will contains only lowercase alphabets. Initialize all values of count array as 0.

2) Traverse the given string and increment count of every character.

3) Traverse the hash array if the hash array has less than or equal to one odd value then answer is YES else NO

AUTHOR'S AND TESTER'S SOLUTIONS:

import java.util.Scanner;

class chefandpalindrome

{

public static void main(String[] args)

{

    Scanner sc=new Scanner(System.in);

    String s=sc.next();

    int hash[]=new int[26];

    for(int i=0;i<s.length();i++)
    {

       hash[s.charAt(i)-97]++;  //hashing is done here

    }

    int cnt=0;

    for(int i=0;i<26;i++)
    {

       if(hash[i]%2!=0 && hash[i]!=0) //check the hash array
           cnt++;

    }


    if(cnt<=1)
        System.out.println("YES");
    else
        System.out.println("NO");
        }

}

Chef and Array Update Editorial

$
0
0

Problem Link:https://www.codechef.com/problems/EXOCODE4

Author:https://www.codechef.com/users/vivek96

DIFFICULTY:CakeWalk

PREREQUISITES:Basic Programming,Array

PROBLEM:Chef Purchased an array A having N Integer values,After Playing it for while,he got bored of it and decided to update value of its element.In one second he can increase value of each array element by 1.He wants each array element’s value to become greater than or equal to K.

Please Help Chef to find out the minimum amount of time it will take,for him to do so..

EXPLANATION:Since we can only increase all the elements by 1, the minimum element will take most step to reach K.So we have to find the minimum element in array A and answer will difference between K and minimum element.

One corner case is if K is less than minimum element in the array A

Time Complexity:O(N)

AUTHOR'S AND TESTER'S SOLUTIONS:

alt text

Note: We can also use Sorting(Bubble,Quick,etc) to find minimum element in Array, but this will increase time complexity

Chef and Weird Spider Editorial

$
0
0

Problem Link:https://www.codechef.com/EXCO2017/problems/EXOCODE6

Author:https://www.codechef.com/users/vivek96

DIFFICULTY:Easy

PREREQUISITES:Conditional statements and loops,Basic Programming

PROBLEM:Chef School of Witchcraft and Wizardry is known for moulding young minds into the finest wizards and witches. However that comes with a lot of practice. One of the young wizards cast a spell on a spider that makes it leap greater distances.

On observing closely the spider leaped 1 meter in its first leap. 10 meters in its second leap, 19 meters in its third leap , 28 meters in its fourth leap, 37 meters in its fifth leap and so on following a pattern.

In order to capture the spider, the young wizard must be able to tell the number of leaps the spider would take to reach a given distance.

EXPLANATION:It is clear that leap length is increased by 9 in every leap,So Now we have to count the minimum number of leaps required to a cover a distance >=N,so we count minimum no of leaps by using while(true) loop because we dont know the number of iterations exactly required to find minimum no of leaps.

Output must be in format: Case #1: (answer)

AUTHOR'S AND TESTER'S SOLUTIONS:

include<iostream>

alt text

Please share , Your Logic for solving INTERVAL feb17

$
0
0

What was the logic in this question . I could solve it only for m=2 . Please explain the logic in simple way , I am a mere beginner.

Editorial for KBIGNUMB required!!


Please Correct my logic for SCHEDULE March 17

$
0
0

I calculated all the continuous lengths(1,2,6,7....) , then I went on reducing k(k--) to convert all segments(l_seg) of a particular length (z) into three segments of lengths 1,(2 of l_seg/2)(odd), (l_seg/2,l_seg/2 -1)(even) and removed the original length and it's count by these three lengths of samecount . When the highest length reached 2 I calculated the minimum no of flips required to make it 1 by adding the alternate distances between segments of length 2 and then taking the minimum of two len, if it was less than k , ans is 1 or its two . at any point if k becomes 0 ans is the length of next big segment , if k becomes less than 0 than ans is that particular segment.

Please tell me where is it wrong , I was getting 5 of 9 cases correct.

HS08TEST - Editorial

$
0
0

PROBLEM LINK:

Practice

Author:ADMIN

Editorialist:SUSHANT AGARWAL

DIFFICULTY:

CAKEWALK

PREREQUISITES:

Basic looping,Basic Input/Output,Data Types

EXPLANATION:

Please refer to the sample solution given by editorialist.

EDITORIALIST'S SOLUTION:

Editorialist's solution can be found here.

Invitation to Alkhwarizm-2017

$
0
0

alt text
The much awaited signature event of IIIT Allahabad's Tech Fest Aparoksha 2017- ALKHWARIZM is here to endeavour with a challenging problem set.
It will be a 5 hour individual contest with algorithmic problem-set of diverse nature to be hosted on Codechef.
Contest Link is here - ALKHWARIZM-2017
Prize money worth INR 30k and other exciting goodies await you.
CODE ON!!
So be ready to have a nail biting experience on March 24th, 2017 - 9 pm to 2 am IST.
Register right now at the link given below to be eligible for prize money -
Form

Problem Setters- Man Mohan Mishra , Shiv Dhingra , Shivam Garg , Ankit Rao

Facebook Event page - Event

CHEFYODA unofficial Editorial

$
0
0

CHEFYODA
Contest link
Let's consider Game1 in which only horizontal and vertical movements are allowed, One can easily see that yoda wins only when both N and M are odd.

In the other game, chef wins only when both N and M are even.

This reduces the problem to following

  • If chef is winning in both the games, output 1
  • If chef is losing in both the games, and P $\neq$ 0 , output 0. Else if P = 0, then output 1.
  • If chef is losing in 1 game and winning in other, then we need to calculate probbability of winning atleast P games out of K.

    This is given by binomial distribution as $\frac1 2^K $ $\sum_{i=P}^{K}$ $K\choose i$

    Now the task is to calculate $K\choose i$ for i = P to K. You can calculate this by using BigDecimal in Java or using Decimal in python. This would work for small test case and would give you 40 points. For large testcase, this would result in TLE, even if you set precision to 6 decimal places.

    Now, sum of last K - P terms is equal to sum of first K - P terms

    $\sum_{i=P}^{K}$ $K\choose i$ = $\sum_{i=0}^{K - P}$ $K\choose i$

    and as per following

    $\sum_{i=0}^{K - P}$ $ \le 2^{K - 1} \exp\frac{(K - 2(K - P) - 2)^2}{4(1+(K - P) -K)}$

    since Probability is $\frac1 2^K $ $\sum_{i=0}^{K - P}$ $K\choose i$, we have

    Probability $\le 2 ^{-1} \exp\frac{(K - 2(K - P) - 2)^2}{4(1+(K - P) -K)}$

    Now, for small values of P, probability would be close to 1 and we could answer 1 instead of finding out probability. Similarly, for large values of P, probability would be close to 0 and we could answer 0 instead of finding the probability.

    The first difference in output would occur when Probability = $10^{-6}$

    We can find the value of P by following

    $10 ^ {-6} = 2 ^{-1} \exp\frac{(K - 2(K - P) - 2)^2}{4(1+(K - P) -K)}$

    Substituting K = $10 ^ 5$ gives P = 49162 and 50821 Substituting K = $10 ^ 6$ gives P = 497370 and 502614

    Observe that these values are pretty close to $ \frac K 2$. We know that sum of all terms is $2^K$ and that the series is symetric. Therefore, sum of $ \frac K 2$ terms is $2^{K - 1}$. Now, we need to add or subtract atmost 3000 Terms from $2^{K - 1}$ to get probability.

    This can be done within the given timelimit and here is thecode

    You can also do it using Python Libraries code

SPOJ - HISTOGRA - Largest Rectangle in a Histogram help needed

$
0
0

Since I couldn't solve the problem myself, I read up the concept and codes and managed to get it submitted via a Divide and Conquer (divide from middle) approach and a stack based O(n) solution. I also came up with a segment tree solution but it seems to be giving me a wrong answer. I've referred to different segment tree solutions but can't seem to fix mine. Can anyone check out my approach and tell me what's wrong here? (It gives me correct answer on the test cases provided)

http://ideone.com/VDtOML

Thanks!

Viewing all 40121 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>