Quantcast
Viewing all 40121 articles
Browse latest View live

LEBOMBS - Editorial

PROBLEM LINK:

Practice
Contest

DIFFICULTY:

Cake walk

PREREQUISITES:

None

PROBLEM:

You're given an array of houses some of which have a bomb and others don't. These bombs will explode simultaneously and when bomb in ith house explodes, it destroys adjacent houses. Your task is to find out the number of houses which aren't destroyed.

QUICK EXPLANATION:

For every house check if it is destroyed or not.

DETAILED EXPLANATION:

There are two almost similar ways of solving this problem. Key idea is to find out for each house if it is destroyed or not. How do we check if ith house will be destroyed or not? It will be destroyed iff at least one of i-1, i and i+1th houses have a bomb. Just beware of the boundaries as first and last houses have only one adjacent house. So final solution is :

saved_count = 0
for i from 1 to N
    destroyed = false
    if( S[i] == '1') destroyed = true
    if( i > 1 and S[i-1] == '1') destroyed = true
    if( i < N and S[i+1] == '1') destroyed = true
    if( not destroyed)
        saved_count += 1
print saved_count

An alternative solution would be to move over houses with bombs and mark those houses that will explode.

bool will_be_destroyed [N]
fill( will_be_destroyed, false)

for i from 1 to N
    if S[i] == '1'
        will_be_destroyed[i] = true
        if(i > 1) will_be_destroyed[i-1] = true
        if(i < N) will_be_destroyed[i+1] = true

saved_count = 0
for i from 1 to N
    if(not will_be_destroyed[i])
        saved_count += 1

print saved_count

Both of these are O(N) solutions and very comfortably fit in time limit.

SETTER'S SOLUTION:

Will be uploaded soon.

TESTER'S SOLUTION:

Can be found here.


GOODBAD - Editorial

PROBLEM LINK:

Practice
Contest

Author:Praveen Dhinwa
Tester:Misha Chorniy
Editorialist:Animesh Fatehpuria

PROBLEM

You just received a message given by a string $s$. You don't know whether this message is sent by Chef or his brother. Also, the communication channel through which you received the message is erroneous and hence can flip a letter from uppercase to lowercase or vice versa. However, you know that this channel can make at most $k$ such flips.

Chef always sends messages to his friends in all small letters, whereas the little brother sends messages in all capital letters. Determine whether the message could have been sent only by Chef, only by the little brother, by both or by none.

EXPLANATION

Number of uppercase letters <= $k$ implies that it could have been Chef. This is because we can consider all the uppercase letters as "flips" made by the communication channel, which would imply that our original message comprised only of lowercase letters. Similarly, number of lowercase letters <= $k$ implies that it could have been Chef's brother. Here is the implementation in Python:

t = int(input()) for _ in range(t): (n, k) = list(map(int, input().split(' '))) s = input() chef = sum([1 for ch in s if ch >= 'A' and ch <= 'Z']) <= k brother = sum([1 for ch in s if ch >= 'a' and ch <= 'z']) <= k if (chef and brother): print("both") elif (chef): print("chef") elif (brother): print("brother") else: print("none")

AUTHOR'S AND TESTER'S SOLUTIONS:

Author's solution can be found here.
Tester's solution can be found here.

Data Structures and Algorithms

Hi all, I need your help to make a list of most used data structures and algorithms along with their tutorials, implementation and some problems on them. It will be helpful to everyone in many ways. I request everyone to contribute to this list by providing links to tutorials, problems, etc. I will keep updating this list regularly.

  1. Binary Search :Tutorial, Problems, Tutorial, Implementation, Problem

  2. Quicksort :Tutorial, Implementation, Tutorial

  3. Merge Sort :Tutorial, Implementation, Tutorial

  4. Suffix Array :Tutorial, Tutorial, Implementation, Tutorial, Implementation, Problem, Problem

  5. Knuth-Morris-Pratt Algorithm (KMP) :Tutorial, Tutorial, Implementation, Tutorial, Problem

  6. Rabin-Karp Algorithm :Tutorial, Implementation, Tutorial, Problem, Problem

  7. Tries :Tutorial, Problems, Tutorial : I,II, Tutorial, Problem, Problem, Problem

  8. Depth First Traversal of a graph :Tutorial, Impelementation, Tutorial, Problems, Problem, Problem, Problem

  9. Breadth First Traversal of a graph :Tutorial, Impelementation, Tutorial, Problems, Problem, Problem, Problem, Flood Fill

  10. Dijkstra's Algorithm :Tutorial, Problems, Problem, Tutorial(greedy), Tutorial (with heap), Implementation, Problem, Problem

  11. Binary Indexed Tree :Tutorial, Problems, Tutorial, Original Paper, Tutorial, Tutorial, Problem, Problem,Problem, Problem, Problem, Problem, Problem

  12. Segment Tree (with lazy propagation) :Tutorial, Implementation, Tutorial, Tutorial, Problems, Implementation, Tutorial, Implementation and Various Uses, Persistent Segment Tree: I, II, problems same as BIT, Problem, Problem/HLD is used as well/

  13. Z algorithm :Tutorial, Problem, Tutorial, Tutorial, problems same as KMP.

  14. Floyd Warshall Algorithm :Tutorial, Implementation, Problem, Problem

  15. Sparse Table (LCP, RMQ) :Tutorial, Problems, Tutorial, Implementation(C++), Java implementation

  16. Heap / Priority Queue / Heapsort :Implementation, Explanation, Tutorial, Implementation, Problem, Chapter from CLRS

  17. Modular Multiplicative Inverse

  18. Binomial coefficients (nCr % M): Tutorial, Tutorial, Paper, Problem

  19. Suffix Automaton :Detailed Paper, Tutorial, Implementation (I), Tutorial, Implementation (II), Problem, Problem, Problem, Problem, Tutorial, Implementation

  20. Lowest Common Ancestor :Tutorial, Problems, Paper, Paper, Problem, Problem, Problem

  21. Counting Inversions :Divide and Conquer, Segment Tree, Fenwick Tree, Problem

  22. Euclid's Extended Algorithm

  23. Suffix Tree :Tutorial, Tutorial, Intro, Construction : I, II, Implementation, Implementation, Problem, Problem, Problem, Problem

  24. Dynamic Programming : Chapter from CLRS(essential), Tutorial, Problems, Problem, Problem, Problem, Problem, Tutorial, Problem, Problem, Problem, Longest Increasing Subsequence, Bitmask DP, Bitmask DP, Optimization, Problem, Problem, Problem, Problem, Problem, Problem, Problem, DP on Trees : I, II

  25. Basic Data Structures :Tutorial, Stack Implementation, Queue Implementation, Tutorial, Linked List Implementation

  26. Logarithmic Exponentiation

  27. Graphs :Definition, Representation, Definition, Representation, Problem, Problem

  28. Minimum Spanning Tree :Tutorial, Tutorial, Kruskal's Implementation, Prim's Implementation, Problem, Problem, Problem, Problem, Problem

  29. Efficient Prime Factorization

  30. Combinatorics :Tutorial, Problems, Problem, Tutorial

  31. Union Find/Disjoint Set :Tutorial, Tutorial, Problems, Problem, Problem, Problem

  32. Knapsack problem :Solution, Implementation

  33. Aho-Corasick String Matching Algorithm :Tutorial, Implementation, Problem, Problem, Problem, Problem

  34. Strongly Connected Components :Tutorial, Implementation, Tutorial, Problem, Problem, Problem

  35. Bellman Ford algorithm :Tutorial, Implementation, Tutorial, Implementation, Problem, Problem

  36. Heavy-light Decomposition :Tutorial, Problems, Tutorial, Implementation, Tutorial, Implementation, Implementation, Problem, Problem, Problem

  37. Convex Hull :Tutorial, Jarvis Algorithm Implementation, Tutorial with Graham scan, Tutorial, Implementation, Problem, Problem, Problem, Problem, Problem

  38. Line Intersection :Tutorial, Implementation, Tutorial, Problems

  39. Sieve of Erastothenes

  40. Interval Tree :Tutorial, Implementation, Problem, Problem, Problem, Problem, Problem, Problem, Tutorial

  41. Counting Sort

  42. Probabilities

  43. Matrix Exponentiation :Tutorial, Tutorial

  44. Network flow :(Max Flow)Tutorial : I,II, Max Flow(Ford-Fulkerson) Tutorial, Implementation, (Min Cut) Tutorial, Implementation, (Min Cost Flow)Tutorial : I,II,III, Dinic's Algorithm with Implementation, Max flow by Edmonds Karp with Implementation, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Problem

  45. K-d tree :Tutorial, Tutorial, Implementation, Problem

  46. Deque

  47. Binary Search Tree :Tutorial, Implementation, Searching and Insertion, Deletion

  48. Quick Select :Implementation, Implementation

  49. Treap/Cartesian Tree :Tutorial(detailed), Tutorial, Implementation, Uses and Problems, Problem, Problem

  50. Game Theory :Detailed Paper, Tutorial, Problems, Grundy Numbers, Tutorial with example problems - I,II,III,IV, Tutorial, Problems, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Problem, Nim

  51. STL (C++) :I,II, Crash Course

  52. Maximum Bipartite Matching

  53. Manacher's Algorithm :Implementation, Tutorial, Tutorial, Implementation, Tutorial, Implementation, Problem, Problem, Problem

  54. Miller-Rabin Primality Test : Code

  55. Stable Marriage Problem

  56. Hungarian Algorithm, Tutorial

  57. Sweep line Algorithm : I, II

  58. LCP :Tutorial, Implementation, Tutorial, Implementation

  59. Gaussian Elimination

  60. Pollard Rho Integer Factorization, problem

  61. Topological Sorting

  62. Detecting Cycles in a Graph : Directed - I, II Undirected : I

  63. Geometry : Basics, Tutorial

  64. Backtracking :N queens problem, Tug of War, Sudoku

  65. Eulerian and Hamiltonian Paths :Tutorial, Tutorial, (Eulerian Path and Cycle)Implementation, (Hamiltonian Cycle)Implementation

  66. Graph Coloring :Tutorial, Implementation

  67. Meet in the Middle :Tutorial, Implementation

  68. Arbitrary Precision Integer(BigInt), II

  69. Radix Sort, Bucket Sort

  70. Johnson's Algorithm :Tutorial, Tutorial, Implementation

  71. Maximal Matching in a General Graph :Blossom/Edmond's Algorithm, Implementation, Tutte Matrix, Problem

  72. Recursion : I,II, Towers of Hanoi with explanation

  73. Inclusion and Exclusion Principle : I, II

  74. Co-ordinate Compression

  75. Sqrt-Decomposition :Tutorial, Tutorial, Problem, Problem

  76. Link-Cut Tree :Tutorial, Wiki, Tutorial, Implementation, Problem, Problem, Problem, Problem

  77. Euler's Totient Function :Explanation, Implementation, Problems, Explanation, Problems

  78. Burnside Lemma :Tutorial, Tutorial, Problem

  79. Edit/Levenshtein Distance :Tutorial, Introduction, Tutorial, Problem, Problem

  80. Branch and Bound

  81. Math for Competitive Programming

  82. Mo's Algorithm : Tutorial and Problems

MINMAX2 - EDITORIAL

Minimum Maximum Partition

Problem Setter:Istasis Mishra

Problem Tester:Istasis Mishra

Editorialist:Taranpreet Singh

Problem:

Given two arrays P and Q of Size N and an integer K, Minimize AND maximize the cost of partitioning the range [1...N] into exactly K partitions, where cost of a partition is defined as $min(P[L...N])*max(Q[1...R])$.

Prerequisites:

Dynamic Programming - Convex Hull Optimization or Divide and Conquer Optimization(But don't worry, its not as hard as it sounds)

Solution:

Since We have cost of a partition defined as $min_{L \leq i \leq N}(P[i]) \times max_{1 \leq i \leq R}(Q[i])$, we can observe that min(P[L....N]) = min(P[L], P[L+1....N]) and max(Q[1...R]) = max(Q[1...L-1], Q[L]). This means that we can pre-calculate min(P[i..N]) as well as max(Q[1...i]) for 0<=i<=N-1.

Now, The most complicated part of this problem is that, both P and Q can also have negative values, implying that in case both min(P[L..N) and max(Q[1..R]) are negative, we may still have positive cost, thus, have to be considered for Maximum solution, otherwise if there were only positive values then there is a nice greedy solution to this.

Now, to get the correct solution that receives 36 points, there is a recurrence. Let us define a function $F$ such that $F(i, k) = \text{Making k partitions till i}$. Defining the states like this gives the clear recurrence that $F(i, k) = min_{1 \leq j \leq i}(F(j, k-1) + A[j] \times B[i])$ where A[j] is the pre-computed value of min of all P from j to N and B[i] is the max of all Q from i to N. Using this as DP, we see that we have to traverse for each i, j and k and this is an $O(N^2 \times K)$ solution and gives 36 points.

We need to optimize it, and for that, it would require us the knowledge of Convex Hull Optimization. As we can see the Dp is of the form $y = m \times x + c$.

Basically, Convex hull deals with a set of lines with slope m and y-intercept, arranged on basis of slope in a stack, Speeding up selection of j in above recurrence to O(logN) time by use of binary search, giving us a total runtime of O(N^2*logN) which will easily pass the Time Limit.

The dp optimization mentioned above is usually used once, but in our problem, we are going to maintain K hulls one for each layer of DP. As you can see, if we treat the DP as having K layers then each layer depends on the previous layer. Thus, we can see that for each k we have to calculate the answer from k-1 and then add all the calculated “lines” in the current iteration to the stack.

Also, we can see that for min we require the “slope” to be decreasing and to find the min we want the slope to be increasing. Even though, this problem can be solved using a dynamic convex hull, this could be overcome by changing the DP to be calculated from N to 1 instead of 1 to N and also changing what represents the slope and the $x$. For more details, refer to the setters implementation below.

Now, to incorporate negative values and also accommodate for equal slopes, changes are required to be made in bad function (Refer code of Acquire problem here.

Also, one of the user solved this problem using divide and Conquer optimization. Here's the link to submission.

PS:Sorry for delay, its kinda hard writing editorial for a problem you yourself haven't solved yet.

Setter's solution

C++ Implementation

Java Implementation

How to forward declare variables in Python

I would like to know how to forward declare variables in Python. I have attached a program here. Please if anyon e has time please look at it. It is a pizza ordering program. SGST and CGST are taxes in my country. I have added the taxes to the final price and it is printing the final price as well. But I want to print SGST & CGST individually ( CGST = SGST = 2.5% of final price ). Please help me if you know.

CGST = 0.025 SGST = 0.025

View Content

How to get rid of getting NZEC error while submitting solution in java?

To all who are geting NZEC, try using this format in java:

import java.io.*;
import java.util.*;

public class Main
{
    public static void main(String[] args) throws IOException
    {
        try{
            //Your Solve
        }catch(Exception e){
            return;
        }
    }
}

"I want to ask a question" - Ask them all here!

Hello guys,

As you all are aware, many times there are genuine users who wish to ask a question, but dont have karma for it. They then, have to resort to means of either asking their question in other threads, or request someone to upvote them so they can ask a question.

As we have seen last month, some fake accounts were used in malpractices in discuss, and they also gained karma by "I want to ask a question" thing. Hence, now it is becoming increasingly difficult to differentiate between genuine users, and fake users.

This thread is my solution for it. Any user, with less than 3 karma who wants to ask a question is requested to ask it here, and if the question is upto standards (meaning it needs more than those "one line answers") then we (at least I ) will convert your "answer" here into a question.

In short, post your question here, and if its a good genuine question, it will get posted as a separate question by using "Convert to question" feature.

In case your question required only 1 line answers or such, we would comment it on your question.

You guys are requested to direct any such guy (who wants to ask a question) here and not "free-upvote" them, so that we can avoid any duplicate/irrelevant questions (as questions posted here would be verified first, before converting to question).

Note to @admin - We will require your active participation and help in events related to deletion of any spam content here. Also, since only admins are ones who could delete answers, it is requested that you keep an eye out on this thread.

With Regards

Vijju123

Invitation to ACM-ICPC Asia-Kharagpur Onsite Replay Contest

Hearty Greetings!

I invite you to participate in the ACM-ICPC Asia-Kharagpur Onsite Replay Contest, which will feature the same problem sets faced by contestants at the ICPC 2017 onsite regionals.

Contest Details:
Time: (Saturday) 13th January 2018 00:00 hrs — 14th January 02:00 hrs Indian Standard Time — +5:30 GMT) — Check your timezone.
Contest link:https://www.codechef.com/KGP17ROL
Registration: You need to have a team and a CodeChef handle to participate.
Team Registration Link: https://www.codechef.com/teams/register/KGP17ROL.

For all those who are interested and do not have a CodeChef handle, are requested to register in order to participate.

Good Luck!
Hope to see you participating!


INOI 2018 discussion

Need help with a point update and range query question

Given an array of 'N' integers, I need to perform two kinds of queries :

  1. Point update : U P : Arr[u] = P
  2. Given a L,R,P I need to find the smallest number in the range [L,R] that is greater than P.

There are 'Q' queries.

This question was in a Hiring challenge on Hackerearth (Challenge is over now) so I can't provide a link to the statement. I want to know if this problem can be solved with complexity better than Q*Log^2N

help in bit manipulation question!

Programming Contest Detailed Syllabus Along with Example Problems

Competitive Programming Syllabus

Note that in general, the syllabus for Competitive Programming is open-ended. For ACM ICPC, the syllabus is not mentioned anywhere, whereas IOI syllabus is specified before the start of the contest each year. The below syllabus is kind of detailed topics from which you may face questions in competitive programming related competitions.

Geometry

String Algorithms

Substring search

Suffix Arrays

  • O(n^2 * logn) Naive method of suffix array construction
  • O(n * logn^2) method of suffix array construction
  • O(n * logn) method of suffix array construction
  • O(n) method of suffix array construction
  • O(n) LCA preprocess on Suffix Arrays to solve a variety of string problems

Suffix Trees

  • O(n) construction of Suffix trees using Ukkonon’s algorithm
  • O(n) construction of Suffix Trees if provided with Suffix Arrays using Farach's algorithm

Other

  • Suffix Automata - O(n) Suffix Automaton construction.
  • Dictionary Of Basic Factors - O(n * logn) method of DBF construction using Radix Sort.
  • Manacher’s algorithm to find length of palindromic substring of a string centered at a position for each position in the string. Runtime -> O(n).
  • Searching and preprocessing Regular Expressions consisting of '?' and '*'

Multi-dimensional pattern matching

Graphs

Basic Graphs

  • Representation of graphs as adjacency list, adjacency matrix, incidence matrix and edge list and uses of different representations in different scenarios
  • Breadth First Search (Problems - PPATH, ONEZERO, WATER on SPOJ)
  • Depth First Search
  • Strongly Connected Components (TOUR and BOTTOM on SPOJ)
  • Biconnected Components, Finding articulation points and bridges (RELINETS, PT07A on SPOJ)
  • Dijkstra algorithm (SHPATH on SPOJ)
  • Floyd Warshall algorithm (COURIER on SPOJ)
  • Minimum Spanning Tree (BLINNET on SPOJ)
  • Flood-fill algorithm
  • Topological sort
  • Bellman-Ford algorithm.
  • Euler Tour/Path (WORDS1 on SPOJ)
  • Suggested reading for most of the topics in Graph algorithms -http://www.topcoder.com/tc?module=Static&d1=tutorials&d2=graphsDataStrucs1.
  • Also refer to the tutorial for problems concerning these techniques.
  • Cormen chapter 22 to 24.

Flow networks/ matching

Dynamic Programming.

Greedy

Number Theory

Modulus arithmetic

Fermat's theorem, Euler Totient theorem (totient function, order, primitive roots)

Chinese remainder theorem

Primality tests

GCD using euclidean method

Logarithmic Exponentiation

Integer Factorization

Other

Math (Probability, Counting, Game Theory, Group Theory, Generating functions, Permutation Cycles, Linear Algebra)

Probability

Counting

Special numbers

Advanced counting techniques - Polya counting, burnsides lemma

Game theory

Linear Algebra

Matrix Operations

Matrix transformations (Transpose, Rotation of Matrix, Representing Linear transformations using matrix)

Solving system of linear equations

Using matrix exponentiation to solve recurrences

Eigen values and Eigen vectors

Polynomials

Permutation cycles

  • Suggested Reading - Art of Computer Programming by Knuth Vol. 3
  • Problems - ShuffleMethod, Permutation and WordGame on topcoder.

Group Theory (Advanced Techniques)

Generating functions

  • Suggested Reading
  • Herbert Wilf's generating functionology
  • Robert Sedgewick and Flajoulet's Combinatorial analysis

Data Structures

Basic

Singly/Doubly Linked List

Hash Tables

Circular linked list / queue

Binary/n-ary trees

Heaps

Trie

Interval trees / Segment Trees

Fenwick (Binary Indexed) trees

Disjoint data structures

Range minimum Query (RMQ)

Customized interval/segment trees (Augmented DS)

AVL Trees

Miscellaneous

  • Splay Trees
  • B/B+ Trees
  • k-d Trees
  • Red-black Trees
  • Skip List
  • Binomial/ Fibonacci heaps

Exercices

Persistent Segment Tree

Centroid Decomposition

Heavy Light Decomposition

Search Techniques/Bruteforce writing techniques/Randomized algorithms.

Backtracking (beginner)

  • N queens problems
  • Knights Tour
  • Sudoku Problem
  • Tiling Problem
  • 15 puzzle.

Dancing Links and Algorithm X given by Knuth (advanced)

Binary Search (beginner)

Ternary Search (intermediate)

Meet in the middle (Intermediate)

Hill Climbing (Advanced)

Simulated Annealing (Advanced)

Regular Iteration to reach a fixed point (Advanced)

  • Newton-Raphson method to find root of a mathematical function.
  • Iterations to solve linear non homogeneous system of equations.

Representing sets with bitmasks and manipulating bitmasks (Beginner)

General programming issues in contests

References:

https://docs.google.com/document/d/1_dc3Ifg7Gg1LxhiqMMmE9UbTsXpdRiYh4pKILYG2eA4/edit1

MAXCANDY - Editorial

Maximum Candies

Tags: Dynamic Programming, Recursion with memoization.

PROBLEM LINK :
practice

Author: Shami.
Tester: Kaustav

It may be tempting to solve this problem with greedy strategy but, as the example shows, it gives the wrong answer.

To reach (i, j), there are two options (i-1, j) or (i, j-1) (for legal values of i and j). Let’s just iterate through both of them and take the maximum.

Just don’t forget to cache the values, or it will become an exponential time algorithm!

Top Down (Recursion with memoization)

Bottom up (DP)

SHELPASS - Editorial

Sheldon Password

Problem
practice

Tags: Permutation.

Author: Shami.

This problem is a fancy way of asking to compute Kth permutation given a starting string. Since the maximum length of string is only 9, we can map the letters to digits and work with numbers (if that is more comfortable).

How to find the next permutation?

This Wiki article describes the following steps:

  1. Find the largest index k such that a[k] < a[k + 1]. If no such index exists, the permutation is the last permutation.
  2. Find the largest index l greater than k such that a[k] < a[l].
  3. Swap the value of a[k] with that of a[l].
  4. Reverse the sequence from a[k + 1] up to and including the final element a[n].

However, if you are programming in C++, you’ll be happy to know there is a function that just does that!

Equal sum partition

Equal partition: Given a set A of 40 real numbers, find out if there is any way to split A in two sets such that the sums of their elements are equal. (Hint: complexity O(2n/2))

How do I solve this problem using meet in the middle? I found it on this blog.


RTTE - Editorial

Race To The End (RTTE)

Tags: Complete Search, Shortest path in DAG.

Problem:
practice

Author: Naman.
Tester: Shami.

There are two possible approaches for this problem.

Brute force
Since the limit on N is very small, we can try all possible combinations and find the result. We can store the minimum steps to reach each index in an array (arr).

Steps:

  1. Start from index 0. a[0] = 0
  2. For each index ‘i’, we update value of a[i] = min(a[i], a[i+1]+1) we don’t need to check a[i-1] as it would already have been processed because we started from left.
  3. Find all indices j to the right such that a[j] == a[i]
    a. For each j, update all left indices similar to step #2.
  4. Answer is stored in a[N-1].

Graph

Let’s consider each index ‘i’ as a node and all possible moves as directed edges. So the edges from A[i] will be
1. A[i-1]
2. A[i+1]
3. All A[j] such that A[j] == A[i]

Complexity to generate graph: O(N^2)

Notice that the directed graph may have back edges, but it does not matter in our case. Now we can apply BFS starting from index 0 and count the minimum number of levels to reach N. The number of levels is the answer.

KEYPAD - Editorial

Crack the passcode

Problem :
practice

Tags: Mathematics, Brute force.

Author: Kaustav
Tester: Murali

There are many ways to approach this such as iterating over 2 dimensional keypad for the paths satisfying the Manhattan length constraint of 5 and printing the corresponding code and eliminating the case where there are unwanted characters. Also an adjacency array for every key of the keypad can be created and can be traversed to get all the possible solution paths with the given constraint.

AGNSJUMP - Editorial

Agnes Jump

Problem :
practice

Tags: Dynamic Programming, Recursion with memoization.

Author: Shami.

Tester: Murali, Kaustav

This is just an extension of Fibonacci sequence with extra memory and different initial conditions.

How many ways can we get to N? We can reach N from N-1, N-2 and N-3 (those are the allowed step/jump sizes). If we denote number of ways of reaching N by F(N)

                 F(N) = F(N-1) + F(N-2) + F(N-3)

All we need to do now is initialize the values of F(1), F(2) and F(3) (these are given in the examples) and just implement a recursive function.

Let’s examine the order of the algorithm: For each i (1 <= i <= N), we call 3 recursive functions, each of which make another 3 recursive calls. This is asymptotically 3^N for computing N.

For SubTask1, N = 10, 3^10 ~= 6x10^4. T = 10
So total computations are 6x10^5 < 10^7 (you can do roughly 10^7 calculations per second)
This is good enough to pass our time limit of 1s.

For SubTask2, N = 1000. 3^1000 is indeed a large number, so this is not good enough.

But notice that to calculate F(i), we need to calculate F(i-1), F(i-2) and F(i-3) again. And again! This is clearly not needed. Let’s just cache these values.

Let’s take an array of size N and store the number of ways for each i. Take an array of size N and keep storing the values of each i as and when we compute it.

This is a linear order algorithm, so complexity is NT = 10001000 = 10^6.

Now for SubTask3, we have an upper bound on N = 10^6 and T = 10^6. Even with linear algorithm, the complexity is 10^6*10^6 = 10^12. Clearly TLE! Also, a recursive solution may run out of stack depending on the settings.

But we don’t really need to compute F(N) for each T. We can just calculate F(1000000) and store it in an array and just do a plain look up. Complexity is 10^6 + 10^6 = O(10^6).

HAPPYARR - Editorial

Happy Array

Problem :
practice

Tags: Dynamic Programming, Prefix sum.

Author: Shami.
Tester: Naman

There are multiple ways to look at this problem.

1.Longest Increasing Subsequence A sequence (not necessarily contiguous) with leading 0s and (possibly) ending with 1s is essentially a weakly increasing subsequence. As such, we can compute the LIS for the array that will give you the answer.

This problem had weak testcases, which allowed O(N^2) LIS solutions to be accepted. However, LIS can be computed in O(Nlog(K)) as well.

2.For each 0, the longest length of happy array is, at least, number of 0s to the left (including itself) and number of 1s to the right. We can use prefix sums to compute the number of 1s at each index and use it to compute the longest possible happy array for each 0. Not using prefix sum array will cause this algorithm to degenerate to O(N^2), which is same as above.

TRIPLET2 - Editorial

Queer Triplets

Problem:
practice

Tags: Number Theory

Author: Kaustav.
Tester: Shami.

This problem is a trick question. If you were to solve it with brute force taking the question too seriously you will time out. Here is the solution

Yes, the bounds of 10^18 (later reduced to 10^16) will not let you converge in time for the solution. You have to figure out the actual bound of I,j and k to compute them in time. Even if you were to pick lesser constraining bound say 100 you would have got the solution. The bounds you compute are 2 <= i,j,k <= 11. The way you go about is that if you are to notice ii-k, kj-I and j*i-k are symmetric where every permutation of the i,j, and k has to satisfy the constraint. Hence if you are to only consider the i<=j<=k go and plug i=0,1,2,… you will soon discover that the bound on i is 2<=i<=3. You then move the analysis to discover bounds of j to be actually bounded by only 2 and 5 and k to be only 2 and 11. Given this bound just run to see the satisfiability of the the constraints and you will have the all of the solution.

Viewing all 40121 articles
Browse latest View live


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