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

DHPC1704 - Editorial

$
0
0

PROBLEM LINK:

Contest

Author:Adabelle Xie

DIFFICULTY:

MEDIUM

PREREQUISITES:

Greedy

PROBLEM:

Given a string of ‘X’ and ‘O’ characters, ‘X’ representing a closed building and ‘O’ representing an open building, N boards that can cover any number of consecutive buildings, and a maximum K closed buildings that can be covered by the N boards, find whether or not it is possible to cover all open buildings using N boards, only covering a K closed buildings or fewer.

QUICK EXPLANATION:

For each board, remove the largest contiguous section of closed buildings you can. If after removing N sections, there are more than K closed buildings left, than it is impossible to use N boards to cover all the open buildings only covering K closed buildings. If there are K or fewer buildings left, then it is possible.

EXPLANATION:

This problem is heavily inspired by a problem from the 1999 USACO Spring Open, and USACO has a good explanation on their training site. This problem is optimally solved using a greedy approach. We assume that the best solution only using 2 boards can be modified to yield the best solution for 3 boards. Taking out one contiguous section of buildings from a 2-board solution will yield a 3-board solution. And we always want to remove the largest section of closed buildings possible, as we want to minimize the number of closed stalls covered by the boards. Using one pass through the string, we can find both the number of closed buildings and add the lengths of the contiguous sections of buildings to a max priority queue (in java, a priority queue dequeues smaller integers first, therefore I add the negatives of the lengths then multiply by -1 after the poll operation to reverse the order of removal). Then for the N boards, do N dequeue operations, subtracting each result from the total number of closed stalls we already found. If what is left is less than or equal to K, return “Possible”. Else, return “Impossible”.

AUTHOR'S AND TESTER'S SOLUTIONS:

Author's solution can be found here.


DHPC1705 - Editorial

$
0
0

PROBLEM LINK:

Contest

Author:Adabelle Xie

DIFFICULTY:

MEDIUM

PREREQUISITES:

DP, specifically Kadane's algorithm.

PROBLEM:

Given an array of integers, return the maximum sum of consecutive elements from the array.

QUICK EXPLANATION:

Use Kadane’s algorithm. Keep track of two variables: max and current. For each element in the array, add it to current. If current becomes negative because of this, set it to 0. If current is greater than max, set max equal to current. After going through all the elements in the array, return max.

EXPLANATION:

If all the elements were positive or zero, the maximum sum would include all elements. However, elements in the array can be negative. This means that sometimes we will stop our sum when we encounter a negative number. Other times, including negative numbers is beneficial because positive numbers later in the array result in a net gain from continuing the sum. But if the current sum at any point is negative, we might as well have not included those numbers in the first place and started our sum after the current element. We keep track of the maximum sum we have discovered, and return it after processing all the array elements.

AUTHOR'S AND TESTER'S SOLUTIONS:

Author's solution can be found here.

Playlist to become yellow/red on codechef, codeforces in two months

$
0
0

Everyone wants to improve as soon as they can and reach the top of the leaderboard so I have found a website/community made by one of the best programmers of India Keshav Dhandhania . It looks that he has worked really hard to collect all the famous problems and all the topics that are used by a sport programmer frequently. He has made a playlist which will help to improve your skills very quickly. I am sure it will help each and everyone out there.
COMPETITIVE PROGRAMMING PLAYLIST by Keshav Dhandhania
This is what he says about his playlist:

What to expect, and how to make the most out of this playlist

You're going to learn something new from almost every problem. This implies that it is quite possible that majority of the time, you will not be able to solve the problem in the playlist and will need hints. That's completely okay, just make sure you try to solve each problem for an hour before reading a hint, and go back to solving the problem for 20-30 minutes after reading a hint. If you feel de-motivated, just take a break and talk to people in the community. We are all in the same boat as you.

When you are reading about a new topic, try to solve the motivation problem on your own before watching the videos and reading the tutorial. The algorithms you discover independently will be the ones you remember the best. In fact, they become cherished moments for a lifetime! And this goes without saying, but you're only getting better when you implement things on your own. Copy pasting, or using the language library is only once you feel you have mastered the concept.

Motivation, i.e. why make this playlist?

A lot of people in competitive programming work hard, but not smart. This playlist is all about smart. It is an aim at learning the most in the shortest amount of time. The most popular Quora question on competitive programming is, What is the best strategy to improve my skills in competitive programming in 2-3 months?, this playlist is my answer to that question. It's also trying to answer the question, what problem should I solve next?

Topics covered, and structural overview

The topics covered in this playlist include algorithm analysis, quick-sort, merge-sort, binary search, dynamic programming, graph theory (graph representation, breadth-first search and depth-first search, shortest paths, minimum spanning tree), segment trees and binary indexed trees.

There are multiple problems per topic, and almost a dozen problems each on dynamic programming and graphs, because these two are the most versatile topics in competitive programming.

Expected time to completion

I measure time to learn something in number of sessions (a session is a focused period of say 1.5-2 hours). This playlist should take about 40-60 sessions total, which is about 2-3 months on average depending on how many sessions you do per week.

Pre-requisites

Basic knowledge of any programming language (C++, Java, Python).

ALL THE BEST EVERYONE ^_^ KEEP CODING

HFT Battle 2017

$
0
0

Hi Codechef!

HFT Battle 2017 is going on – the trading algorithms competition, in which every participant can try on an HFT researcher’s hat. The goal is to create a stable and profitable HFT algorithm by researching a market microstructure and a behaviour of the financial instrument. In May we will be hosting another 24-hour competition in code optimization and speeding up based on algorithms created during HFT Battle. We hope that Codechef users will especially like this format :)

During the competition we provide you a set of real HFT-instruments for research and strategy analysis and real market data from one of the world’s largest exchanges. Same as last year, trading conditions are simplified compared to the real ones: there are lower fees and round-trip.

Also there are some significant differences from the previous competition:

  • You are able to create your strategies both in C++ or Python.
  • We made it possible to participate in teams. To do this you should create a single account for the entire team and provide the information about one of the participants during the registration process.
  • You can call out any other participant for a duel, where your strategies can see and affect each other’s transactions. Let the battle begin!

How to start

To make the strategy development easier, we have prepared the sample strategy and collected few ideas for the algorithm improvement at one place with the corresponding code examples.

We suggest you to start with the brief documentation, which will be enough for you to become familiar with the competition system. Also we have developed the offline development package: https://github.com/hftbattle/hftbattle.

The competition ends on the 30th of April 2017. The final testing will be held after that on a set of 20 new trading sessions.

This year TOP-20 participants will be awarded with valuable prizes. The best competitors will be invited to an interview at AIM Tech and will have an opportunity to join our team.

We will be happy to hear your feedback! You may use “Support” button in the web interface or text directly to help@hftbattle.com. You may also join the active discussion of the contest in our Telegram channel!

It is not required to have any specific economical knowledge to create your strategy. Basic C++ or Python skills would be enough. We are confident that most of Codechef participants will be able to reach excellent results!

We wish you high rating and great results in HFT Battle 2017!

Wrong answer in second subtask of CLIQUED.

$
0
0

I solved the problem CLIQUED in the same way as mentioned in the editorail using Dijkstra with little modification.But got wrong answer on the second subtask.

Some one please help me out.

Code link:link text

What is wrong with the following solution for CHEFDIV for April 17 long?

$
0
0

problem link: https://www.codechef.com/APRIL17/problems/CHEFDIV My solution: https://www.codechef.com/viewsolution/13349102

I am calculating prime factors of numbers in the range from A to B and storing them in a set. Then on each step I am finding the number of divisors a number has and then dividing my current number with the prime factor that has the highest power. But somehow 0 is getting stored in the list of primes that I had generated in the set s. The solution gets an AC on 17 tasks out of 19, but fails on 2 tasks because somehow 0 is getting stored in the list of primes. I don't understand why this happens. Thank you.

SPOJ problem YODANESS, query?

$
0
0

I've solved YODANESS using BIT, but problem tag say it can be solved using graph and bitmask also, any insight into how it can be solved using graph and bitmask?

CHEFNUMK - Editorial

$
0
0

PROBLEM LINK:

Contest
Practice

Author:Misha Chorniy
Tester:Tuan Anh Tran Dang
Translators:Sergey Kulik (Russian), Team VNOI (Vietnamese) and Hu Zecong (Mandarin)
Editorialist:Tuan Anh Tran Dang

DIFFICULTY

EASY-MEDIUM

PREREQUISITE

Mo’s algorithm

PROBLEM

Given an array of N integers A[1…N] you have to answer Q queries of the form L R K which requires you to find how many number inside the sub-array A[L…R] that appears no more than K time in that sub-array.

SOLUTION

The query in this problem would be wierd to who are not familiar with Mo’s algorithm. If you don’t know about this algorithm please take a look at the mentioned blog. This will help you solve a class of query problems with O(Nsqrt(N)) when segment tree cannot handle.

The core of Mo’s algorithm is that you maintain the query value of the range after adding/removing elements. The frequencies of numbers can be easily maintained in this fashion. We just need an cnt[] array to keep the frequencies of each numbers. Note that while the number can be as large as 10^9 we can do some precalculation to convert them into the range [1…n]. So now let assume that A[i] ≤ N and cnt[i] is the frequency of the number i in the current range.

Recall that in this problem we need to find the number of numbers that have frequency no more than K. That value equals to the number of numbers in cnt[] array that is less than or equal to K. Now it comes to the tricky part. Let above[] array where above[i] is the number of numbers in cnt[] that is larger than i. We can see that when we add/remove elements in the current range in Mo’s Algorithm we will change the value of one element in cnt[]. More specifically we need to increase or decrease an element of cnt[] by one when adding/removing one element into the current range. Let’s see how this effect the above[] array.

  • When increase cnt[i] by one: let’s call the value of cnt[i] before the increment is v then after the increment there is one more number in cnt[] that is larger then v so we just need to increase above[v] or basically we need to increase above[cnt[i]] before do so with cnt[].
  • Similary when decrease cnt[i] we need to decrease above[cnt[i]] after that because there is now one less number in cnt[] that is larger than cnt[i].

Now we have cnt[] and above[] all being maintained corresponding to the current range. Now one question is left - What is the answer for the current query? Some of you might see that it is already there: above[0] - above[k]. above[0] is the number of numbers in cnt[] that is larger than 0 which means the number of distinct values in the current range. above[k] is the number of distinct values that is have frequency more than k in the range.

AUTHOR'S AND TESTER'S SOLUTIONS:

setter
tester


Unfair ratings in IOPC 2017

$
0
0

So in the contest this happened -

There were some extra whitespaces at the end of lines in the testdata of Problem C. It has been fixed now, and all submissions will be re-judged at the end of the contest so that no penalty is incurred due to this. We apologize for the error.

Because of this I wasted an hour and a few wrong submission. The whitespaces issue happened only to python users because they take the whitespace as well while taking the input. So a similar thing happened in March Cook-Off but in that contest the ratings were removed. Please make this contest un-rated as well. I don't have issues because of the whitespace issue as I should have moved on with the other problems but then in that case you should make March Cook-Off rated.

Secondly they didn't even remove the penalty for the wrong(although correct) submissions.
See here - https://www.codechef.com/rankings/IOPC2017?filterBy=Institution%20type%3DSchool%3BCountry%3DIndia&order=asc&sortBy=rank

My score is giving 2(-8) where as it should be 2(-6).

Because of these reasons I incurred a loss of 148 rating.

@admin please see, time of 1hr+2 wrong submissions = 1hr 40 mins is a lot of time wasted.

MCO16504 - Editorial

$
0
0

PROBLEM LINK:

PracticeContest

Author:Zi Song Yeoh

DIFFICULTY:

MEDIUM

PREREQUISITES:

PARALLEL BINARY SEARCH, DISJOINT SET UNION

PROBLEM:

You have a graph. On some days, roads are destroyed. On some days, some people in some vertices are killed. Happiness of a student is the number of students in its connected component. For each query $(u, v)$, find the maximum day such that the total happiness of student $u$ and $v$ is still at least $V$.

EXPLANATION:

First, a naive solution is to solve each query independently. Instead of destroying roads and killing students, we reverse the entire process and add students and roads instead. Now, with a fixed $v$ as target, we can use DSU to perform the updates in reverse and find the first day where the two students in the query has total happiness $\ge V$. This solution works in $O(n\alpha n)$ per query.

Now, we need to find a way to not reconstruct the DSU every query. We'll use a technique called parallel binary search. There's a tutorial of it here. Once you understand how it works, it's very easy to relate it here. Instead of using a segment tree as in the article, we just replace it with a DSU instead. You can refer to the sample solutions for how to implement it for this problem.

AUTHOR'S AND TESTER'S SOLUTIONS:

Author's solution can be found here.

Tester's solution can be found here.

RELATED PROBLEMS:

DGCD - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

DIFFICULTY:

Hard

PREREQUISITES:

Number theory, Segment Trees, Heavy Light Decomposition

PROBLEM:

You're given a tree of N vertices. Each vertex has a number written on it. Process two types of queries :

  1. Add d (input) to numbers of all vertices along the unique path between vertices u and v (both input)
  2. Find out GCD of all numbers on the vertices along unique path between vertices u and v (both input).

QUICK EXPLANATION:

Use Heavy Light Decomposition of the tree to reduce problem to only linear paths. Use the fact that gcd(a, b, c, d..) = gcd(a, b-a, c-b, d-c...) to change segment updates to point updates.

DETAILED EXPLANATION:

It's a difficult problem and as with many other difficult problems as well - the secret of solving this problem is solving a simplification of the problem.

Simplification : Given tree is a linear path
So what can we do if given tree is a linear path? Now our change operations is reduced to to addition of a constant to a contiguous sub-array and our find opertion reduces to finding out gcd of all numbers on a contiguous sub-array. Experienced programmers would've seen immediately that a datastructure like segment tree with technique of lazy propogation could be useful for this problem, however what information is to be stored at each segment, that is not obvious. There are two very simple identities at the core of this problem. Assume (a,b) represents gcd(a,b).

  1. (a,b) = (a,b-a)
  2. (a,b,c) = (a,(b,c)) = ((a,b),c)

It is still not clear how these help us. Let us first try to see how gcd is changed (or rather how it is not changed) when we increment all the numbers of a sequence.

Say G = (A1,A2,...,An) and G' = (A1 + k, A2 + k, ... An + k)
Now using identities 1 and 2 we can say that :G is same as (A1, A2 - A1, A3 - A2..., An-An-1)
=> G = (A1, (A2-A1, A3-A2...., An- An-1))

So similarly G' = ( A1 + k, A2 + k - (A1 + k) , ...., An + k - (An-1 + k) )
=> G' = ( A1 + k, A2 - A1, A3 - A2, ..... An - An-1 )
=> G' = ( A1 + k, (A2-A1, A3-A2, ....., An - An-1 ))

Now call { A2-A1, A3-A2, ...., An - An-1 } as the difference sequence. So if we compare G and G', we see that much of the information has been retained through the gcd of the difference sequence. In particular it tells us what information we need to store at each segment of segment tree: first number of the sequence and the gcd of the difference sequence. With this information, its easy to find gcd of the segment : its the gcd of first number and gcd of difference sequence.

It's also easy to increment all numbers of the sequence by d, gcd of difference sequence remains unchanged and the first number increments by d. If we want to merge two consecutive smaller segments to make a larger segment, as we'd need to do with segment trees, we also need to store the last number of the segment.

Using this, it is easy to write a segment tree which can do all operations in O(logN) time, making it an O( (N + Q) * logN) solution.

Back to original problem:

We can solve original problem with the help of a technique called Heavy Light Decomposition of a tree. Essential idea is as follows. We divide the vertex set of the tree in O(N) linear chains such that following property holds : On the unique path between any two vertices u and v, there are utmost 2 * log(N) different chains. If we can find such a decomposition, we could build individual segment trees on each of these chains. Now a single query would correspond to quries on each of these O(log N) chains making a single query O( (log N)2) overall.

I'm not going to explain Heavy Light Decomposition here - rather I'd leave you with an exceptionally well written description of this technique. I myself learnt this technique from here.

SETTER'S SOLUTION:

Can be found here.

TESTER'S SOLUTION:

Can be found here.

RELATED PROBLEMS:

QTREE on Spoj
QTREE3 on Spoj
IPSC 2009 problem L

REFERENCES:

WCIPEG wiki

CS Academy Round #29 (Div. 2 only) with Special Prizes

$
0
0

Hi all,

I would like to invite you to CS Academy's next contest which takes place on Wednesday. There will be 3 special prizes awarded randomly to Div. 2 participants. The prizes consist of private coaching lessons with me. You can find out more details on the contest page.

You are welcome to join. Good luck!

Finds the missing numbers.

$
0
0

Please tell me - How to finds the missing numbers from 1 to n. I can not understand how to solve this.

Input: int array[] = { 1, 2, 3, 4, 6, 7, 8, 9, 12 }

Output: Missing number(s): 5, 11.

Getting started here, questions about strategy, etiquitte, etc.

$
0
0

Hi guys.

I've just started here, I have a few questions about how I approach this place. Firstly, let me just say that wow - some of the problems here are pretty difficult, even for easy!

Alright, so I've just bunch of the questions in the FAQ, here's a few more.

  1. What's the etiquette for posting here? For example are 'I'm working XYZ practice problem, I've got TLE error, here's my code, what should I do?' questions ok?

  2. What's the general strategy for solving problem, or doing time optimization? Are there any tools that you use? Like, one of the things I can see that would be problematic, is when you get a 'wrong answer' but you don't know what the 'expected vs output' is. Is this just something you need to deal with as a programmer, to think of the corner cases yourself?

  3. Is there any way to get additional test data?

  4. How do you organise your code chef files in your IDE? For example, your class name (in Java) must called Main, and it can't be part of any package, when you paste in to the submitter, otherwise it'll give you an error, wondering how people deal with that.

  5. code reusablity - I get the feeling that a lot of this is going to be using various appropriate algorithms. What I would tend to do is import the package that contains the algorithm. But given that the submission has to be a single file with no non-native imports, is the only thing you can do, is copy the code in for each algorithm?

  6. Where would you start in terms of first problems to solve? For example I would suggest doing the Enormous Input test as one of your first problems.

.

CLIQUED - Editorial

$
0
0

PROBLEM LINK

Practice
Contest

DIFFICULTY

easy

PREREQUISITES

graph theory, Dijkstra's algorithm, transforming graph into similar graph

PROBLEM

You are given a undirected weighted graph consisting of $n$ vertices, and $m$ edges. Initially there is no edge between any pair of first $K$ vertices. We add the edge between each pair of first $K$ vertices of weight $X$ (i.e. the first $K$ vertices form a clique). Given a source vertex $s$, find out the shortest distance of each node from vertex $s$.

Finding the shortest distance in a weighted graph from a fixed source vertex is a classical problem. There is a famous greedy algorithm called Dijkstra's algorithm which can solve this problem in $\mathcal{O}((|V| + E|) log (|V|))$ time.

If we directly apply the Dijkstra's algorithm in our problem, the number of vertices, i.e. $|V| = n$, and the number of edges, i.e. $|E| = m$ + $\binom{K}{2}$ (due to the clique). Hence, the time complexity of this algorithm will be $\mathcal{O}((m + K^2) \, log (n))$, which is enough to solve the first subtask, but won't be sufficient to solve the final subtask.

Solution by constructing another graph

One of the ways of dealing with such situations is to think whether it is possible to convert the given graph into another graph that doesn't have $\mathcal{O}(K^2)$ edges of the clique added in it, and yet it preserves the pairwise distances of the vertices of the original graph.

We can do this in the following way. Let us create a fake vertex. This fake vertex will be connected to the each of the first $K$ vertices. The weight of each edge will be $\frac{X}{2}$. So now, instead of the first $K$ vertices being connected in the form of clique are connected to the fake vertex in the form of a star topology where the central node of star is the fake vertex.

// Add an image.

Thus we have $K$ edges in the modified graph instead of $K^2$ edges of the original graph. The remaining edges in the modified graph will remain same. Notice that the distances in the modified graph are precisely the same as that of in the old graph. Here the edge connecting vertices $u$ and $v$ (where $u, v \leq K$) with weight $X$ directly has been replaced with the $u$ being connected with fake vertex with distance $\frac{X}{2}$, and from the fake vertex with $v$ with distance $\frac{X}{2}$.

Apply Dijkstra's algorithm on this modified graph will yield a time complexity of $\mathcal{O}((m + K) log (n))$ which will give you full score.

A small detail which can be useful here. As the number $\frac{X}{2}$ will not be an integer when $X$ is odd. So, instead of dealing with non-integers (reals) in the Dijkstra's algorithm, you can multiply all the distances by $2$ to make all the distances even. Finally you divide the final distances by 2 to get the actual answer. In this way, you will never have to deal with real numbers.

Solution by applying the usual Dijkstra with a little twist

You can apply the usual Dijkstra's algorithm. Let $d[i]$ denote the distance of vertex $i$ from source vertex $s$. When you are first time processing one of the vertices belonging to the clique, say vertex $u$, you consider the distances of all other vertices in the clique to be $d[u] + X$. Afterwards, whenever you encounter a vertex in clique, you need not to go over the clique edges to relax the distances of clique vertices. This algorithm will make sure that your time complexity is $\mathcal{O}((m + K) log (n))$, as instead of processing all the $K^2$ edges of clique, you are processing only $K$ of them.

A solution by trusting your intuition and implement direct Dijkstra with a bit modification.

One might intuitively think that the number of relaxations in the Dijkstra's algorithm might be $m + K$ instead of $m + K^2$. Proof of this intuition lies in the understanding of previous algorithm.

You can directly implement this algorithm. You maintain a set (balanced binary search tree) of the clique vertices sorted by their distances in the increasing order. You can find the set of vertices to relax by making a search in the set. This way, you will only be relaxing the vertices only among the necessary vertices in the clique. See the editorialist's solution for a sample implementation of this approach.

SETTER'S SOLUTION

Setter

TESTER'S SOLUTION

Tester2
Tester3


Problem in solving hackerearth's balance brackets problem

$
0
0

I was solving balance brackets problems on hackerearth. I solved the problem but my solution is not passing one test case. This is link to my problem.

Please tell me what is wrong with my code and tell me the correct approach for it.

CODECHEF Attendance

$
0
0

Hey There Guys,

Hope You all are having a good time. I want to present you another tool which can show you your attendance in CodeChef.

This is especially useful for those who want to check their Attendance for the 100% Attendance prize category recently introduced to CodeChef.

Not Writing any further (need to study for exams :p)

Please leave your comments below.

alt text

MAJOR CHANGES

I literally wrote the entire code for the site again from scratch today morning (LITERALLY).

There were mainly 2 problems :

  1. The MARCH COOK OFF getting unrated, so even if some one participated in that, it was still showing that the person didn't take part.

  2. Even if a person did not solve any problem correctly and their rating changes (might happen if someone submits but doesn't get AC in any of their submissions) will still be shown as present.

These 2 problems were there because I was scraping the change of ratings instead of the number of Problems solved (which was actually needed).

But no worries people, It's been fixed now.

Also as I already mentioned that I wrote the entire code again (major parts), there might be some new bugs waiting for me to fix. So please Let me Know. Peace.

Here's The Link to the site.

Thank You.

When will be the May CookOff 2017?

$
0
0

Usually the CookOff takes place on 21st or 22nd day of the month. But In this month we have the grand event SnackDown 2017 Qualifier from 20th-24th May.

So will the CookOff be held simultaneously with SnackDown in due date this month or will it postponed , making it closer to May Lunchtime?

REARRSTR - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Praveen Dhinwa
Tester:Utkarsh Lath
Editorialist:Balajiganapathi Senthilnathan
Russian Translator:Sergey Kulik
Mandarian Translator:Gedi Zheng

DIFFICULTY:

Easy

PREREQUISITES:

Greedy

PROBLEM:

Given a string $s$, can you rearrange it such that no two consecutive characters are equal? If yes, print any such rearrangement.

SHORT EXPLANATION

We will use the following greedy algorithm. At each position, the character we are going to put will be the one with highest frequency and is not equal to previous character.

In other words, count the frequency of each character. For each position, select the highest frequency character which is not equal to the previous character. Decrement the frequency of this character. If such a character does not exist for any position, then a rearrangement is not possible.

EXPLANATION:

First we note that only the count of characters in the string $s$ matters i.e. the initial order of characters in the string $s$ does not matter.

Let us try to build the string from left to right. Intuitively, we want that the remaining highest frequency of the characters should be as low as possible (i.e. if a character has very high frequency, then it is tough for us to accommodate the no two consecutive equal characters condition).

So, for each position we will try to place the character with highest frequency such that it is not equal to previous character. If we have put all the characters in such way, then we are done. Otherwise we can prove that the arrangement is not possible and we output -1.

Time Complexity:

$O (n)$

Author's Solution

Let us take a string $s$ = "abbcc". Now, in this example, we have a bad space between the two b's and between the two c's. In the corresponding string "ab-bc-c", bad spaces are denoted by "-". Formally, we define number of bad spaces as number of places where we should insert some character different from it's previous and next one to make sure that string is valid.

Now, let us take most basic case for which it would be impossible to arrange the characters in the desired way. If the higest frequency character has size more than half of size the string, then it is impossible to construct the valid string because number of bad spaces by putting highest frequency frequency will be at least $\lceil \frac{n}{2} \rceil$.

Let us take the characters from in decreasing order of their frequency. Initially, we take the first character and put all its occurrences linearly. So, it we have total $k$ characters, we will have $k - 1$ bad spaces initially. Now, iteratively, we will reduce number of bad spaces. Now, we will take the next character and by using it, first we will first greedily remove as many bad spaces as possible. Now, if all the bad spaces are removed, then, we will try to create least amount of bad spaces as possible. Note that this process will reduce number of bad spaces strictly. As, you are processing characters one by one, and for a fixed character, you can have at most $\mathcal{O}(n)$ time. So total time will be $\mathcal{O}(26 * n)$ which will fit in the time. Please see author's solution from for more details.

AUTHOR'S AND TESTER'S SOLUTIONS:

Author's solution
Tester's solution

Internal error in MAY17 challenge problem

$
0
0

Hi!

I get the error ":( internal error occurred in the system" when I submit my solution for the challenge problem. Can someone please let me know what does this mean?

I searched for other similar threads and the replies are that the problem is on server side but I see that others are getting proper verdict for their solutions.

Thanks!

Viewing all 39796 articles
Browse latest View live


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